diff --git a/DEPLOY.md b/DEPLOY.md new file mode 100644 index 00000000..9c40f593 --- /dev/null +++ b/DEPLOY.md @@ -0,0 +1,737 @@ +# DEPLOY.md - 手动部署 paper + live copybot 到新服务器 + +> 一步一步来,可以一边看一边敲。不要一次性复制粘贴大段命令--每一步做完、看到预期输出,再进下一步。 +> +> 适用:把 paper bot + live bot 部署到一台新的 Linux 服务器(Ubuntu/Debian),从你自己的 Gitea 拉代码。如果服务器在 Polymarket 禁单地区(美国/英国/法国等),用 mihomo 代理绕开 geo-block。 +> +> 完成时间参考:60-90 分钟(含每步等待 + live 配置)。 +> +> 完成部署后提供: +> - **paper bot**:24/7 模拟跟单(直连,不走代理) +> - **live bot**:24/7 真钱跟单(走代理绕 geo-block) +> - **bot 实时账本(中文 web dashboard)**:`http://服务器IP:18080/` +> - **原始 JSON**:`https:////winning-wallet-finder/raw/branch/main/live/copybot_live.json` + +--- + +## 目录 + +- [Part A: Paper Bot 部署](#part-a-paper-bot-部署) (§0-§13) +- [Part B: 代理配置(geo-block 绕行)](#part-b-代理配置geo-block-绕行) (§14-§16) +- [Part C: Live Bot 部署](#part-c-live-bot-部署) (§17-§23) +- [常见坑](#常见坑) +- [日常命令](#日常用的命令) + +--- + +# Part A: Paper Bot 部署 + +## 0. 前置条件 + +- [ ] 一台 Linux VPS(Ubuntu 20.04+ / Debian 11+) +- [ ] 你有 root SSH 权限 +- [ ] 你的 Gitea 上有这个仓库的镜像 +- [ ] Gitea PAT(权限 `repository: Write`) + +测 Polymarket 直连: + +```bash +python3 -c " +import urllib.request, time +for url in [ + 'https://data-api.polymarket.com/v1/leaderboard?limit=1', + 'https://gamma-api.polymarket.com/markets?limit=1', + 'https://clob.polymarket.com/markets?next_cursor=', +]: + t = time.time() + try: + urllib.request.urlopen(urllib.request.Request(url, headers={'User-Agent':'Mozilla/5.0'}), timeout=10) + print(f'OK {(time.time()-t)*1000:6.0f}ms {url}') + except Exception as e: + print(f'FAIL {type(e).__name__}: {url}') +" +``` + +三行 `OK` = 能读 API(paper 够用)。 + +## 1. 装基础依赖 + +```bash +ssh root@你的服务器IP +apt-get update +apt-get install -y git python3 python3-pip ca-certificates +``` + +## 2. 从 Gitea 拉代码 + +```bash +cd /opt +git clone https://:@//winning-wallet-finder.git +cd winning-wallet-finder/live +``` + +## 3. 装 duckdb + 首次回测 + +```bash +pip3 install duckdb --break-system-packages +python3 portfolio.py --days 30 +``` + +预期:`portfolio[30d rolling]: equity $... | ... | -> portfolio.json` + +## 4. 前台测试 bot + +```bash +python3 ../copybot.py --config copybot.paper.json --state copybot_state.json --poll 60 +``` + +看到 `watching N wallets` + 2-3 条心跳后 `Ctrl+C`。 + +## 5. 配 Gitea 凭证 + +### 5.1 生成 PAT + +Gitea -> 用户设置 -> Applications -> Generate Token(权限 `repository: Write`) + +### 5.2 写 .netrc + +```bash +nano ~/.netrc +``` + +``` +machine +login +password +``` + +```bash +chmod 600 ~/.netrc +cd /opt/winning-wallet-finder +git push origin main --dry-run +``` + +### 5.3 root git 白名单 + +```bash +git config --global --add safe.directory /opt/winning-wallet-finder +``` + +## 6. 建专用用户 wwf + +```bash +useradd --system --shell /usr/sbin/nologin --home /opt/winning-wallet-finder wwf +chown -R wwf:wwf /opt/winning-wallet-finder +chmod -R u+rwX,g+rX,o-rwx /opt/winning-wallet-finder +sudo cp /root/.netrc /opt/winning-wallet-finder/.netrc +sudo chown wwf:wwf /opt/winning-wallet-finder/.netrc +sudo chmod 600 /opt/winning-wallet-finder/.netrc +sudo -u wwf git config --global user.name "copybot[bot]" +sudo -u wwf git config --global user.email "copybot@wwf.local" +``` + +> **坑**:wwf 没配 git identity 会导致 commit 报 `Author identity unknown`。上面最后两行不能漏。 + +## 7. 写 paper systemd unit + +```bash +cat > /etc/systemd/system/copybot-paper.service <<'EOF' +[Unit] +Description=Polymarket Paper Copybot +After=network-online.target +Wants=network-online.target + +[Service] +Type=simple +User=wwf +Group=wwf +WorkingDirectory=/opt/winning-wallet-finder/live +ExecStart=/usr/bin/python3 /opt/winning-wallet-finder/copybot.py \ + --config /opt/winning-wallet-finder/live/copybot.paper.json \ + --state /opt/winning-wallet-finder/copybot_state.json \ + --poll 60 + +Restart=always +RestartSec=10 +TimeoutStopSec=30 +Nice=5 + +StandardOutput=journal +StandardError=journal +SyslogIdentifier=copybot-paper + +EnvironmentFile=-/etc/copybot/paper.env + +NoNewPrivileges=true +ProtectSystem=strict +ProtectHome=true +PrivateTmp=true +PrivateDevices=true +RestrictSUIDSGID=true +RestrictNamespaces=true +LockPersonality=true +RestrictRealtime=true +ProtectKernelTunables=true +ProtectKernelModules=true +ProtectControlGroups=true +SystemCallArchitectures=native +ReadWritePaths=/opt/winning-wallet-finder + +[Install] +WantedBy=multi-user.target +EOF +``` + +## 8. 启动 paper bot + +```bash +systemctl daemon-reload +systemctl enable --now copybot-paper +sleep 5 +systemctl status copybot-paper +``` + +## 9. 验证 Gitea 推送 + +```bash +cd /opt/winning-wallet-finder +sudo -u wwf git add -A +sudo -u wwf git commit -m "manual sync" +sudo -u wwf git push +``` + +## 10. 加 Alchemy RPC + +```bash +sudo install -d -m 750 -o wwf -g wwf /etc/copybot +sudo tee /etc/copybot/paper.env > /dev/null < 北京 10:00 = cron 0 2 +(crontab -l 2>/dev/null; echo "0 2 * * * cd /opt/winning-wallet-finder/live && bash daily.sh >> daily.log 2>&1") | crontab - +``` + +## 12. 部署 web dashboard + +```bash +cat > /etc/systemd/system/copybot-dashboard.service <<'EOF' +[Unit] +Description=Polymarket Copybot Live Dashboard +After=network-online.target +Wants=network-online.target + +[Service] +Type=simple +User=wwf +Group=wwf +WorkingDirectory=/opt/winning-wallet-finder/live +ExecStart=/usr/bin/python3 /opt/winning-wallet-finder/live/serve_dashboard.py +Restart=always +RestartSec=5 +Nice=10 + +StandardOutput=journal +StandardError=journal +SyslogIdentifier=copybot-dashboard + +NoNewPrivileges=true +ProtectSystem=strict +ProtectHome=true +PrivateTmp=true +PrivateDevices=true +RestrictNamespaces=true + +[Install] +WantedBy=multi-user.target +EOF + +systemctl daemon-reload +systemctl enable --now copybot-dashboard +sleep 3 +curl -s http://localhost:18080/api/feed | python3 -m json.tool | head -10 +``` + +浏览器访问 `http://服务器IP:18080/`。如果打不开,放行防火墙 TCP 18080。 + +## 13. Paper 完成检查 + +- [x] paper bot systemd 24/7 跑 +- [x] web dashboard @ :18080 +- [x] Alchemy RPC ON +- [x] 状态推 Gitea +- [x] 每日 cron + +--- + +# Part B: 代理配置(geo-block 绕行) + +> **为什么要代理**:Polymarket 禁止美国/英国/法国/德国/意大利/荷兰/波兰/新加坡/澳大利亚/加拿大安大略/巴西 等地区的 IP 下单。如果你的服务器在这些地区,live bot 需要走代理。 +> +> paper bot 不受影响(只读 API 全球开放)。 + +## 14. 检查 geo-gate + +```bash +cd /opt/winning-wallet-finder +python3 host/geocheck.py +``` + +- `VERDICT: TRADABLE` -> 跳过 Part B,直接去 Part C +- `VERDICT: BLOCKED` -> 继续往下配代理 + +## 15. 装 mihomo(Clash Meta 内核) + +### 15.1 下载 mihomo + +```bash +mkdir -p /etc/mihomo +cd /tmp +wget -q https://github.com/MetaCubeX/mihomo/releases/download/v1.19.0/mihomo-linux-amd64-v1.19.0.gz +gzip -d mihomo-linux-amd64-v1.19.0.gz +mv mihomo-linux-amd64-v1.19.0 /usr/local/bin/mihomo +chmod +x /usr/local/bin/mihomo +mihomo -v +``` + +### 15.2 拉订阅配置 + +> **坑**:机场会检测 User-Agent,wget 默认 UA 会被返回假节点。必须伪装 UA。 + +```bash +wget -O /etc/mihomo/config.yaml \ + --user-agent="clash-verge/v1.7.7" \ + "你的订阅链接&flag=meta" +``` + +验证拿到的是真实节点(不是"当前Clash客户端不支持本机场协议"): + +```bash +grep "name:" /etc/mihomo/config.yaml | grep -i "日本\|香港\|新加坡" | head -10 +``` + +### 15.3 改全局模式 + 启动 + +```bash +sed -i 's/^mode: rule/mode: global/' /etc/mihomo/config.yaml + +nohup mihomo -d /etc/mihomo > /var/log/mihomo.log 2>&1 & +sleep 5 + +# 选一个非美国节点(以日本为例) +curl -s -X PUT http://127.0.0.1:9090/proxies/GLOBAL \ + -H "Content-Type: application/json" \ + -d '{"name":"节点名"}' + +# 验证 +HTTPS_PROXY=http://127.0.0.1:7890 python3 host/geocheck.py +``` + +期望 `VERDICT: TRADABLE`。 + +### 15.4 做 systemd 服务 + +```bash +kill $(pgrep mihomo) + +cat > /etc/systemd/system/mihomo.service <<'EOF' +[Unit] +Description=Mihomo (Clash Meta) Proxy +After=network-online.target +Wants=network-online.target + +[Service] +Type=simple +ExecStart=/usr/local/bin/mihomo -d /etc/mihomo +Restart=always +RestartSec=5 +StandardOutput=journal +StandardError=journal +SyslogIdentifier=mihomo +NoNewPrivileges=true + +[Install] +WantedBy=multi-user.target +EOF + +systemctl daemon-reload +systemctl enable --now mihomo +sleep 5 + +# 重选节点(mihomo 重启会记住,但第一次要手动选) +curl -s -X PUT http://127.0.0.1:9090/proxies/GLOBAL \ + -H "Content-Type: application/json" \ + -d '{"name":"节点名"}' + +# 验证代理 + geo-gate +HTTPS_PROXY=http://127.0.0.1:7890 python3 host/geocheck.py | tail -1 +``` + +> **mihomo 会记住节点选择**:`cache.db` 持久化,重启不丢。 + +### 15.5 自动健康检查(节点挂了自动换) + +```bash +cat > /opt/mihomo-healthcheck.sh <<'SCRIPT' +#!/bin/bash +API="http://127.0.0.1:9090" +PROXY="http://127.0.0.1:7890" +code=$(curl -s -o /dev/null -w "%{http_code}" --max-time 10 -x $PROXY \ + "https://clob.polymarket.com/markets?next_cursor=" 2>/dev/null) +if [ "$code" = "200" ]; then exit 0; fi +nodes=$(curl -s "$API/proxies" | python3 -c " +import sys, json +d = json.load(sys.stdin) +skip = {'DIRECT','REJECT','自动选择','故障转移','良心云','GLOBAL'} +for name, info in d.get('proxies', {}).items(): + if name in skip: continue + if info.get('type') in ('Selector','URLTest','Fallback','LoadBalance'): continue + if any(k in name for k in ['美国','US','United States']): continue + print(name) +") +for node in $nodes; do + curl -s -X PUT "$API/proxies/GLOBAL" -H "Content-Type: application/json" -d "{\"name\":\"$node\"}" > /dev/null + sleep 2 + code=$(curl -s -o /dev/null -w "%{http_code}" --max-time 10 -x $PROXY \ + "https://clob.polymarket.com/markets?next_cursor=" 2>/dev/null) + if [ "$code" = "200" ]; then + logger "mihomo-healthcheck: switched to $node" + exit 0 + fi +done +logger "mihomo-healthcheck: ALL nodes failed" +exit 1 +SCRIPT + +chmod +x /opt/mihomo-healthcheck.sh +(crontab -l 2>/dev/null | grep -v mihomo-healthcheck; echo "*/5 * * * * /opt/mihomo-healthcheck.sh") | crontab - +``` + +> **代理只影响 live bot**:mihomo 监听 `127.0.0.1:7890`,不是透明代理。只有设了 `HTTPS_PROXY` 的程序才走代理。paper bot / dashboard / Gitea 全部直连,不受影响。 +> +> **不要**把 `HTTPS_PROXY` 写进 `/etc/environment` 或 `~/.bashrc`(会全局生效),只放在 `/etc/copybot/live.env` 里。 + +--- + +# Part C: Live Bot 部署 + +> **真钱!** 每一步验证完再进下一步。建议先 $3-5 测试。 + +## 17. 装 live 依赖 + +```bash +pip3 install py-clob-client==0.34.6 web3==7.16.0 polymarket-client==0.1.0b16 websocket-client --break-system-packages +``` + +> **坑**:`preflight_live.py` 需要 `polymarket-client`(不是 `py-clob-client`),漏装会报 `ModuleNotFoundError: No module named 'polymarket'`。 + +## 18. 准备钱包 + +### 18.1 钱包架构说明 + +Polymarket 2026 新架构有两套钱包系统: + +``` +你的私钥(MetaMask 导出) + | + +-- EOA 地址(MetaMask 本身) + +-- 代理钱包(邮箱登录自动创建,POLY_PROXY type=1) + +-- 存款钱包(API 自动创建,POLY_1271 type=3)<- bot 用这个 +``` + +**bot 只能用存款钱包**。pUSD 在 EOA 或代理钱包里 bot 看不到。 + +### 18.2 用 MetaMask 登录(推荐,比邮箱简单) + +1. 浏览器装 MetaMask,创建新钱包 +2. 用 MetaMask 登录 polymarket.com +3. MetaMask -> 账户详情 -> 导出私钥 + +### 18.3 创建存款钱包 + +```bash +cd /opt/winning-wallet-finder +export HTTPS_PROXY=http://127.0.0.1:7890 +export LIVE_PRIVATE_KEY=0x你的MetaMask私钥 + +python3 -c " +from polymarket import SecureClient +client = SecureClient.create(private_key='$LIVE_PRIVATE_KEY') +print('存款钱包:', client.wallet) +b = client.get_balance_allowance(asset_type='COLLATERAL') +print('pUSD 余额: \$' + str(b.balance / 1e6)) +client.close() +" +``` + +> **坑(邮箱登录用户)**:如果用邮箱登录的私钥(Magic.link 导出),`SecureClient.create()` 会报 `Gasless transactions require a Builder API Key`。需要用 Builder API 凭证创建存款钱包: +> ```python +> bk = BuilderApiKey(key=..., secret=..., passphrase=...) +> client = SecureClient.create(private_key=pk, api_key=bk) +> ``` +> Builder 凭证在 polymarket.com -> Settings -> API Keys 获取。创建完存款钱包后不再需要 Builder 凭证。 +> +> **MetaMask 登录用户不受此影响**,存款钱包自动创建。 + +### 18.4 充值 USDC -> pUSD + +**关键**:必须充到**存款钱包地址**,不是 MetaMask 地址。 + +1. 从交易所提 USDC 到 Polygon 链 +2. 接收地址 = 步骤 18.3 打印的存款钱包地址 +3. 到账后 USDC 自动转成 pUSD + +> **坑**:充到 Polymarket 网站显示的充值地址(代理钱包)是错的,bot 在存款钱包里看不到。必须充到存款钱包地址。 + +### 18.5 验证余额 + +```bash +export HTTPS_PROXY=http://127.0.0.1:7890 +export LIVE_PRIVATE_KEY=0x你的私钥 +python3 -c " +from polymarket import SecureClient +client = SecureClient.create(private_key='$LIVE_PRIVATE_KEY') +b = client.get_balance_allowance(asset_type='COLLATERAL') +print('pUSD: \$' + str(b.balance / 1e6)) +client.close() +" +``` + +## 19. 创建 config.live.json + +```bash +cd /opt/winning-wallet-finder +cp config.live.example.json config.live.json +# 改 bankroll_usd 为实际 pUSD 余额 +sed -i 's/"bankroll_usd": 22.28/"bankroll_usd": 你的余额/' config.live.json +chown wwf:wwf config.live.json +chmod 640 config.live.json +``` + +> **坑**:config.live.json 是 root 创建的,wwf 用户读不了会报 `PermissionError`。必须 `chown wwf:wwf`。 + +## 20. 创建 live.env + +```bash +cat > /etc/copybot/live.env <<'EOF' +LIVE_PRIVATE_KEY=0x你的MetaMask私钥 +LIVE_FUNDER_ADDRESS=0x你的MetaMask地址 +LIVE_SIGNATURE_TYPE=1 +LIVE_CONFIRM=TRADE LIVE +HTTPS_PROXY=http://127.0.0.1:7890 +EOF + +chown wwf:wwf /etc/copybot/live.env +chmod 600 /etc/copybot/live.env +``` + +> **坑 1**:`LIVE_CONFIRM` 的值必须是 `TRADE LIVE`(copytrade.py:48 的 `CONFIRM_PHRASE`),不是 `I understand real money is at risk`。填错会报 `Aborted - LIVE_CONFIRM is set but does not match the phrase`。 +> +> **坑 2**:systemd EnvironmentFile 里值**不要加引号**。`LIVE_CONFIRM=TRADE LIVE` 是对的,`LIVE_CONFIRM="TRADE LIVE"` 会让值带引号导致不匹配。 +> +> **坑 3**:`HTTPS_PROXY` 只在 live.env 里设,不要放 paper.env(paper bot 不需要代理)。 + +## 21. 跑 preflight + +```bash +cd /opt/winning-wallet-finder +export LIVE_PRIVATE_KEY=$(grep LIVE_PRIVATE_KEY /etc/copybot/live.env | cut -d= -f2-) +export LIVE_FUNDER_ADDRESS=$(grep LIVE_FUNDER_ADDRESS /etc/copybot/live.env | cut -d= -f2-) +export HTTPS_PROXY=http://127.0.0.1:7890 +python3 preflight_live.py +``` + +全绿才能继续。常见失败: +- `ModuleNotFoundError: No module named 'websocket'` -> `pip3 install websocket-client` +- `Gasless transactions require a Builder API Key` -> 见 §18.3 邮箱登录的坑 +- `Invalid private_key: 'ascii' codec can't encode` -> 私钥里有非 ASCII 字符(中文占位符没替换) + +## 22. 写 live systemd unit + +```bash +cat > /etc/systemd/system/copybot-live.service <<'EOF' +[Unit] +Description=Polymarket LIVE Copybot (real money) +After=network-online.target mihomo.service +Wants=network-online.target +Requires=mihomo.service + +[Service] +Type=simple +User=wwf +Group=wwf +WorkingDirectory=/opt/winning-wallet-finder/live +ExecStart=/usr/bin/python3 /opt/winning-wallet-finder/copybot.py \ + --config /opt/winning-wallet-finder/config.live.json \ + --state /opt/winning-wallet-finder/copybot_state.live.json \ + --poll 60 --live + +Restart=always +RestartSec=10 +TimeoutStopSec=30 +Nice=5 + +StandardOutput=journal +StandardError=journal +SyslogIdentifier=copybot-live + +EnvironmentFile=/etc/copybot/live.env + +NoNewPrivileges=true +ProtectSystem=strict +ProtectHome=true +PrivateTmp=true +PrivateDevices=true +RestrictSUIDSGID=true +RestrictNamespaces=true +LockPersonality=true +RestrictRealtime=true +ProtectKernelTunables=true +ProtectKernelModules=true +ProtectControlGroups=true +SystemCallArchitectures=native +ReadWritePaths=/opt/winning-wallet-finder + +[Install] +WantedBy=multi-user.target +EOF +``` + +> `Requires=mihomo.service` + `After=mihomo.service`:代理先启动,live bot 才启动。 + +## 23. 启动 live bot + +```bash +systemctl daemon-reload +systemctl enable --now copybot-live +sleep 10 +journalctl -u copybot-live --since "15 seconds ago" --no-pager +``` + +预期看到: + +``` +geo-gate: TRADABLE - order endpoint reachable +LIVE MODE - this will place REAL orders with REAL money. +confirmed via LIVE_CONFIRM env - armed. +mode: LIVE - REAL MONEY +watching 5 wallets +``` + +### 清空 live state(如果出现 LEDGER DRIFT) + +```bash +systemctl stop copybot-live +rm -f /opt/winning-wallet-finder/copybot_state.live.json +rm -f /opt/winning-wallet-finder/copybot_fills.live.jsonl +rm -f /opt/winning-wallet-finder/live/copybot_live_real.json +systemctl start copybot-live +``` + +### 监控第一笔成交 + +```bash +journalctl -u copybot-live -f +``` + +看到 `FOLLOW` + `[LIVE] order placed` = 第一笔真钱成交。然后去 polymarket.com 用 MetaMask 登录确认仓位。 + +--- + +# 完整部署架构 + +``` +服务器 +| ++-- mihomo.service 代理(日本节点,127.0.0.1:7890) +| +-- healthcheck cron 每 5 分钟自动换节点 +| ++-- copybot-paper.service paper bot(直连,不走代理) +| +-- EnvironmentFile: paper.env(ALCHEMY_RPC_URL) +| +-- state: copybot_state.json +| +-- feed: live/copybot_live.json +| ++-- copybot-live.service live bot(走代理绕 geo-block) +| +-- EnvironmentFile: live.env(LIVE_PRIVATE_KEY + HTTPS_PROXY + TRADE LIVE) +| +-- state: copybot_state.live.json +| +-- feed: live/copybot_live_real.json +| ++-- copybot-dashboard.service web dashboard(:18080) +| ++-- cron 每日 02:00 UTC daily.sh +``` + +--- + +# 常见坑 + +| 坑 | 症状 | 解法 | +| --- | --- | --- | +| 没装 duckdb | `ModuleNotFoundError: No module named 'duckdb'` | `pip3 install duckdb --break-system-packages` | +| 没装 polymarket-client | `ModuleNotFoundError: No module named 'polymarket'` | `pip3 install polymarket-client==0.1.0b16` | +| 没装 websocket-client | preflight 报 `No module named 'websocket'` / 日志 `rtds off` | `pip3 install websocket-client` | +| wwf 没配 git identity | commit 报 `Author identity unknown` | §6 最后两行 | +| root 看不到 wwf 仓库 | `dubious ownership` | `git config --global --add safe.directory ...` | +| config.live.json 权限 | `PermissionError: [Errno 13]` | `chown wwf:wwf config.live.json` | +| LIVE_CONFIRM 值错 | `Aborted - LIVE_CONFIRM is set but does not match` | 值必须是 `TRADE LIVE`,不加引号 | +| 私钥有非 ASCII 字符 | `UnicodeEncodeError: 'ascii' codec can't encode` | env 文件里私钥必须是纯 hex(0x + 64 位),不能有中文占位符 | +| 邮箱登录建存款钱包失败 | `Gasless transactions require a Builder API Key` | 用 Builder API 凭证创建(§18.3),或改用 MetaMask 登录 | +| 充错钱包 | bot 余额 $0 | 必须充到存款钱包地址,不是 MetaMask 地址或网站充值地址 | +| geo-gate BLOCKED | `VERDICT: BLOCKED` | 服务器在禁单区,需配代理(Part B) | +| 机场返回假节点 | 节点名是"当前Clash客户端不支持" | wget 加 `--user-agent="clash-verge/v1.7.7"` + `&flag=meta` | +| mihomo 重启丢节点 | 出口 IP 变回美国 | mihomo cache.db 自动记忆;第一次需手动选节点 | +| LEDGER DRIFT | `check_book could not attribute it` | 清空 live state 重来(§23) | +| bot 不自动 commit | dashboard 数据陈旧 | commit-on-change 节流,无新交易不写;手动 commit 见 §9 | +| 浏览器 dashboard 不更新 | 数据没变 | `Ctrl+Shift+R` 强制刷新 | +| cron 时区错 | daily.sh 时间不对 | 服务器 UTC,北京 10:00 = cron `0 2` | +| 防火墙挡 18080 | 浏览器打不开 dashboard | 放行 TCP 18080 | + +--- + +# 日常用的命令 + +```bash +# === 看日志 === +journalctl -u copybot-paper -f # paper bot +journalctl -u copybot-live -f # live bot +journalctl -u copybot-dashboard -f # dashboard +journalctl -u mihomo -f # 代理 + +# === 看 dashboard === +# 浏览器:http://服务器IP:18080/ + +# === 改配置 === +nano /opt/winning-wallet-finder/live/copybot.paper.json # paper 跟单钱包/金额 +sudo systemctl restart copybot-paper + +nano /opt/winning-wallet-finder/config.live.json # live 跟单钱包/金额 +sudo systemctl restart copybot-live + +# === 代理管理 === +# 看当前节点 +curl -s http://127.0.0.1:9090/proxies/GLOBAL | python3 -c "import sys,json;print(json.load(sys.stdin).get('now'))" +# 换节点 +curl -s -X PUT http://127.0.0.1:9090/proxies/GLOBAL -H "Content-Type: application/json" -d '{"name":"节点名"}' +# 手动健康检查 +/opt/mihomo-healthcheck.sh + +# === 停/启动 === +sudo systemctl stop copybot-live # 停 live(真钱!) +sudo systemctl start copybot-live +sudo systemctl stop copybot-paper # 停 paper +sudo systemctl stop mihomo # 停代理(live 也会停) + +# === 完全卸载 === +sudo systemctl disable --now copybot-paper copybot-live copybot-dashboard mihomo +sudo rm /etc/systemd/system/copybot-*.service /etc/systemd/system/mihomo.service +sudo userdel wwf +rm -rf /opt/winning-wallet-finder +``` diff --git a/PolymarketDocumentation-main/.gitignore b/PolymarketDocumentation-main/.gitignore new file mode 100644 index 00000000..b7faf403 --- /dev/null +++ b/PolymarketDocumentation-main/.gitignore @@ -0,0 +1,207 @@ +# Byte-compiled / optimized / DLL files +__pycache__/ +*.py[codz] +*$py.class + +# C extensions +*.so + +# Distribution / packaging +.Python +build/ +develop-eggs/ +dist/ +downloads/ +eggs/ +.eggs/ +lib/ +lib64/ +parts/ +sdist/ +var/ +wheels/ +share/python-wheels/ +*.egg-info/ +.installed.cfg +*.egg +MANIFEST + +# PyInstaller +# Usually these files are written by a python script from a template +# before PyInstaller builds the exe, so as to inject date/other infos into it. +*.manifest +*.spec + +# Installer logs +pip-log.txt +pip-delete-this-directory.txt + +# Unit test / coverage reports +htmlcov/ +.tox/ +.nox/ +.coverage +.coverage.* +.cache +nosetests.xml +coverage.xml +*.cover +*.py.cover +.hypothesis/ +.pytest_cache/ +cover/ + +# Translations +*.mo +*.pot + +# Django stuff: +*.log +local_settings.py +db.sqlite3 +db.sqlite3-journal + +# Flask stuff: +instance/ +.webassets-cache + +# Scrapy stuff: +.scrapy + +# Sphinx documentation +docs/_build/ + +# PyBuilder +.pybuilder/ +target/ + +# Jupyter Notebook +.ipynb_checkpoints + +# IPython +profile_default/ +ipython_config.py + +# pyenv +# For a library or package, you might want to ignore these files since the code is +# intended to run in multiple environments; otherwise, check them in: +# .python-version + +# pipenv +# According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control. +# However, in case of collaboration, if having platform-specific dependencies or dependencies +# having no cross-platform support, pipenv may install dependencies that don't work, or not +# install all needed dependencies. +#Pipfile.lock + +# UV +# Similar to Pipfile.lock, it is generally recommended to include uv.lock in version control. +# This is especially recommended for binary packages to ensure reproducibility, and is more +# commonly ignored for libraries. +#uv.lock + +# poetry +# Similar to Pipfile.lock, it is generally recommended to include poetry.lock in version control. +# This is especially recommended for binary packages to ensure reproducibility, and is more +# commonly ignored for libraries. +# https://python-poetry.org/docs/basic-usage/#commit-your-poetrylock-file-to-version-control +#poetry.lock +#poetry.toml + +# pdm +# Similar to Pipfile.lock, it is generally recommended to include pdm.lock in version control. +# pdm recommends including project-wide configuration in pdm.toml, but excluding .pdm-python. +# https://pdm-project.org/en/latest/usage/project/#working-with-version-control +#pdm.lock +#pdm.toml +.pdm-python +.pdm-build/ + +# pixi +# Similar to Pipfile.lock, it is generally recommended to include pixi.lock in version control. +#pixi.lock +# Pixi creates a virtual environment in the .pixi directory, just like venv module creates one +# in the .venv directory. It is recommended not to include this directory in version control. +.pixi + +# PEP 582; used by e.g. github.com/David-OConnor/pyflow and github.com/pdm-project/pdm +__pypackages__/ + +# Celery stuff +celerybeat-schedule +celerybeat.pid + +# SageMath parsed files +*.sage.py + +# Environments +.env +.envrc +.venv +env/ +venv/ +ENV/ +env.bak/ +venv.bak/ + +# Spyder project settings +.spyderproject +.spyproject + +# Rope project settings +.ropeproject + +# mkdocs documentation +/site + +# mypy +.mypy_cache/ +.dmypy.json +dmypy.json + +# Pyre type checker +.pyre/ + +# pytype static type analyzer +.pytype/ + +# Cython debug symbols +cython_debug/ + +# PyCharm +# JetBrains specific template is maintained in a separate JetBrains.gitignore that can +# be found at https://github.com/github/gitignore/blob/main/Global/JetBrains.gitignore +# and can be added to the global gitignore or merged into this file. For a more nuclear +# option (not recommended) you can uncomment the following to ignore the entire idea folder. +#.idea/ + +# Abstra +# Abstra is an AI-powered process automation framework. +# Ignore directories containing user credentials, local state, and settings. +# Learn more at https://abstra.io/docs +.abstra/ + +# Visual Studio Code +# Visual Studio Code specific template is maintained in a separate VisualStudioCode.gitignore +# that can be found at https://github.com/github/gitignore/blob/main/Global/VisualStudioCode.gitignore +# and can be added to the global gitignore or merged into this file. However, if you prefer, +# you could uncomment the following to ignore the entire vscode folder +# .vscode/ + +# Ruff stuff: +.ruff_cache/ + +# PyPI configuration file +.pypirc + +# Cursor +# Cursor is an AI-powered code editor. `.cursorignore` specifies files/directories to +# exclude from AI features like autocomplete and code analysis. Recommended for sensitive data +# refer to https://docs.cursor.com/context/ignore-files +.cursorignore +.cursorindexingignore + +# Marimo +marimo/_static/ +marimo/_lsp/ +__marimo__/ diff --git a/PolymarketDocumentation-main/CRON.md b/PolymarketDocumentation-main/CRON.md new file mode 100644 index 00000000..e08b87b8 --- /dev/null +++ b/PolymarketDocumentation-main/CRON.md @@ -0,0 +1,69 @@ +# Polymarket Documentation - Daily Update Instructions for AI Agent + +## Mission +Your task is to check for updates to the Polymarket documentation and push any changes to the GitHub repository daily. + +## What You Are +You are an AI assistant responsible for keeping the Polymarket documentation synchronized with the official docs.polymarket.com website. + +## When to Run +Execute this task once per day. Choose a consistent time (e.g., early morning your time). + +## Step-by-Step Instructions + +### Step 1: Navigate to the Repository +Go to the PolymarketDocumentation folder: +``` +/home/himalaya/clawd/PolymarketDocumentation +``` + +### Step 2: Check if TARGET.md Has New URLs +Read the TARGET.md file and check if any new URLs have been added compared to what's already been scraped. The file contains a list of documentation URLs that need to be fetched. + +### Step 3: Scrape New or Updated Pages +For each URL in TARGET.md that doesn't already have a corresponding file in the docs/ folder, or if you suspect the official docs have been updated: + +1. Use the web_fetch tool or curl to fetch each URL +2. Save the content as a .md file in the appropriate docs/ subfolder +3. Match the folder structure to the URL path (e.g., `/quickstart/overview.md` goes in `docs/quickstart/`) + +### Step 4: Check for Changes +Run `git status` to see what files have been added or modified. + +### Step 5: Commit Changes +If there are new or updated files: +1. Add all changes: `git add -A` +2. Commit with a message that includes today's date, for example: "Update Polymarket documentation - 2026-02-14" +3. Use `git commit` to save the changes locally + +### Step 6: Push to GitHub +After committing, push the changes to the remote repository: +``` +git push origin main +``` + +### Step 7: Report +Tell the user what was done: +- How many new files were added +- Which sections were updated +- Confirm the push was successful + +## Important Notes + +- Only commit and push if there are actual changes +- If TARGET.md hasn't changed and all docs are already scraped, simply report "No updates needed today" +- Keep the folder structure organized - match the URL paths +- The repository is at: https://github.com/Etherdrake/PolymarketDocumentation + +## Example Output + +When you complete this task, say something like: + +"Checked Polymarket documentation. No new URLs in TARGET.md and all 117 files already present. No update needed today." + +OR: + +"Updated Polymarket documentation: Added 3 new API reference files (get-market-price, get-order-book, list-events). Pushed to GitHub successfully." + +## Manual Trigger +If the user asks you to check for updates, run through these steps immediately rather than waiting for your daily schedule. diff --git a/PolymarketDocumentation-main/INSTRUCTIONS.md b/PolymarketDocumentation-main/INSTRUCTIONS.md new file mode 100644 index 00000000..955d8369 --- /dev/null +++ b/PolymarketDocumentation-main/INSTRUCTIONS.md @@ -0,0 +1,202 @@ +# Polymarket Documentation Scraper Instructions + +## Overview +This document contains instructions for scraping Polymarket documentation from `docs.polymarket.com` and organizing it into the GitHub repository. + +The target URLs are stored in `TARGET.md` - edit that file to add/remove URLs to scrape. + +## How It Works + +1. **TARGET.md** - Contains the list of URLs to scrape (one per line) +2. **INSTRUCTIONS.md** - This file with scraping instructions +3. **scrape.sh** - The automation script that reads from TARGET.md + +## Quick Start + +```bash +cd /home/himalaya/clawd/PolymarketDocumentation +./scrape.sh +``` + +## Directory Structure +Organize the scraped files into the following structure: +``` +PolymarketDocumentation/ +├── TARGET.md # Source URLs (edit this file) +├── INSTRUCTIONS.md # This file +├── scrape.sh # Automation script +├── quickstart/ +│ ├── overview.md +│ ├── fetching-data.md +│ ├── first-order.md +│ └── reference/ +│ ├── glossary.md +│ ├── endpoints.md +│ └── introduction/ +│ └── rate-limits.md +├── developers/ +│ ├── market-makers/ +│ │ ├── introduction.md +│ │ ├── setup.md +│ │ ├── trading.md +│ │ ├── liquidity-rewards.md +│ │ ├── maker-rebates-program.md +│ │ ├── data-feeds.md +│ │ └── inventory.md +│ ├── CLOB/ +│ │ ├── introduction.md +│ │ ├── status.md +│ │ ├── quickstart.md +│ │ ├── authentication.md +│ │ ├── geoblock.md +│ │ ├── timeseries.md +│ │ ├── clients/ +│ │ │ ├── methods-overview.md +│ │ │ ├── methods-public.md +│ │ │ ├── methods-l1.md +│ │ │ ├── methods-l2.md +│ │ │ └── methods-builder.md +│ │ ├── orders/ +│ │ │ ├── orders.md +│ │ │ ├── create-order.md +│ │ │ ├── create-order-batch.md +│ │ │ ├── get-order.md +│ │ │ ├── get-active-order.md +│ │ │ ├── check-scoring.md +│ │ │ ├── cancel-orders.md +│ │ │ └── onchain-order-info.md +│ │ ├── trades/ +│ │ │ ├── trades-overview.md +│ │ │ └── trades.md +│ │ └── websocket/ +│ │ ├── wss-overview.md +│ │ ├── wss-auth.md +│ │ ├── user-channel.md +│ │ └── market-channel.md +│ ├── sports-websocket/ +│ │ ├── overview.md +│ │ ├── message-format.md +│ │ └── quickstart.md +│ ├── RTDS/ +│ │ ├── RTDS-overview.md +│ │ ├── RTDS-crypto-prices.md +│ │ └── RTDS-comments.md +│ └── gamma-markets-api/ +│ ├── overview.md +│ ├── gamma-structure.md +│ └── fetch-markets-guide.md +├── api-reference/ +│ ├── orderbook/ +│ │ ├── get-order-book-summary.md +│ │ └── get-multiple-order-books-summaries-by-request.md +│ ├── pricing/ +│ │ ├── get-market-price.md +│ │ ├── get-multiple-market-prices.md +│ │ ├── get-multiple-market-prices-by-request.md +│ │ ├── get-midpoint-price.md +│ │ └── get-price-history-for-a-traded-token.md +│ └── spreads/ +│ └── get-bid-ask-spreads.md +└── quickstart-websocket/ + └── WSS-Quickstart.md +``` + +## The Scrape Script (scrape.sh) + +```bash +#!/bin/bash + +# Base URL +BASE_URL="https://docs.polymarket.com" + +# Output directory +OUTPUT_DIR="PolymarketDocumentation" + +# Create output directory +mkdir -p "$OUTPUT_DIR" + +# Read URLs from TARGET.md (skip comments and empty lines) +grep -v '^#' "$OUTPUT_DIR/TARGET.md" | grep -v '^$' | while read -r url; do + # Extract the path portion (remove https://docs.polymarket.com/) + path="${url#https://docs.polymarket.com/}" + + # Remove .md extension for directory structure + filename=$(basename "$path" .md) + dir=$(dirname "$path") + + # Create directory + mkdir -p "$OUTPUT_DIR/$dir" + + # Determine output file path + output_file="$OUTPUT_DIR/$path" + + # Fetch the page + echo "Fetching: $url -> $output_file" + curl -s "$url" -o "$output_file" + + # Check if successful + if [ $? -eq 0 ] && [ -s "$output_file" ]; then + echo " ✅ Success: $filename" + else + echo " ❌ Failed: $filename" + fi + + # Rate limit (0.5 seconds between requests) + sleep 0.5 +done + +echo "Done! Scraped files to $OUTPUT_DIR/" +``` + +## Alternative: Using Python Script + +```python +#!/usr/bin/env python3 +import os +import urllib.request +import time +import re + +BASE_URL = "https://docs.polymarket.com" +OUTPUT_DIR = "PolymarketDocumentation" + +# Read URLs from TARGET.md +with open("TARGET.md", "r") as f: + urls = [line.strip() for line in f if line.strip() and not line.startswith("#")] + +for url in urls: + # Extract path and create directories + path = url.replace("https://docs.polymarket.com/", "") + filepath = os.path.join(OUTPUT_DIR, path) + os.makedirs(os.path.dirname(filepath), exist_ok=True) + + # Fetch the page + print(f"Fetching: {url}") + try: + urllib.request.urlretrieve(url, filepath) + print(f" ✅ Saved: {filepath}") + except Exception as e: + print(f" ❌ Error: {e}") + + # Rate limit + time.sleep(0.5) + +print("Done!") +``` + +## Notes +- The `.md` suffix converts HTML pages to markdown format automatically +- Some URLs may require authentication - handle accordingly +- Rate limiting should be respected between requests +- Check for HTTP 200 status codes to verify successful fetches + +## Adding New URLs + +To add new URLs to scrape, simply edit `TARGET.md` and add the URL on a new line: + +```markdown +## New Section +https://docs.polymarket.com/new-section/page.md +``` + +Then run the scrape script again to fetch the new URLs. diff --git a/PolymarketDocumentation-main/LICENSE b/PolymarketDocumentation-main/LICENSE new file mode 100644 index 00000000..7336962e --- /dev/null +++ b/PolymarketDocumentation-main/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2026 Max Bodewes + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/PolymarketDocumentation-main/README.md b/PolymarketDocumentation-main/README.md new file mode 100644 index 00000000..0c8d15ab --- /dev/null +++ b/PolymarketDocumentation-main/README.md @@ -0,0 +1,2 @@ +# PolymarketDocumentation +Full and completely scraped and maintained Polymarket documentation diff --git a/PolymarketDocumentation-main/TARGET.md b/PolymarketDocumentation-main/TARGET.md new file mode 100644 index 00000000..c9639d93 --- /dev/null +++ b/PolymarketDocumentation-main/TARGET.md @@ -0,0 +1,488 @@ +# Target URLs for Polymarket Documentation + +These URLs will be scraped and organized into the repository. + +## Quickstart +https://docs.polymarket.com/quickstart.md +https://docs.polymarket.com/quickstart/overview.md +https://docs.polymarket.com/quickstart/fetching-data.md +https://docs.polymarket.com/quickstart/first-order.md + +https://docs.polymarket.com/quickstart/introduction/rate-limits.md +https://docs.polymarket.com/quickstart/reference/endpoints.md + +## Market Makers +https://docs.polymarket.com/market-makers/overview.md +https://docs.polymarket.com/market-makers/getting-started.md +https://docs.polymarket.com/market-makers/trading.md +https://docs.polymarket.com/market-makers/liquidity-rewards.md +https://docs.polymarket.com/market-makers/maker-rebates.md +https://docs.polymarket.com/market-makers/inventory.md +https://docs.polymarket.com/market-makers/combos.md +https://docs.polymarket.com/developers/market-makers/introduction.md +https://docs.polymarket.com/developers/market-makers/setup.md +https://docs.polymarket.com/developers/market-makers/data-feeds.md + +## Polymarket Builders Program +https://docs.polymarket.com/builders/overview.md +https://docs.polymarket.com/builders/tiers.md +https://docs.polymarket.com/builders/api-keys.md +https://docs.polymarket.com/developers/builders/builder-intro.md +https://docs.polymarket.com/developers/builders/builder-tiers.md +https://docs.polymarket.com/developers/builders/builder-profile.md +https://docs.polymarket.com/developers/builders/order-attribution.md +https://docs.polymarket.com/developers/builders/relayer-client.md +https://docs.polymarket.com/developers/builders/blockchain-data-resources.md +https://docs.polymarket.com/developers/builders/examples.md + +## Central Limit Order Book (CLOB) +https://docs.polymarket.com/trading/overview.md +https://docs.polymarket.com/trading/quickstart.md +https://docs.polymarket.com/developers/CLOB/introduction.md +https://docs.polymarket.com/developers/CLOB/status.md +https://docs.polymarket.com/developers/CLOB/quickstart.md +https://docs.polymarket.com/developers/CLOB/authentication.md +https://docs.polymarket.com/developers/CLOB/geoblock.md +https://docs.polymarket.com/developers/CLOB/clients/methods-overview.md +https://docs.polymarket.com/developers/CLOB/clients/methods-public.md +https://docs.polymarket.com/developers/CLOB/clients/methods-l1.md +https://docs.polymarket.com/developers/CLOB/clients/methods-l2.md +https://docs.polymarket.com/developers/CLOB/clients/methods-builder.md + +## API Reference - Market Data +https://docs.polymarket.com/api-reference/introduction.md +https://docs.polymarket.com/api-reference/authentication.md +https://docs.polymarket.com/api-reference/rate-limits.md +https://docs.polymarket.com/api-reference/geoblock.md +https://docs.polymarket.com/api-reference/clients-sdks.md + +## API Reference - Market Data (Data API) +https://docs.polymarket.com/market-data/overview.md +https://docs.polymarket.com/market-data/fetching-markets.md +https://docs.polymarket.com/api-reference/market-data/get-order-book.md +https://docs.polymarket.com/api-reference/market-data/get-order-books-request-body.md +https://docs.polymarket.com/api-reference/market-data/get-market-price.md +https://docs.polymarket.com/api-reference/market-data/get-market-prices-query-parameters.md +https://docs.polymarket.com/api-reference/market-data/get-market-prices-request-body.md +https://docs.polymarket.com/api-reference/data/get-midpoint-price.md +https://docs.polymarket.com/api-reference/market-data/get-midpoint-prices-query-parameters.md +https://docs.polymarket.com/api-reference/market-data/get-midpoint-prices-request-body.md +https://docs.polymarket.com/api-reference/market-data/get-spread.md +https://docs.polymarket.com/api-reference/market-data/get-spreads.md +https://docs.polymarket.com/api-reference/market-data/get-last-trade-price.md +https://docs.polymarket.com/api-reference/market-data/get-last-trade-prices-query-parameters.md +https://docs.polymarket.com/api-reference/market-data/get-last-trade-prices-request-body.md +https://docs.polymarket.com/api-reference/market-data/get-fee-rate.md +https://docs.polymarket.com/api-reference/market-data/get-fee-rate-by-path-parameter.md +https://docs.polymarket.com/api-reference/market-data/get-tick-size.md +https://docs.polymarket.com/api-reference/market-data/get-tick-size-by-path-parameter.md +https://docs.polymarket.com/api-reference/data/get-server-time.md + +## API Reference - Orderbook + + +## API Reference - WSS RFQ +https://docs.polymarket.com/api-reference/wss/rfq.md + +## API Reference - Trade (CLOB) +https://docs.polymarket.com/api-reference/trade/post-a-new-order.md +https://docs.polymarket.com/api-reference/trade/post-multiple-orders.md +https://docs.polymarket.com/api-reference/trade/get-single-order-by-id.md +https://docs.polymarket.com/api-reference/trade/get-user-orders.md +https://docs.polymarket.com/api-reference/trade/get-trades.md +https://docs.polymarket.com/api-reference/trade/cancel-single-order.md +https://docs.polymarket.com/api-reference/trade/cancel-multiple-orders.md +https://docs.polymarket.com/api-reference/trade/cancel-all-orders.md +https://docs.polymarket.com/api-reference/trade/cancel-orders-for-a-market.md +https://docs.polymarket.com/api-reference/trade/get-order-scoring-status.md +https://docs.polymarket.com/api-reference/trade/send-heartbeat.md +https://docs.polymarket.com/api-reference/trade/get-builder-trades.md + +## Historical Timeseries Data +https://docs.polymarket.com/developers/CLOB/timeseries.md + +## Order Management +https://docs.polymarket.com/developers/CLOB/orders/orders.md +https://docs.polymarket.com/developers/CLOB/orders/create-order.md +https://docs.polymarket.com/developers/CLOB/orders/create-order-batch.md +https://docs.polymarket.com/developers/CLOB/orders/get-order.md +https://docs.polymarket.com/developers/CLOB/orders/get-active-order.md +https://docs.polymarket.com/developers/CLOB/orders/check-scoring.md +https://docs.polymarket.com/developers/CLOB/orders/cancel-orders.md +https://docs.polymarket.com/developers/CLOB/orders/onchain-order-info.md +https://docs.polymarket.com/trading/orders/overview.md +https://docs.polymarket.com/trading/orders/create.md +https://docs.polymarket.com/trading/orders/cancel.md +https://docs.polymarket.com/trading/orders/attribution.md + +## Trades +https://docs.polymarket.com/developers/CLOB/trades/trades-overview.md +https://docs.polymarket.com/developers/CLOB/trades/trades.md + +## Websocket +https://docs.polymarket.com/market-data/websocket/overview.md +https://docs.polymarket.com/market-data/websocket/market-channel.md +https://docs.polymarket.com/market-data/websocket/user-channel.md +https://docs.polymarket.com/developers/CLOB/websocket/wss-overview.md +https://docs.polymarket.com/quickstart/websocket/WSS-Quickstart.md +https://docs.polymarket.com/developers/CLOB/websocket/wss-auth.md +https://docs.polymarket.com/developers/CLOB/websocket/user-channel.md +https://docs.polymarket.com/developers/CLOB/websocket/market-channel.md +https://docs.polymarket.com/api-reference/wss/market.md +https://docs.polymarket.com/api-reference/wss/user.md + +## Sports Websocket +https://docs.polymarket.com/developers/sports-websocket/overview.md +https://docs.polymarket.com/developers/sports-websocket/message-format.md +https://docs.polymarket.com/developers/sports-websocket/quickstart.md +https://docs.polymarket.com/market-data/websocket/sports.md +https://docs.polymarket.com/api-reference/wss/sports.md + +## Real Time Data Stream +https://docs.polymarket.com/market-data/websocket/rtds.md +https://docs.polymarket.com/developers/RTDS/RTDS-overview.md +https://docs.polymarket.com/developers/RTDS/RTDS-crypto-prices.md +https://docs.polymarket.com/developers/RTDS/RTDS-comments.md + +## Gamma Structure +https://docs.polymarket.com/developers/gamma-markets-api/overview.md +https://docs.polymarket.com/developers/gamma-markets-api/gamma-structure.md +https://docs.polymarket.com/developers/gamma-markets-api/fetch-markets-guide.md + +## Gamma Endpoints - Status + +## API Reference - Sports +https://docs.polymarket.com/api-reference/sports/list-teams.md +https://docs.polymarket.com/api-reference/sports/get-sports-metadata-information.md +https://docs.polymarket.com/api-reference/sports/get-valid-sports-market-types.md + +## API Reference - Tags +https://docs.polymarket.com/api-reference/tags/list-tags.md +https://docs.polymarket.com/api-reference/tags/get-tag-by-id.md +https://docs.polymarket.com/api-reference/tags/get-tag-by-slug.md +https://docs.polymarket.com/api-reference/tags/get-related-tags-relationships-by-tag-id.md +https://docs.polymarket.com/api-reference/tags/get-related-tags-relationships-by-tag-slug.md +https://docs.polymarket.com/api-reference/tags/get-tags-related-to-a-tag-id.md +https://docs.polymarket.com/api-reference/tags/get-tags-related-to-a-tag-slug.md + +## API Reference - Events +https://docs.polymarket.com/api-reference/events/list-events.md +https://docs.polymarket.com/api-reference/events/list-events-keyset-pagination.md +https://docs.polymarket.com/api-reference/events/get-event-by-id.md +https://docs.polymarket.com/api-reference/events/get-event-tags.md +https://docs.polymarket.com/api-reference/events/get-event-by-slug.md + +## API Reference - Markets +https://docs.polymarket.com/api-reference/markets/list-markets.md +https://docs.polymarket.com/api-reference/markets/list-markets-keyset-pagination.md +https://docs.polymarket.com/api-reference/markets/get-market-by-id.md +https://docs.polymarket.com/api-reference/markets/get-market-tags-by-id.md +https://docs.polymarket.com/api-reference/markets/get-market-by-slug.md +https://docs.polymarket.com/api-reference/markets/get-clob-market-info.md +https://docs.polymarket.com/api-reference/markets/get-market-by-token.md +https://docs.polymarket.com/api-reference/markets/get-prices-history.md +https://docs.polymarket.com/api-reference/markets/get-batch-prices-history.md +https://docs.polymarket.com/api-reference/markets/get-sampling-markets.md +https://docs.polymarket.com/api-reference/markets/get-simplified-markets.md +https://docs.polymarket.com/api-reference/markets/get-sampling-simplified-markets.md + +## API Reference - Series +https://docs.polymarket.com/api-reference/series/list-series.md +https://docs.polymarket.com/api-reference/series/get-series-by-id.md + +## API Reference - Comments +https://docs.polymarket.com/api-reference/comments/list-comments.md +https://docs.polymarket.com/api-reference/comments/get-comments-by-comment-id.md +https://docs.polymarket.com/api-reference/comments/get-comments-by-user-address.md + +## API Reference - Profiles +https://docs.polymarket.com/api-reference/profiles/get-public-profile-by-wallet-address.md + +## API Reference - Search +https://docs.polymarket.com/api-reference/search/search-markets-events-and-profiles.md + +## API Reference - Data API Status + +## API Reference - Misc +https://docs.polymarket.com/api-reference/misc/download-an-accounting-snapshot-zip-of-csvs.md +https://docs.polymarket.com/api-reference/misc/get-total-markets-a-user-has-traded.md +https://docs.polymarket.com/api-reference/misc/get-open-interest.md +https://docs.polymarket.com/api-reference/misc/get-live-volume-for-an-event.md + +## API Reference - Core +https://docs.polymarket.com/api-reference/core/get-current-positions-for-a-user.md +https://docs.polymarket.com/api-reference/core/get-trades-for-a-user-or-markets.md +https://docs.polymarket.com/api-reference/core/get-user-activity.md +https://docs.polymarket.com/api-reference/core/get-top-holders-for-markets.md +https://docs.polymarket.com/api-reference/core/get-total-value-of-a-users-positions.md +https://docs.polymarket.com/api-reference/core/get-closed-positions-for-a-user.md +https://docs.polymarket.com/api-reference/core/get-trader-leaderboard-rankings.md +https://docs.polymarket.com/api-reference/core/get-positions-for-a-market.md + +## API Reference - Builders +https://docs.polymarket.com/api-reference/builders/get-aggregated-builder-leaderboard.md +https://docs.polymarket.com/api-reference/builders/get-daily-builder-volume-time-series.md + +## Bridge & Swap - Overview + +https://docs.polymarket.com/developers/misc-endpoints/bridge-overview.md + +## API Reference - Bridge +https://docs.polymarket.com/api-reference/bridge/get-supported-assets.md +https://docs.polymarket.com/api-reference/bridge/get-a-quote.md + +https://docs.polymarket.com/api-reference/bridge/create-withdrawal-addresses.md +https://docs.polymarket.com/api-reference/bridge/get-transaction-status.md +https://docs.polymarket.com/api-reference/bridge/create-bridge-addresses.md +https://docs.polymarket.com/trading/bridge/deposit.md +https://docs.polymarket.com/trading/bridge/quote.md +https://docs.polymarket.com/trading/bridge/status.md +https://docs.polymarket.com/trading/bridge/supported-assets.md +https://docs.polymarket.com/trading/bridge/withdraw.md + +## Subgraph + + +## Resolution +https://docs.polymarket.com/developers/resolution/UMA.md + +## Conditional Token Frameworks (CTF) +https://docs.polymarket.com/trading/ctf/overview.md +https://docs.polymarket.com/trading/ctf/split.md +https://docs.polymarket.com/trading/ctf/merge.md +https://docs.polymarket.com/trading/ctf/redeem.md +https://docs.polymarket.com/developers/CTF/overview.md +https://docs.polymarket.com/developers/CTF/split.md +https://docs.polymarket.com/developers/CTF/merge.md +https://docs.polymarket.com/developers/CTF/redeem.md +https://docs.polymarket.com/developers/CTF/deployment-resources.md + +## Proxy Wallets +https://docs.polymarket.com/developers/proxy-wallet.md + +## Negative Risk +https://docs.polymarket.com/advanced/neg-risk.md +https://docs.polymarket.com/developers/neg-risk/overview.md + +## Changelog +https://docs.polymarket.com/changelog/changelog.md + +## Polymarket Learn - FAQ +https://docs.polymarket.com/polymarket-learn/FAQ/does-polymarket-have-an-api.md +https://docs.polymarket.com/polymarket-learn/FAQ/embeds.md +https://docs.polymarket.com/polymarket-learn/FAQ/geoblocking.md +https://docs.polymarket.com/polymarket-learn/FAQ/how-to-export-private-key.md +https://docs.polymarket.com/polymarket-learn/FAQ/is-my-money-safe.md +https://docs.polymarket.com/polymarket-learn/FAQ/is-polymarket-the-house.md +https://docs.polymarket.com/polymarket-learn/FAQ/polling.md +https://docs.polymarket.com/polymarket-learn/FAQ/recover-missing-deposit.md +https://docs.polymarket.com/polymarket-learn/FAQ/sell-early.md +https://docs.polymarket.com/polymarket-learn/FAQ/support.md +https://docs.polymarket.com/polymarket-learn/FAQ/wen-token.md +https://docs.polymarket.com/polymarket-learn/FAQ/what-are-prediction-markets.md +https://docs.polymarket.com/polymarket-learn/FAQ/why-do-i-need-crypto.md + +## Polymarket Learn - Deposits +https://docs.polymarket.com/polymarket-learn/deposits/coinbase.md +https://docs.polymarket.com/polymarket-learn/deposits/how-to-withdraw.md +https://docs.polymarket.com/polymarket-learn/deposits/large-cross-chain-deposits.md +https://docs.polymarket.com/polymarket-learn/deposits/moonpay.md +https://docs.polymarket.com/polymarket-learn/deposits/supported-tokens.md +https://docs.polymarket.com/polymarket-learn/deposits/usdc-on-eth.md + +## Polymarket Learn - Get Started +https://docs.polymarket.com/polymarket-learn/get-started/how-to-deposit.md +https://docs.polymarket.com/polymarket-learn/get-started/how-to-signup.md +https://docs.polymarket.com/polymarket-learn/get-started/making-your-first-trade.md +https://docs.polymarket.com/polymarket-learn/get-started/what-is-polymarket.md + +## Polymarket Learn - Markets +https://docs.polymarket.com/polymarket-learn/markets/dispute.md +https://docs.polymarket.com/polymarket-learn/markets/how-are-markets-clarified.md +https://docs.polymarket.com/polymarket-learn/markets/how-are-markets-created.md +https://docs.polymarket.com/polymarket-learn/markets/how-are-markets-resolved.md + +## Polymarket Learn - Trading +https://docs.polymarket.com/polymarket-learn/trading/fees.md +https://docs.polymarket.com/polymarket-learn/trading/holding-rewards.md +https://docs.polymarket.com/polymarket-learn/trading/how-are-prices-calculated.md +https://docs.polymarket.com/polymarket-learn/trading/limit-orders.md +https://docs.polymarket.com/polymarket-learn/trading/liquidity-rewards.md +https://docs.polymarket.com/polymarket-learn/trading/maker-rebates-program.md +https://docs.polymarket.com/polymarket-learn/trading/market-orders.md +https://docs.polymarket.com/polymarket-learn/trading/no-limits.md +https://docs.polymarket.com/polymarket-learn/trading/using-the-orderbook.md + +## Polymarket 101 +https://docs.polymarket.com/polymarket-101.md + +## Concepts +https://docs.polymarket.com/concepts/markets-events.md +https://docs.polymarket.com/concepts/order-lifecycle.md +https://docs.polymarket.com/concepts/positions-tokens.md +https://docs.polymarket.com/concepts/prices-orderbook.md +https://docs.polymarket.com/concepts/resolution.md +https://docs.polymarket.com/concepts/pusd.md + +## Trading +https://docs.polymarket.com/trading/fees.md +https://docs.polymarket.com/trading/gasless.md +https://docs.polymarket.com/trading/orderbook.md +https://docs.polymarket.com/trading/clients/public.md +https://docs.polymarket.com/trading/clients/l1.md +https://docs.polymarket.com/trading/clients/l2.md +https://docs.polymarket.com/trading/clients/builder.md +https://docs.polymarket.com/trading/deposit-wallets.md +https://docs.polymarket.com/trading/taker-rebates.md + +## Index & Resources +https://docs.polymarket.com/index.md +https://docs.polymarket.com/resources/contract-addresses.md +https://docs.polymarket.com/resources/error-codes.md +https://docs.polymarket.com/resources/contracts.md + +## NEW - API Reference - Rebates (2026-03-27) +https://docs.polymarket.com/api-reference/rebates/get-current-rebated-fees-for-a-maker.md + +## NEW - API Reference - Relayer +https://docs.polymarket.com/api-reference/relayer-api-keys/get-all-relayer-api-keys.md +https://docs.polymarket.com/api-reference/relayer/check-if-a-safe-is-deployed.md +https://docs.polymarket.com/api-reference/relayer/check-if-a-wallet-is-deployed.md +https://docs.polymarket.com/api-reference/relayer/get-a-transaction-by-id.md +https://docs.polymarket.com/api-reference/relayer/get-current-nonce-for-a-user.md +https://docs.polymarket.com/api-reference/relayer/get-recent-transactions-for-a-user.md +https://docs.polymarket.com/api-reference/relayer/get-relayer-address-and-nonce.md +https://docs.polymarket.com/api-reference/relayer/submit-a-transaction.md + +## NEW - API Reference - Rewards +https://docs.polymarket.com/api-reference/rewards/get-current-active-rewards-configurations.md +https://docs.polymarket.com/api-reference/rewards/get-earnings-for-user-by-date.md +https://docs.polymarket.com/api-reference/rewards/get-multiple-markets-with-rewards.md +https://docs.polymarket.com/api-reference/rewards/get-raw-rewards-for-a-specific-market.md +https://docs.polymarket.com/api-reference/rewards/get-reward-percentages-for-user.md +https://docs.polymarket.com/api-reference/rewards/get-total-earnings-for-user-by-date.md +https://docs.polymarket.com/api-reference/rewards/get-user-earnings-and-markets-configuration.md + +## NEW - Resources +https://docs.polymarket.com/resources/blockchain-data.md +https://docs.polymarket.com/resources/referral-program.md + +## NEW - Trading +https://docs.polymarket.com/trading/matching-engine.md + +## Dev Tooling +https://docs.polymarket.com/dev-tooling.md +https://docs.polymarket.com/dev-tooling/python.md +https://docs.polymarket.com/dev-tooling/typescript.md + +## NEW - Builders +https://docs.polymarket.com/builders/fees.md + +## NEW - API Reference - Combo Markets (2026-06-17) +https://docs.polymarket.com/api-reference/combo-markets/get-combo-markets.md + +## NEW - API Reference - Core (Combo) (2026-06-17) +https://docs.polymarket.com/api-reference/core/get-user-combo-activity.md +https://docs.polymarket.com/api-reference/core/get-user-combo-positions.md + +## NEW - API Reference - Maker (RFQ) (2026-06-17) +https://docs.polymarket.com/api-reference/maker/cancel-a-quote.md +https://docs.polymarket.com/api-reference/maker/confirm-or-decline-last-look.md +https://docs.polymarket.com/api-reference/maker/submit-a-quote.md + +## NEW - Perps (2026-07-13) +https://docs.polymarket.com/perps/overview.md +https://docs.polymarket.com/perps/account-management.md +https://docs.polymarket.com/perps/authenticated-sessions.md +https://docs.polymarket.com/perps/changelog.md +https://docs.polymarket.com/perps/concepts.md +https://docs.polymarket.com/perps/faq.md +https://docs.polymarket.com/perps/fund-your-account.md +https://docs.polymarket.com/perps/market-data.md +https://docs.polymarket.com/perps/overview.md +https://docs.polymarket.com/perps/place-your-first-trade.md +https://docs.polymarket.com/perps/rate-limits.md +https://docs.polymarket.com/perps/realtime-updates.md +https://docs.polymarket.com/perps/referral-program.md +https://docs.polymarket.com/perps/trading.md +https://docs.polymarket.com/perps/learn-about-trading/architecture.md +https://docs.polymarket.com/perps/learn-about-trading/fees.md +https://docs.polymarket.com/perps/learn-about-trading/funding.md +https://docs.polymarket.com/perps/learn-about-trading/geographic-restrictions.md +https://docs.polymarket.com/perps/learn-about-trading/index-price.md +https://docs.polymarket.com/perps/learn-about-trading/liquidation-mechanics.md +https://docs.polymarket.com/perps/learn-about-trading/margin.md +https://docs.polymarket.com/perps/learn-about-trading/mark-price.md +https://docs.polymarket.com/perps/learn-about-trading/market-sessions.md +https://docs.polymarket.com/perps/learn-about-trading/markets.md +https://docs.polymarket.com/perps/learn-about-trading/overview.md + +## NEW - Perps WebSocket (2026-07-13) +https://docs.polymarket.com/api-reference/wss/perps-auth.md +https://docs.polymarket.com/api-reference/wss/perps-auto-cancel.md +https://docs.polymarket.com/api-reference/wss/perps-balances.md +https://docs.polymarket.com/api-reference/wss/perps-bbo.md +https://docs.polymarket.com/api-reference/wss/perps-book.md +https://docs.polymarket.com/api-reference/wss/perps-cancel-orders.md +https://docs.polymarket.com/api-reference/wss/perps-cancel-orders-coid.md +https://docs.polymarket.com/api-reference/wss/perps-deposits.md +https://docs.polymarket.com/api-reference/wss/perps-fills.md +https://docs.polymarket.com/api-reference/wss/perps-funding.md +https://docs.polymarket.com/api-reference/wss/perps-klines.md +https://docs.polymarket.com/api-reference/wss/perps-orders.md +https://docs.polymarket.com/api-reference/wss/perps-ping.md +https://docs.polymarket.com/api-reference/wss/perps-place-orders.md +https://docs.polymarket.com/api-reference/wss/perps-portfolio.md +https://docs.polymarket.com/api-reference/wss/perps-statistics.md +https://docs.polymarket.com/api-reference/wss/perps-tickers.md +https://docs.polymarket.com/api-reference/wss/perps-trades.md +https://docs.polymarket.com/api-reference/wss/perps-update-leverage.md +https://docs.polymarket.com/api-reference/wss/perps-withdrawals.md + +## NEW - Account & Trading API (2026-07-13) +https://docs.polymarket.com/api-reference/apply-referral-code.md +https://docs.polymarket.com/api-reference/cancel-orders.md +https://docs.polymarket.com/api-reference/cancel-orders-coid.md +https://docs.polymarket.com/api-reference/check-invite-code.md +https://docs.polymarket.com/api-reference/create-account-invite.md +https://docs.polymarket.com/api-reference/create-orders.md +https://docs.polymarket.com/api-reference/create-proxy.md +https://docs.polymarket.com/api-reference/delete-proxy.md +https://docs.polymarket.com/api-reference/get-account-limits.md +https://docs.polymarket.com/api-reference/get-account-referral.md +https://docs.polymarket.com/api-reference/get-account-rewards.md +https://docs.polymarket.com/api-reference/get-account-stats.md +https://docs.polymarket.com/api-reference/get-auto-cancel-status.md +https://docs.polymarket.com/api-reference/get-balances.md +https://docs.polymarket.com/api-reference/get-bbo.md +https://docs.polymarket.com/api-reference/get-book.md +https://docs.polymarket.com/api-reference/get-collateral-assets.md +https://docs.polymarket.com/api-reference/get-credentials.md +https://docs.polymarket.com/api-reference/get-deposits.md +https://docs.polymarket.com/api-reference/get-equity.md +https://docs.polymarket.com/api-reference/get-exchange-info.md +https://docs.polymarket.com/api-reference/get-fees.md +https://docs.polymarket.com/api-reference/get-fills.md +https://docs.polymarket.com/api-reference/get-funding-charges.md +https://docs.polymarket.com/api-reference/get-historical-funding.md +https://docs.polymarket.com/api-reference/get-index.md +https://docs.polymarket.com/api-reference/get-instrument-config.md +https://docs.polymarket.com/api-reference/get-instruments.md +https://docs.polymarket.com/api-reference/get-internal-transfers.md +https://docs.polymarket.com/api-reference/get-klines.md +https://docs.polymarket.com/api-reference/get-limit-tiers.md +https://docs.polymarket.com/api-reference/get-open-orders.md +https://docs.polymarket.com/api-reference/get-orders.md +https://docs.polymarket.com/api-reference/get-pnl.md +https://docs.polymarket.com/api-reference/get-portfolio.md +https://docs.polymarket.com/api-reference/get-public-portfolio.md +https://docs.polymarket.com/api-reference/get-recent-trades.md +https://docs.polymarket.com/api-reference/get-server-time.md +https://docs.polymarket.com/api-reference/get-statistics.md +https://docs.polymarket.com/api-reference/get-tickers.md +https://docs.polymarket.com/api-reference/get-withdrawals.md +https://docs.polymarket.com/api-reference/internal-transfer.md +https://docs.polymarket.com/api-reference/set-auto-cancel.md +https://docs.polymarket.com/api-reference/test-connection.md +https://docs.polymarket.com/api-reference/update-leverage.md +https://docs.polymarket.com/api-reference/withdraw.md diff --git a/PolymarketDocumentation-main/docs/advanced/neg-risk.md b/PolymarketDocumentation-main/docs/advanced/neg-risk.md new file mode 100644 index 00000000..579d57c1 --- /dev/null +++ b/PolymarketDocumentation-main/docs/advanced/neg-risk.md @@ -0,0 +1,145 @@ +> ## Documentation Index +> Fetch the complete documentation index at: https://docs.polymarket.com/llms.txt +> Use this file to discover all available pages before exploring further. + +# Negative Risk Markets + +> Capital-efficient trading for multi-outcome events + +**Negative risk** is a mechanism for multi-outcome events where only one outcome can win. It enables capital-efficient trading by allowing positions across all outcomes within an event to be related through a **conversion** operation. + +## How It Works + +In a standard multi-outcome event, each market is independent. If you want to bet against one outcome, you must buy that outcome's No tokens—but those No tokens have no relationship to the other outcomes. + +Negative risk changes this. In a neg risk event: + +* A **No share** in any market can be converted into **1 Yes share in every other market** +* This conversion happens through the Neg Risk Adapter contract + +### Example + +Consider an event: "Who will win the 2024 Presidential Election?" with three outcomes: + +| Outcome | Your Position | +| ------- | ------------- | +| Trump | — | +| Harris | — | +| Other | 1 No | + +With negative risk, that 1 No on "Other" can be converted into: + +| Outcome | After Conversion | +| ------- | ---------------- | +| Trump | 1 Yes | +| Harris | 1 Yes | +| Other | — | + +This is capital-efficient because betting against one outcome is economically equivalent to betting *for* all other outcomes. + +## Identifying Neg Risk Markets + +The Gamma API includes a `negRisk` boolean on events and markets: + +```json theme={null} +{ + "id": "123", + "title": "Who will win the 2024 Presidential Election?", + "negRisk": true, + "markets": [...] +} +``` + +When placing orders on neg risk markets, you must specify this in your order options: + +```typescript theme={null} +const response = await client.createAndPostOrder( + { + tokenID: "TOKEN_ID", + price: 0.5, + size: 100, + side: Side.BUY, + }, + { + tickSize: "0.01", + negRisk: true, // Required for neg risk markets + }, +); +``` + +## Contract Addresses + +Neg risk markets use different contracts than standard markets: + +See [Contracts](/resources/contracts) for the Neg Risk Adapter and Neg Risk CTF Exchange addresses. + +## Augmented Negative Risk + +Standard negative risk requires the complete set of outcomes to be known at market creation. But sometimes new outcomes emerge after trading begins (e.g., a new candidate enters a race). + +**Augmented negative risk** solves this with: + +| Outcome Type | Description | +| ------------------------ | ------------------------------------------------------------- | +| **Named outcomes** | Known outcomes (e.g., "Trump", "Harris") | +| **Placeholder outcomes** | Reserved slots that can be clarified later (e.g., "Person A") | +| **Explicit Other** | Catches any outcome not explicitly named | + +### How Placeholders Work + +1. Event launches with named outcomes + placeholders + "Other" +2. When a new outcome emerges, a placeholder is clarified via the bulletin board +3. The "Other" definition narrows as placeholders are assigned + +### Trading Rules for Augmented Neg Risk + + + Only trade on **named outcomes**. Placeholder outcomes should be ignored until + they are named or until resolution occurs. The Polymarket UI does not display + unnamed outcomes. + + +* If the correct outcome at resolution is not named, the market resolves to "Other" +* The "Other" outcome's definition changes as placeholders are clarified—avoid trading it directly + +### Identifying Augmented Neg Risk + +An event is augmented neg risk when both flags are true: + +```json theme={null} +{ + "enableNegRisk": true, + "negRiskAugmented": true +} +``` + + + The Gamma API includes a boolean field `negRisk` on events and markets, which indicates whether the event uses negative risk. For augmented neg risk events, an additional `enableNegRisk` field is also `true`. When placing orders, the SDK option is always `negRisk: true` / `neg_risk: True` regardless of whether the market is standard or augmented neg risk. + + +## Technical Details + +### Conversion Mechanics + +The conversion operation is atomic and happens through the Neg Risk Adapter: + +1. You hold 1 No token for Outcome A +2. Call the convert function on the adapter +3. You receive 1 Yes token for every other outcome in the event + +## Resources + +* [Neg Risk Adapter Source Code](https://github.com/Polymarket/neg-risk-ctf-adapter) +* [Gamma API Documentation](/market-data/overview) + +## Next Steps + + + + Understand how multi-market events are structured. + + + + Learn about token operations like split, merge, and redeem. + + diff --git a/PolymarketDocumentation-main/docs/api-reference/apply-referral-code.md b/PolymarketDocumentation-main/docs/api-reference/apply-referral-code.md new file mode 100644 index 00000000..6abaeb4a --- /dev/null +++ b/PolymarketDocumentation-main/docs/api-reference/apply-referral-code.md @@ -0,0 +1,226 @@ +> ## Documentation Index +> Fetch the complete documentation index at: https://docs.polymarket.com/llms.txt +> Use this file to discover all available pages before exploring further. + +# Apply Referral Code + +> Apply a referral code to the authenticated account after signup. Accounts +can only apply a referral code if they do not already have one. + + +Request Weight: **1** + + +## OpenAPI + +````yaml /api-spec/perps-openapi.json post /v1/account/referral +openapi: 3.0.3 +info: + title: Polymarket Perps HTTP API + version: 1.0.0 + description: HTTP API for Polymarket perpetual trading system. + license: + name: Apache 2.0 + url: https://www.apache.org/licenses/LICENSE-2.0.html +servers: + - url: https://api.perpetuals.polymarket.com + description: Production Perps HTTP API +security: [] +paths: + /v1/account/referral: + post: + summary: Apply Referral Code + description: > + Apply a referral code to the authenticated account after signup. + Accounts + + can only apply a referral code if they do not already have one. + operationId: applyReferral + requestBody: + required: true + description: Referral code to apply. + content: + application/json: + schema: + $ref: '#/components/schemas/AccountReferralRequest' + examples: + applyReferral: + summary: Apply a referral code + value: + code: ABC123 + responses: + '200': + description: Referral code accepted. + content: + application/json: + schema: + $ref: '#/components/schemas/GenericAccepted' + '400': + $ref: '#/components/responses/Error400Response' + '401': + $ref: '#/components/responses/Error401Response' + '429': + $ref: '#/components/responses/Error429Response' + '500': + $ref: '#/components/responses/Error500Response' + security: + - polymarket_proxy: [] + polymarket_secret: [] +components: + schemas: + AccountReferralRequest: + type: object + required: + - code + properties: + code: + $ref: '#/components/schemas/code' + GenericAccepted: + type: object + required: + - status + properties: + status: + type: string + enum: + - ok + code: + type: string + description: Referral or invite code + example: ABC123 + Error400: + title: Error400 + type: object + required: + - status + - error + properties: + status: + type: string + enum: + - err + error: + $ref: '#/components/schemas/error' + Error401: + title: Error401 + type: object + required: + - status + - error + properties: + status: + type: string + enum: + - err + error: + $ref: '#/components/schemas/error' + Error429: + title: Error429 + type: object + required: + - status + - error + properties: + status: + type: string + enum: + - err + error: + $ref: '#/components/schemas/error' + Error500: + title: Error500 + type: object + required: + - status + - error + properties: + status: + type: string + enum: + - err + error: + $ref: '#/components/schemas/error' + error: + type: string + description: >- + Error identifier. For domain rejections and transport errors + (`401`/`404`/`429`/`500`) this is a stable, machine-readable snake_case + identifier that is part of the API contract and safe to branch on, e.g. + `insufficient_margin`, `insufficient_balance`, `order_not_found`, + `reduce_only_invalid`, `unauthorized`, `not_found`. For `400` it is a + human-readable validation detail whose wording may change. See the Error + handling guide for the domain identifiers. (Post-only / Fill-or-Kill + outcomes are order statuses such as `post_only_rejected`, not + rejections.) + example: insufficient_margin + responses: + Error400Response: + description: | + Bad request — the request was malformed or failed validation (bad query + parameters, unparseable body, invalid signature, or a domain pre-check). + The `error` field is a human-readable validation detail. + content: + application/json: + schema: + $ref: '#/components/schemas/Error400' + Error401Response: + description: > + Unauthorized — missing or invalid `POLYMARKET-PROXY` / + `POLYMARKET-SECRET` + + credentials. `error` is `unauthorized`. + content: + application/json: + schema: + $ref: '#/components/schemas/Error401' + Error429Response: + description: > + Too Many Requests. `error` distinguishes the limit that was hit: + + `ip_rate_limited` (per-IP token bucket), `action_rate_limited` + (per-account + + action rate), or `open_orders_limit` (resting open-order cap). + headers: + Retry-After: + description: > + Whole seconds to wait before retrying. Present only on token-bucket + + rate-limit rejections (`ip_rate_limited` and `action_rate_limited`); + a + + conservative estimate of when enough capacity will have refilled to + + admit the request. Absent on `open_orders_limit`, which is a + capacity + + limit, not a rate limit — waiting does not free order slots; cancel + + resting orders or wait for fills instead. + schema: + type: integer + example: 2 + content: + application/json: + schema: + $ref: '#/components/schemas/Error429' + Error500Response: + description: | + Internal server error. `error` is `internal_error`. + content: + application/json: + schema: + $ref: '#/components/schemas/Error500' + securitySchemes: + polymarket_proxy: + type: apiKey + name: POLYMARKET-PROXY + in: header + description: Proxy address + polymarket_secret: + type: apiKey + name: POLYMARKET-SECRET + in: header + description: Correponding proxy secret + +```` \ No newline at end of file diff --git a/PolymarketDocumentation-main/docs/api-reference/authentication.md b/PolymarketDocumentation-main/docs/api-reference/authentication.md new file mode 100644 index 00000000..d099fd75 --- /dev/null +++ b/PolymarketDocumentation-main/docs/api-reference/authentication.md @@ -0,0 +1,437 @@ +> ## Documentation Index +> Fetch the complete documentation index at: https://docs.polymarket.com/llms.txt +> Use this file to discover all available pages before exploring further. + +# Authentication + +> How to authenticate requests to the CLOB API + +The CLOB API uses two levels of authentication: **L1 (Private Key)** and **L2 (API Key)**. Either can be accomplished using the CLOB client or REST API. + +## Public vs Authenticated + + + + The **Gamma API**, **Data API**, and CLOB read endpoints (orderbook, prices, spreads) require no authentication. + + + + CLOB trading endpoints (placing orders, cancellations, heartbeat) require all 5 `POLY_*` L2 HTTP headers. + + + +*** + +## Two-Level Authentication Model + +The CLOB uses two levels of authentication: L1 (Private Key) and L2 (API Key). Either can be accomplished using the CLOB client or REST API + +### L1 Authentication + +L1 authentication uses the wallet's private key to sign an EIP-712 message used in the request header. It proves ownership and control over the private key. The private key stays in control of the user and all trading activity remains non-custodial. + +**Used for:** + +* Creating API credentials +* Deriving existing API credentials +* Signing and creating user's orders locally + +### L2 Authentication + +L2 uses API credentials (apiKey, secret, passphrase) generated from L1 authentication. These are used solely to authenticate requests made to the CLOB API. Requests are signed using HMAC-SHA256. + +**Used for:** + +* Cancel or get user's open orders +* Check user's balances and allowances +* Post user's signed orders + + + Even with L2 authentication headers, methods that create user orders still + require the user to sign the order payload. + + +*** + +## Getting API Credentials + +Before making authenticated requests, you need to obtain API credentials using L1 authentication. + +### Using the SDK + + + + ```typescript theme={null} + import { ClobClient } from "@polymarket/clob-client-v2"; + import { createWalletClient, http } from "viem"; + import { privateKeyToAccount } from "viem/accounts"; + + const account = privateKeyToAccount(process.env.PRIVATE_KEY as `0x${string}`); + const signer = createWalletClient({ account, transport: http() }); + + const client = new ClobClient({ + host: "https://clob.polymarket.com", + chain: 137, // Polygon mainnet + signer, + }); + + // Creates new credentials or derives existing ones + const credentials = await client.createOrDeriveApiKey(); + + console.log(credentials); + // { + // key: "550e8400-e29b-41d4-a716-446655440000", + // secret: "base64EncodedSecretString", + // passphrase: "randomPassphraseString" + // } + ``` + + + + ```python theme={null} + from py_clob_client_v2 import ClobClient + import os + + client = ClobClient( + host="https://clob.polymarket.com", + chain_id=137, # Polygon mainnet + key=os.getenv("PRIVATE_KEY") + ) + + # Creates new credentials or derives existing ones + credentials = client.create_or_derive_api_key() + + print(credentials) + # { + # "apiKey": "550e8400-e29b-41d4-a716-446655440000", + # "secret": "base64EncodedSecretString", + # "passphrase": "randomPassphraseString" + # } + ``` + + + + ```rust theme={null} + use std::str::FromStr; + use polymarket_client_sdk_v2::POLYGON; + use polymarket_client_sdk_v2::auth::{LocalSigner, Signer}; + use polymarket_client_sdk_v2::clob::{Client, Config}; + + let private_key = std::env::var("POLYMARKET_PRIVATE_KEY")?; + let signer = LocalSigner::from_str(&private_key)? + .with_chain_id(Some(POLYGON)); + + // Creates new credentials or derives existing ones, + // then initializes the authenticated client — all in one step + let client = Client::new("https://clob.polymarket.com", Config::default())? + .authentication_builder(&signer) + .authenticate() + .await?; + + let credentials = client.credentials(); + println!("API Key: {}", credentials.key()); + ``` + + + + + **Never commit private keys to version control.** Always use environment + variables or secure key management systems. + + +### Using the REST API + +While we highly recommend using our provided clients to handle signing and authentication, the following is for developers who choose NOT to use our [Python](https://github.com/Polymarket/py-clob-client-v2) or [TypeScript](https://github.com/Polymarket/clob-client-v2) clients. + +**Create API Credentials** + +```bash theme={null} +POST https://clob.polymarket.com/auth/api-key +``` + +**Derive API Credentials** + +```bash theme={null} +GET https://clob.polymarket.com/auth/derive-api-key +``` + +Required L1 headers: + +| Header | Description | +| ---------------- | ---------------------- | +| `POLY_ADDRESS` | Polygon signer address | +| `POLY_SIGNATURE` | CLOB EIP-712 signature | +| `POLY_TIMESTAMP` | Current UNIX timestamp | +| `POLY_NONCE` | Nonce (default: 0) | + +The `POLY_SIGNATURE` is generated by signing the following EIP-712 struct: + + + + ```typescript TypeScript theme={null} + const domain = { + name: "ClobAuthDomain", + version: "1", + chainId: chainId, // Polygon Chain ID 137 + }; + + const types = { + ClobAuth: [ + { name: "address", type: "address" }, + { name: "timestamp", type: "string" }, + { name: "nonce", type: "uint256" }, + { name: "message", type: "string" }, + ], + }; + + const value = { + address: signingAddress, // The Signing address + timestamp: ts, // The CLOB API server timestamp + nonce: nonce, // The nonce used + message: "This message attests that I control the given wallet", + }; + + const sig = await signer._signTypedData(domain, types, value); + ``` + + ```python Python theme={null} + domain = { + "name": "ClobAuthDomain", + "version": "1", + "chainId": chainId, # Polygon Chain ID 137 + } + + types = { + "ClobAuth": [ + {"name": "address", "type": "address"}, + {"name": "timestamp", "type": "string"}, + {"name": "nonce", "type": "uint256"}, + {"name": "message", "type": "string"}, + ] + } + + value = { + "address": signingAddress, # The signing address + "timestamp": ts, # The CLOB API server timestamp + "nonce": nonce, # The nonce used + "message": "This message attests that I control the given wallet", + } + + sig = signer.sign_typed_data(domain, types, value) + ``` + + + +Reference implementations: + +* [TypeScript](https://github.com/Polymarket/clob-client-v2/blob/main/src/signing/eip712.ts) +* [Python](https://github.com/Polymarket/py-clob-client-v2/blob/main/py_clob_client_v2/signing/eip712.py) + +Response: + +```json theme={null} +{ + "apiKey": "550e8400-e29b-41d4-a716-446655440000", + "secret": "base64EncodedSecretString", + "passphrase": "randomPassphraseString" +} +``` + +**You'll need all three values for L2 authentication.** + +*** + +## L2 Authentication Headers + +All trading endpoints require these 5 headers: + +| Header | Description | +| ----------------- | ----------------------------- | +| `POLY_ADDRESS` | Polygon signer address | +| `POLY_SIGNATURE` | HMAC signature for request | +| `POLY_TIMESTAMP` | Current UNIX timestamp | +| `POLY_API_KEY` | User's API `apiKey` value | +| `POLY_PASSPHRASE` | User's API `passphrase` value | + +The `POLY_SIGNATURE` for L2 is an HMAC-SHA256 signature created using the user's API credentials `secret` value. Reference implementations can be found in the [TypeScript](https://github.com/Polymarket/clob-client-v2/blob/main/src/signing/hmac.ts) and [Python](https://github.com/Polymarket/py-clob-client-v2/blob/main/py_clob_client_v2/signing/hmac.py) clients. + +### CLOB Client + + + + ```typescript theme={null} + import { ClobClient, Side } from "@polymarket/clob-client-v2"; + import { createWalletClient, http } from "viem"; + import { privateKeyToAccount } from "viem/accounts"; + + const account = privateKeyToAccount(process.env.PRIVATE_KEY as `0x${string}`); + const signer = createWalletClient({ account, transport: http() }); + const depositWalletAddress = process.env.DEPOSIT_WALLET_ADDRESS!; + + const client = new ClobClient({ + host: "https://clob.polymarket.com", + chain: 137, + signer, + creds: apiCreds, // Generated from L1 auth, API credentials enable L2 methods + signatureType: 3, // POLY_1271, explained below + funderAddress: depositWalletAddress, // deposit wallet funder + }); + + // Now you can trade! + const order = await client.createAndPostOrder( + { tokenID: "123456", price: 0.65, size: 100, side: Side.BUY }, + { tickSize: "0.01", negRisk: false } + ); + ``` + + + + ```python theme={null} + from py_clob_client_v2 import ClobClient, OrderArgs, PartialCreateOrderOptions + from py_clob_client_v2.order_builder.constants import BUY + import os + + client = ClobClient( + host="https://clob.polymarket.com", + chain_id=137, + key=os.getenv("PRIVATE_KEY"), + creds=api_creds, # Generated from L1 auth, API credentials enable L2 methods + signature_type=3, # POLY_1271, explained below + funder=os.getenv("DEPOSIT_WALLET_ADDRESS") + ) + + # Now you can trade! + order = client.create_and_post_order( + OrderArgs(token_id="123456", price=0.65, size=100, side=BUY), + options=PartialCreateOrderOptions(tick_size="0.01", neg_risk=False), + ) + ``` + + + + ```rust theme={null} + use polymarket_client_sdk_v2::clob::types::{Side, SignatureType}; + use polymarket_client_sdk_v2::types::dec; + + let deposit_wallet = std::env::var("DEPOSIT_WALLET_ADDRESS")?.parse()?; + + let client = Client::new("https://clob.polymarket.com", Config::default())? + .authentication_builder(&signer) + .funder(deposit_wallet) + .signature_type(SignatureType::Poly1271) + .authenticate() + .await?; + + // Now you can trade! + let order = client.limit_order() + .token_id("123456".parse()?) + .price(dec!(0.65)) + .size(dec!(100)) + .side(Side::Buy) + .build().await?; + let signed = client.sign(&signer, order).await?; + let response = client.post_order(signed).await?; + ``` + + + + + Even with L2 authentication headers, methods that create user orders still + require the user to sign the order payload. + + +*** + +## Signature Types and Funder + +When initializing the L2 client, you must specify your wallet **signatureType** and the **funder** address which holds the funds: + +| Signature Type | Value | Description | +| -------------- | ----- | -------------------------------------------------------------------------------------------------------------------------- | +| EOA | `0` | Standard Ethereum wallet (MetaMask). Funder is the EOA address and will need POL to pay gas on transactions. | +| POLY\_PROXY | `1` | Existing Polymarket proxy wallet flow, commonly used by users who logged in via Magic Link email/Google. | +| GNOSIS\_SAFE | `2` | Existing Gnosis Safe wallet flow. Existing Safe users can continue using this type. | +| POLY\_1271 | `3` | Deposit wallet flow for new API users. The funder is the deposit wallet address and orders are validated through ERC-1271. | + + + New API users should use deposit wallets with `POLY_1271`. Existing Safe and + Proxy users are unaffected and can keep using their current funder address and + signature type. See the [Deposit Wallet Guide](/trading/deposit-wallets) for + setup details. + + +*** + +## Security Best Practices + + + + Store private keys in environment variables or secure key management systems. Never commit them to version control. + + ```bash theme={null} + # .env (never commit this file) + PRIVATE_KEY=0x... + ``` + + + + Never expose your API secret in client-side code. All authenticated requests should originate from your backend. + + + +*** + +## Troubleshooting + + + + Your wallet's private key is incorrect or improperly formatted. + + **Solutions:** + + * Verify your private key is a valid hex string (starts with "0x") + * Ensure you're using the correct key for the intended address + * Check that the key has proper permissions + + + + The nonce you provided has already been used to create an API key. + + **Solutions:** + + * Use `deriveApiKey()` with the same nonce to retrieve existing credentials + * Or use a different nonce with `createApiKey()` + + + + Your funder address is incorrect or doesn't match your wallet. + + **Solution:** Check your Polymarket profile address at [polymarket.com/settings](https://polymarket.com/settings). + + If it does not exist or user has never logged into Polymarket.com, deploy it first before creating L2 authentication. + + + + Unfortunately, there's no way to recover lost API credentials without the nonce. You'll need to create new credentials: + + ```typescript theme={null} + // Create fresh credentials with a new nonce + const newCreds = await client.createApiKey(); + // Save the nonce this time! + ``` + + + +*** + +## Next Steps + + + + Learn how to create and submit orders. + + + + Check trading availability by region. + + diff --git a/PolymarketDocumentation-main/docs/api-reference/bridge/create-bridge-addresses.md b/PolymarketDocumentation-main/docs/api-reference/bridge/create-bridge-addresses.md new file mode 100644 index 00000000..cc2bee95 --- /dev/null +++ b/PolymarketDocumentation-main/docs/api-reference/bridge/create-bridge-addresses.md @@ -0,0 +1,128 @@ +> ## Documentation Index +> Fetch the complete documentation index at: https://docs.polymarket.com/llms.txt +> Use this file to discover all available pages before exploring further. + +# Create bridge addresses + + + +## OpenAPI + +````yaml /api-spec/bridge-openapi.yaml post /deposit +openapi: 3.0.3 +info: + title: Polymarket Bridge API + version: 1.0.0 + description: HTTP API for Polymarket bridge and swap operations. +servers: + - url: https://bridge.polymarket.com + description: Polymarket Bridge API +security: [] +tags: + - name: Bridge + description: Bridge and swap operations for Polymarket +paths: + /deposit: + post: + tags: + - Bridge + summary: Create bridge addresses + parameters: + - $ref: '#/components/parameters/BuilderCodeHeader' + requestBody: + required: true + content: + application/json: + schema: + $ref: '#/components/schemas/DepositRequest' + example: + address: '0x56687bf447db6ffa42ffe2204a05edaa20f55839' + responses: + '201': + description: Bridge addresses created successfully + content: + application/json: + schema: + $ref: '#/components/schemas/DepositResponse' + '400': + description: >- + Bad Request - Invalid address, request body, or malformed + X-Builder-Code + content: + application/json: + schema: + $ref: '#/components/schemas/ErrorResponse' + '500': + description: Server Error + content: + application/json: + schema: + $ref: '#/components/schemas/ErrorResponse' +components: + parameters: + BuilderCodeHeader: + name: X-Builder-Code + in: header + required: false + description: > + Optional builder code (bytes32 hex) attributing this request to your + integration so transfer issues can be traced to your app. Omitting it + still succeeds but returns a `missing_builder_code` warning; a malformed + code returns 400. Get your code at + https://polymarket.com/settings?tab=builder + schema: + type: string + pattern: ^0x[a-fA-F0-9]{64}$ + example: '0x00000000000000000000000000000000000000000000000000000000abcd1234' + schemas: + DepositRequest: + type: object + required: + - address + properties: + address: + $ref: '#/components/schemas/Address' + description: >- + Your Polymarket wallet address where deposited funds will be + credited as pUSD + DepositResponse: + type: object + properties: + address: + type: object + description: Bridge addresses for different blockchain networks + properties: + evm: + type: string + description: >- + EVM-compatible bridge address (Ethereum, Polygon, Arbitrum, + Base, etc.) + example: '0x23566f8b2E82aDfCf01846E54899d110e97AC053' + svm: + type: string + description: Solana Virtual Machine bridge address + example: CrvTBvzryYxBHbWu2TiQpcqD5M7Le7iBKzVmEj3f36Jb + btc: + type: string + description: Bitcoin bridge address + example: bc1q8eau83qffxcj8ht4hsjdza3lha9r3egfqysj3g + note: + type: string + description: Additional information about the bridge addresses + example: >- + Only certain chains and tokens are supported. See /supported-assets + for details. + ErrorResponse: + type: object + properties: + error: + type: string + required: + - error + Address: + type: string + description: Ethereum address (0x-prefixed, 40 hex chars) + pattern: ^0x[a-fA-F0-9]{40}$ + example: '0x56687bf447db6ffa42ffe2204a05edaa20f55839' + +```` \ No newline at end of file diff --git a/PolymarketDocumentation-main/docs/api-reference/bridge/create-withdrawal-addresses.md b/PolymarketDocumentation-main/docs/api-reference/bridge/create-withdrawal-addresses.md new file mode 100644 index 00000000..36cc3478 --- /dev/null +++ b/PolymarketDocumentation-main/docs/api-reference/bridge/create-withdrawal-addresses.md @@ -0,0 +1,152 @@ +> ## Documentation Index +> Fetch the complete documentation index at: https://docs.polymarket.com/llms.txt +> Use this file to discover all available pages before exploring further. + +# Create withdrawal addresses + + + +## OpenAPI + +````yaml /api-spec/bridge-openapi.yaml post /withdraw +openapi: 3.0.3 +info: + title: Polymarket Bridge API + version: 1.0.0 + description: HTTP API for Polymarket bridge and swap operations. +servers: + - url: https://bridge.polymarket.com + description: Polymarket Bridge API +security: [] +tags: + - name: Bridge + description: Bridge and swap operations for Polymarket +paths: + /withdraw: + post: + tags: + - Bridge + summary: Create withdrawal addresses + parameters: + - $ref: '#/components/parameters/BuilderCodeHeader' + requestBody: + required: true + content: + application/json: + schema: + $ref: '#/components/schemas/WithdrawalRequest' + example: + address: '0x9156dd10bea4c8d7e2d591b633d1694b1d764756' + toChainId: '1' + toTokenAddress: '0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48' + recipientAddr: '0xd8dA6BF26964aF9D7eEd9e03E53415D37aA96045' + responses: + '201': + description: Withdrawal addresses created successfully + content: + application/json: + schema: + $ref: '#/components/schemas/DepositResponse' + example: + address: + evm: '0x23566f8b2E82aDfCf01846E54899d110e97AC053' + svm: CrvTBvzryYxBHbWu2TiQpcqD5M7Le7iBKzVmEj3f36Jb + btc: bc1q8eau83qffxcj8ht4hsjdza3lha9r3egfqysj3g + note: >- + Send funds to these addresses to bridge to your destination + chain and token. + '400': + description: Bad Request - Invalid/missing parameters or malformed X-Builder-Code + content: + application/json: + schema: + $ref: '#/components/schemas/ErrorResponse' + '500': + description: Server Error + content: + application/json: + schema: + $ref: '#/components/schemas/ErrorResponse' +components: + parameters: + BuilderCodeHeader: + name: X-Builder-Code + in: header + required: false + description: > + Optional builder code (bytes32 hex) attributing this request to your + integration so transfer issues can be traced to your app. Omitting it + still succeeds but returns a `missing_builder_code` warning; a malformed + code returns 400. Get your code at + https://polymarket.com/settings?tab=builder + schema: + type: string + pattern: ^0x[a-fA-F0-9]{64}$ + example: '0x00000000000000000000000000000000000000000000000000000000abcd1234' + schemas: + WithdrawalRequest: + type: object + required: + - address + - toChainId + - toTokenAddress + - recipientAddr + properties: + address: + $ref: '#/components/schemas/Address' + description: Source Polymarket wallet address on Polygon + toChainId: + type: string + description: >- + Destination chain ID (e.g., "1" for Ethereum, "8453" for Base, + "1151111081099710" for Solana) + example: '1' + toTokenAddress: + type: string + description: Destination token contract address + example: '0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48' + recipientAddr: + type: string + description: Destination wallet address where funds will be sent + example: '0xd8dA6BF26964aF9D7eEd9e03E53415D37aA96045' + DepositResponse: + type: object + properties: + address: + type: object + description: Bridge addresses for different blockchain networks + properties: + evm: + type: string + description: >- + EVM-compatible bridge address (Ethereum, Polygon, Arbitrum, + Base, etc.) + example: '0x23566f8b2E82aDfCf01846E54899d110e97AC053' + svm: + type: string + description: Solana Virtual Machine bridge address + example: CrvTBvzryYxBHbWu2TiQpcqD5M7Le7iBKzVmEj3f36Jb + btc: + type: string + description: Bitcoin bridge address + example: bc1q8eau83qffxcj8ht4hsjdza3lha9r3egfqysj3g + note: + type: string + description: Additional information about the bridge addresses + example: >- + Only certain chains and tokens are supported. See /supported-assets + for details. + ErrorResponse: + type: object + properties: + error: + type: string + required: + - error + Address: + type: string + description: Ethereum address (0x-prefixed, 40 hex chars) + pattern: ^0x[a-fA-F0-9]{40}$ + example: '0x56687bf447db6ffa42ffe2204a05edaa20f55839' + +```` \ No newline at end of file diff --git a/PolymarketDocumentation-main/docs/api-reference/bridge/get-a-quote.md b/PolymarketDocumentation-main/docs/api-reference/bridge/get-a-quote.md new file mode 100644 index 00000000..10970e29 --- /dev/null +++ b/PolymarketDocumentation-main/docs/api-reference/bridge/get-a-quote.md @@ -0,0 +1,224 @@ +> ## Documentation Index +> Fetch the complete documentation index at: https://docs.polymarket.com/llms.txt +> Use this file to discover all available pages before exploring further. + +# Get a quote + + + +## OpenAPI + +````yaml /api-spec/bridge-openapi.yaml post /quote +openapi: 3.0.3 +info: + title: Polymarket Bridge API + version: 1.0.0 + description: HTTP API for Polymarket bridge and swap operations. +servers: + - url: https://bridge.polymarket.com + description: Polymarket Bridge API +security: [] +tags: + - name: Bridge + description: Bridge and swap operations for Polymarket +paths: + /quote: + post: + tags: + - Bridge + summary: Get a quote + requestBody: + required: true + content: + application/json: + schema: + $ref: '#/components/schemas/QuoteRequest' + example: + fromAmountBaseUnit: '10000000' + fromChainId: '137' + fromTokenAddress: '0x3c499c542cEF5E3811e1192ce70d8cC03d5c3359' + recipientAddress: '0x17eC161f126e82A8ba337f4022d574DBEaFef575' + toChainId: '137' + toTokenAddress: '0xC011a7E12a19f7B1f670d46F03B03f3342E82DFB' + responses: + '200': + description: Quote retrieved successfully + content: + application/json: + schema: + $ref: '#/components/schemas/QuoteResponse' + example: + estCheckoutTimeMs: 25000 + estFeeBreakdown: + appFeeLabel: Fun.xyz fee + appFeePercent: 0 + appFeeUsd: 0 + fillCostPercent: 0 + fillCostUsd: 0 + gasUsd: 0.003854 + maxSlippage: 0 + minReceived: 14.488305 + swapImpact: 0 + swapImpactUsd: 0 + totalImpact: 0 + totalImpactUsd: 0 + estInputUsd: 14.488305 + estOutputUsd: 14.488305 + estToTokenBaseUnit: '14491203' + quoteId: >- + 0x00c34ba467184b0146406d62b0e60aaa24ed52460bd456222b6155a0d9de0ad5 + '400': + description: Bad Request - Missing required field + content: + application/json: + schema: + $ref: '#/components/schemas/ErrorResponse' + examples: + missingFromAmount: + value: + error: fromAmountBaseUnit is required + missingFromChainId: + value: + error: fromChainId is required + missingFromTokenAddress: + value: + error: fromTokenAddress is required + missingRecipientAddress: + value: + error: recipientAddress is required + missingToChainId: + value: + error: toChainId is required + missingToTokenAddress: + value: + error: toTokenAddress is required + '500': + description: Server Error + content: + application/json: + schema: + $ref: '#/components/schemas/ErrorResponse' + example: + error: cannot get quote +components: + schemas: + QuoteRequest: + type: object + required: + - fromAmountBaseUnit + - fromChainId + - fromTokenAddress + - recipientAddress + - toChainId + - toTokenAddress + properties: + fromAmountBaseUnit: + type: string + description: Amount of tokens to send + example: '10000000' + fromChainId: + type: string + description: Source Chain ID + example: '137' + fromTokenAddress: + type: string + description: Source token address + example: '0x3c499c542cEF5E3811e1192ce70d8cC03d5c3359' + recipientAddress: + type: string + description: Address of the recipient + example: '0x17eC161f126e82A8ba337f4022d574DBEaFef575' + toChainId: + type: string + description: Destination Chain ID + example: '137' + toTokenAddress: + type: string + description: Destination token address + example: '0xC011a7E12a19f7B1f670d46F03B03f3342E82DFB' + QuoteResponse: + type: object + properties: + estCheckoutTimeMs: + type: integer + description: Estimated time to complete the checkout in milliseconds + example: 25000 + estFeeBreakdown: + $ref: '#/components/schemas/FeeBreakdown' + estInputUsd: + type: number + description: Estimated token amount received in USD + example: 14.488305 + estOutputUsd: + type: number + description: Estimated token amount sent in USD + example: 14.488305 + estToTokenBaseUnit: + type: string + description: Estimated token amount received + example: '14491203' + quoteId: + type: string + description: Unique quote id of the request + example: '0x00c34ba467184b0146406d62b0e60aaa24ed52460bd456222b6155a0d9de0ad5' + ErrorResponse: + type: object + properties: + error: + type: string + required: + - error + FeeBreakdown: + type: object + description: Breakdown of the estimated fees + properties: + appFeeLabel: + type: string + description: Label of the app fee + example: Fun.xyz fee + appFeePercent: + type: number + description: App fees as a percentage of the total amount sent + example: 0 + appFeeUsd: + type: number + description: App fees in USD + example: 0 + fillCostPercent: + type: number + description: Fill cost percentage of the total amount sent + example: 0 + fillCostUsd: + type: number + description: Fill cost in USD + example: 0 + gasUsd: + type: number + description: Gas fee in USD + example: 0.003854 + maxSlippage: + type: number + description: Maximum potential slippage as a percentage + example: 0 + minReceived: + type: number + description: Amount after factoring slippage + example: 14.488305 + swapImpact: + type: number + description: Swap impact as a percentage of the total amount sent + example: 0 + swapImpactUsd: + type: number + description: Swap impact of the transaction in USD + example: 0 + totalImpact: + type: number + description: Total impact as a percentage of the total amount sent + example: 0 + totalImpactUsd: + type: number + description: Impact cost of the transaction + example: 0 + +```` \ No newline at end of file diff --git a/PolymarketDocumentation-main/docs/api-reference/bridge/get-supported-assets.md b/PolymarketDocumentation-main/docs/api-reference/bridge/get-supported-assets.md new file mode 100644 index 00000000..b5cd652c --- /dev/null +++ b/PolymarketDocumentation-main/docs/api-reference/bridge/get-supported-assets.md @@ -0,0 +1,99 @@ +> ## Documentation Index +> Fetch the complete documentation index at: https://docs.polymarket.com/llms.txt +> Use this file to discover all available pages before exploring further. + +# Get supported assets + + + +## OpenAPI + +````yaml /api-spec/bridge-openapi.yaml get /supported-assets +openapi: 3.0.3 +info: + title: Polymarket Bridge API + version: 1.0.0 + description: HTTP API for Polymarket bridge and swap operations. +servers: + - url: https://bridge.polymarket.com + description: Polymarket Bridge API +security: [] +tags: + - name: Bridge + description: Bridge and swap operations for Polymarket +paths: + /supported-assets: + get: + tags: + - Bridge + summary: Get supported assets + responses: + '200': + description: Successfully retrieved supported assets + content: + application/json: + schema: + $ref: '#/components/schemas/SupportedAssetsResponse' + '500': + description: Server Error + content: + application/json: + schema: + $ref: '#/components/schemas/ErrorResponse' +components: + schemas: + SupportedAssetsResponse: + type: object + properties: + supportedAssets: + type: array + items: + $ref: '#/components/schemas/SupportedAsset' + description: >- + List of supported assets with minimum amounts for deposits and + withdrawals + ErrorResponse: + type: object + properties: + error: + type: string + required: + - error + SupportedAsset: + type: object + properties: + chainId: + type: string + description: Chain ID + example: '1' + chainName: + type: string + description: Human-readable chain name + example: Ethereum + token: + $ref: '#/components/schemas/Token' + minCheckoutUsd: + type: number + description: Minimum amount in USD for deposits and withdrawals + example: 45 + Token: + type: object + properties: + name: + type: string + description: Full token name + example: USD Coin + symbol: + type: string + description: Token symbol + example: USDC + address: + type: string + description: Token contract address + example: '0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48' + decimals: + type: integer + description: Token decimals + example: 6 + +```` \ No newline at end of file diff --git a/PolymarketDocumentation-main/docs/api-reference/bridge/get-transaction-status.md b/PolymarketDocumentation-main/docs/api-reference/bridge/get-transaction-status.md new file mode 100644 index 00000000..f4c340d4 --- /dev/null +++ b/PolymarketDocumentation-main/docs/api-reference/bridge/get-transaction-status.md @@ -0,0 +1,154 @@ +> ## Documentation Index +> Fetch the complete documentation index at: https://docs.polymarket.com/llms.txt +> Use this file to discover all available pages before exploring further. + +# Get transaction status + + + +## OpenAPI + +````yaml /api-spec/bridge-openapi.yaml get /status/{address} +openapi: 3.0.3 +info: + title: Polymarket Bridge API + version: 1.0.0 + description: HTTP API for Polymarket bridge and swap operations. +servers: + - url: https://bridge.polymarket.com + description: Polymarket Bridge API +security: [] +tags: + - name: Bridge + description: Bridge and swap operations for Polymarket +paths: + /status/{address}: + get: + tags: + - Bridge + summary: Get transaction status + parameters: + - name: address + in: path + required: true + description: >- + The address to query for transaction status (EVM, SVM, or BTC + address from the `/deposit` or `/withdraw` response) + schema: + type: string + example: EXoZue2avJae1d45B3fVw2unhkrtToSYQqHtHgfZ2cbE + responses: + '200': + description: Successfully retrieved transaction status + content: + application/json: + schema: + $ref: '#/components/schemas/TransactionStatusResponse' + example: + transactions: + - fromChainId: '1151111081099710' + fromTokenAddress: '11111111111111111111111111111111' + fromAmountBaseUnit: '13566635' + toChainId: '137' + toTokenAddress: '0xC011a7E12a19f7B1f670d46F03B03f3342E82DFB' + status: DEPOSIT_DETECTED + - fromChainId: '1151111081099710' + fromTokenAddress: '11111111111111111111111111111111' + fromAmountBaseUnit: '13400000' + toChainId: '137' + toTokenAddress: '0xC011a7E12a19f7B1f670d46F03B03f3342E82DFB' + createdTimeMs: 1757646914535 + status: PROCESSING + - fromChainId: '1151111081099710' + fromTokenAddress: '11111111111111111111111111111111' + fromAmountBaseUnit: '13500152' + toChainId: '137' + toTokenAddress: '0xC011a7E12a19f7B1f670d46F03B03f3342E82DFB' + txHash: >- + 3atr19NAiNCYt24RHM1WnzZp47RXskpTDzspJoCBBaMFwUB8fk37hFkxz35P5UEnnmWz21rb2t5wJ8pq3EE2XnxU + createdTimeMs: 1757531217339 + status: COMPLETED + '400': + description: Bad Request - Missing address parameter + content: + application/json: + schema: + $ref: '#/components/schemas/ErrorResponse' + example: + error: address is required + '500': + description: Server Error + content: + application/json: + schema: + $ref: '#/components/schemas/ErrorResponse' + example: + error: cannot get transaction status +components: + schemas: + TransactionStatusResponse: + type: object + properties: + transactions: + type: array + items: + $ref: '#/components/schemas/Transaction' + description: List of transactions for the given address + ErrorResponse: + type: object + properties: + error: + type: string + required: + - error + Transaction: + type: object + properties: + fromChainId: + type: string + description: Source chain ID + example: '1151111081099710' + fromTokenAddress: + type: string + description: Source token contract address + example: '11111111111111111111111111111111' + fromAmountBaseUnit: + type: string + description: Amount in base units (without decimals) + example: '13566635' + toChainId: + type: string + description: Destination chain ID + example: '137' + toTokenAddress: + type: string + description: Destination token contract address + example: '0xC011a7E12a19f7B1f670d46F03B03f3342E82DFB' + status: + type: string + description: > + Current status of the transaction. If a transaction fails, remains + stuck, or funds are held due to a compliance check, direct users to + our Bridge API provider's support + (https://intercom.help/funxyz/en/articles/10732578-contact-us). + enum: + - DEPOSIT_DETECTED + - PROCESSING + - ORIGIN_TX_CONFIRMED + - SUBMITTED + - COMPLETED + - FAILED + example: COMPLETED + txHash: + type: string + description: Transaction hash (only available when status is COMPLETED) + example: >- + 3atr19NAiNCYt24RHM1WnzZp47RXskpTDzspJoCBBaMFwUB8fk37hFkxz35P5UEnnmWz21rb2t5wJ8pq3EE2XnxU + createdTimeMs: + type: number + description: >- + Unix timestamp in milliseconds when transaction was created (missing + when status is DEPOSIT_DETECTED) + example: 1757531217339 + +```` \ No newline at end of file diff --git a/PolymarketDocumentation-main/docs/api-reference/builders/get-aggregated-builder-leaderboard.md b/PolymarketDocumentation-main/docs/api-reference/builders/get-aggregated-builder-leaderboard.md new file mode 100644 index 00000000..68347555 --- /dev/null +++ b/PolymarketDocumentation-main/docs/api-reference/builders/get-aggregated-builder-leaderboard.md @@ -0,0 +1,122 @@ +> ## Documentation Index +> Fetch the complete documentation index at: https://docs.polymarket.com/llms.txt +> Use this file to discover all available pages before exploring further. + +# Get aggregated builder leaderboard + + + +## OpenAPI + +````yaml /api-spec/data-openapi.yaml get /v1/builders/leaderboard +openapi: 3.0.3 +info: + title: Polymarket Data API + version: 1.0.0 + description: > + HTTP API for Polymarket data. This specification documents all public + routes. +servers: + - url: https://data-api.polymarket.com + description: Relative server (same host) +security: [] +tags: + - name: Data API Status + description: Data API health check + - name: Core + - name: Builders + - name: Misc +paths: + /v1/builders/leaderboard: + get: + tags: + - Builders + summary: Get aggregated builder leaderboard + parameters: + - in: query + name: timePeriod + schema: + type: string + enum: + - DAY + - WEEK + - MONTH + - ALL + default: DAY + description: | + The time period to aggregate results over. + - in: query + name: limit + schema: + type: integer + default: 25 + minimum: 0 + maximum: 50 + description: Maximum number of builders to return + - in: query + name: offset + schema: + type: integer + default: 0 + minimum: 0 + maximum: 1000 + description: Starting index for pagination + responses: + '200': + description: Success + content: + application/json: + schema: + type: array + items: + $ref: '#/components/schemas/LeaderboardEntry' + '400': + description: Bad Request + content: + application/json: + schema: + $ref: '#/components/schemas/ErrorResponse' + '500': + description: Server Error + content: + application/json: + schema: + $ref: '#/components/schemas/ErrorResponse' +components: + schemas: + LeaderboardEntry: + type: object + properties: + rank: + type: string + description: The rank position of the builder + builder: + type: string + description: The builder name or identifier + builderCode: + type: string + description: >- + The builder's onchain attribution code as attached to orders via + `builderCode` (see CLOB V2). Empty string for legacy builders + without a registered code. + volume: + type: number + description: Total trading volume attributed to this builder + activeUsers: + type: integer + description: Number of active users for this builder + verified: + type: boolean + description: Whether the builder is verified + builderLogo: + type: string + description: URL to the builder's logo image + ErrorResponse: + type: object + properties: + error: + type: string + required: + - error + +```` \ No newline at end of file diff --git a/PolymarketDocumentation-main/docs/api-reference/builders/get-daily-builder-volume-time-series.md b/PolymarketDocumentation-main/docs/api-reference/builders/get-daily-builder-volume-time-series.md new file mode 100644 index 00000000..32568449 --- /dev/null +++ b/PolymarketDocumentation-main/docs/api-reference/builders/get-daily-builder-volume-time-series.md @@ -0,0 +1,111 @@ +> ## Documentation Index +> Fetch the complete documentation index at: https://docs.polymarket.com/llms.txt +> Use this file to discover all available pages before exploring further. + +# Get daily builder volume time-series + + + +## OpenAPI + +````yaml /api-spec/data-openapi.yaml get /v1/builders/volume +openapi: 3.0.3 +info: + title: Polymarket Data API + version: 1.0.0 + description: > + HTTP API for Polymarket data. This specification documents all public + routes. +servers: + - url: https://data-api.polymarket.com + description: Relative server (same host) +security: [] +tags: + - name: Data API Status + description: Data API health check + - name: Core + - name: Builders + - name: Misc +paths: + /v1/builders/volume: + get: + tags: + - Builders + summary: Get daily builder volume time-series + parameters: + - in: query + name: timePeriod + schema: + type: string + enum: + - DAY + - WEEK + - MONTH + - ALL + default: DAY + description: | + The time period to fetch daily records for. + responses: + '200': + description: Success - Returns array of daily volume records + content: + application/json: + schema: + type: array + items: + $ref: '#/components/schemas/BuilderVolumeEntry' + '400': + description: Bad Request + content: + application/json: + schema: + $ref: '#/components/schemas/ErrorResponse' + '500': + description: Server Error + content: + application/json: + schema: + $ref: '#/components/schemas/ErrorResponse' +components: + schemas: + BuilderVolumeEntry: + type: object + properties: + dt: + type: string + format: date-time + description: The timestamp for this volume entry in ISO 8601 format + example: '2025-11-15T00:00:00Z' + builder: + type: string + description: The builder name or identifier + builderCode: + type: string + description: >- + The builder's onchain attribution code as attached to orders via + `builderCode` (see CLOB V2). Empty string for legacy builders + without a registered code. + builderLogo: + type: string + description: URL to the builder's logo image + verified: + type: boolean + description: Whether the builder is verified + volume: + type: number + description: Trading volume for this builder on this date + activeUsers: + type: integer + description: Number of active users for this builder on this date + rank: + type: string + description: The rank position of the builder on this date + ErrorResponse: + type: object + properties: + error: + type: string + required: + - error + +```` \ No newline at end of file diff --git a/PolymarketDocumentation-main/docs/api-reference/cancel-orders-coid.md b/PolymarketDocumentation-main/docs/api-reference/cancel-orders-coid.md new file mode 100644 index 00000000..077ae154 --- /dev/null +++ b/PolymarketDocumentation-main/docs/api-reference/cancel-orders-coid.md @@ -0,0 +1,278 @@ +> ## Documentation Index +> Fetch the complete documentation index at: https://docs.polymarket.com/llms.txt +> Use this file to discover all available pages before exploring further. + +# Cancel Orders COID + +> Cancel orders by client order ID. +Requires proxy signature, see [proxy signing](/http/signing#2-proxy-signing). + + +Request Weight: **1 + floor(n / 20)** Action Weight: **0** + + +## OpenAPI + +````yaml /api-spec/perps-openapi.json delete /v1/trade/orders-coid +openapi: 3.0.3 +info: + title: Polymarket Perps HTTP API + version: 1.0.0 + description: HTTP API for Polymarket perpetual trading system. + license: + name: Apache 2.0 + url: https://www.apache.org/licenses/LICENSE-2.0.html +servers: + - url: https://api.perpetuals.polymarket.com + description: Production Perps HTTP API +security: [] +paths: + /v1/trade/orders-coid: + delete: + summary: Cancel Orders COID + description: > + Cancel orders by client order ID. + + Requires proxy signature, see [proxy + signing](/http/signing#2-proxy-signing). + operationId: cancelOrdersByCoid + requestBody: + description: Cancel by coid request. + content: + application/json: + schema: + $ref: '#/components/schemas/CancelByCoidRequest' + responses: + '200': + description: Cancel response. + content: + application/json: + schema: + type: array + items: + $ref: '#/components/schemas/CancelResponse' + '400': + $ref: '#/components/responses/Error400Response' + '429': + $ref: '#/components/responses/Error429Response' + '500': + $ref: '#/components/responses/Error500Response' + security: [] +components: + schemas: + CancelByCoidRequest: + allOf: + - type: object + required: + - op + properties: + op: + $ref: '#/components/schemas/OpCancelOrdersByCoid' + - $ref: '#/components/schemas/BaseOp' + - type: object + properties: + exp: + $ref: '#/components/schemas/exp' + CancelResponse: + oneOf: + - $ref: '#/components/schemas/CancelAccepted' + - $ref: '#/components/schemas/CancelRejected' + OpCancelOrdersByCoid: + type: object + required: + - type + - args + properties: + type: + type: string + enum: + - cancelOrdersCOID + args: + type: array + description: | + Array of client order IDs to cancel. Cancelling an order that has + attached take-profit / stop-loss children (see `CreateOrder.tr`) + cascades to those children — they are cancelled with reason + `ParentCancelled`. + items: + $ref: '#/components/schemas/coid' + BaseOp: + type: object + required: + - sig + - salt + - ts + properties: + sig: + $ref: '#/components/schemas/sig' + salt: + $ref: '#/components/schemas/salt' + ts: + $ref: '#/components/schemas/ts' + exp: + type: integer + description: >- + Command expiry timestamp in Unix milliseconds. If provided, it must be + in the future and within the gateway's default command timeout. It can + shorten request validity but cannot extend it. This is not an order + auto-cancel time. + example: 1767225600000 + CancelAccepted: + type: object + required: + - status + - oid + properties: + status: + type: string + enum: + - ok + oid: + $ref: '#/components/schemas/oid' + coid: + $ref: '#/components/schemas/coid' + description: Echoed only when the request carried a client_order_id. + CancelRejected: + type: object + required: + - status + - error + properties: + status: + type: string + enum: + - err + oid: + $ref: '#/components/schemas/oid' + coid: + $ref: '#/components/schemas/coid' + error: + $ref: '#/components/schemas/error' + Error400: + title: Error400 + type: object + required: + - status + - error + properties: + status: + type: string + enum: + - err + error: + $ref: '#/components/schemas/error' + Error429: + title: Error429 + type: object + required: + - status + - error + properties: + status: + type: string + enum: + - err + error: + $ref: '#/components/schemas/error' + Error500: + title: Error500 + type: object + required: + - status + - error + properties: + status: + type: string + enum: + - err + error: + $ref: '#/components/schemas/error' + coid: + type: string + description: Client order ID + minLength: 32 + maxLength: 32 + pattern: ^[0-9a-f]{32}$ + example: 550e8400e29b41d4a716446655440000 + sig: + type: string + description: Signature in hex format + example: 0x1234567890... + salt: + type: integer + description: Salt + example: 1234567890 + ts: + type: integer + description: >- + Request timestamp. Unix milliseconds for most operations; Unix seconds + for withdrawals (must match the on-chain EIP-712 struct verified against + block.timestamp). + example: 1767225600000 + oid: + type: integer + description: Order ID + example: 1234567890 + error: + type: string + description: >- + Error identifier. For domain rejections and transport errors + (`401`/`404`/`429`/`500`) this is a stable, machine-readable snake_case + identifier that is part of the API contract and safe to branch on, e.g. + `insufficient_margin`, `insufficient_balance`, `order_not_found`, + `reduce_only_invalid`, `unauthorized`, `not_found`. For `400` it is a + human-readable validation detail whose wording may change. See the Error + handling guide for the domain identifiers. (Post-only / Fill-or-Kill + outcomes are order statuses such as `post_only_rejected`, not + rejections.) + example: insufficient_margin + responses: + Error400Response: + description: | + Bad request — the request was malformed or failed validation (bad query + parameters, unparseable body, invalid signature, or a domain pre-check). + The `error` field is a human-readable validation detail. + content: + application/json: + schema: + $ref: '#/components/schemas/Error400' + Error429Response: + description: > + Too Many Requests. `error` distinguishes the limit that was hit: + + `ip_rate_limited` (per-IP token bucket), `action_rate_limited` + (per-account + + action rate), or `open_orders_limit` (resting open-order cap). + headers: + Retry-After: + description: > + Whole seconds to wait before retrying. Present only on token-bucket + + rate-limit rejections (`ip_rate_limited` and `action_rate_limited`); + a + + conservative estimate of when enough capacity will have refilled to + + admit the request. Absent on `open_orders_limit`, which is a + capacity + + limit, not a rate limit — waiting does not free order slots; cancel + + resting orders or wait for fills instead. + schema: + type: integer + example: 2 + content: + application/json: + schema: + $ref: '#/components/schemas/Error429' + Error500Response: + description: | + Internal server error. `error` is `internal_error`. + content: + application/json: + schema: + $ref: '#/components/schemas/Error500' + +```` \ No newline at end of file diff --git a/PolymarketDocumentation-main/docs/api-reference/cancel-orders.md b/PolymarketDocumentation-main/docs/api-reference/cancel-orders.md new file mode 100644 index 00000000..8922897c --- /dev/null +++ b/PolymarketDocumentation-main/docs/api-reference/cancel-orders.md @@ -0,0 +1,277 @@ +> ## Documentation Index +> Fetch the complete documentation index at: https://docs.polymarket.com/llms.txt +> Use this file to discover all available pages before exploring further. + +# Cancel Orders + +> Cancel orders. +Requires proxy signature, see [proxy signing](/http/signing#2-proxy-signing). + + +Request Weight: **1 + floor(n / 20)** Action Weight: **0** + + +## OpenAPI + +````yaml /api-spec/perps-openapi.json delete /v1/trade/orders +openapi: 3.0.3 +info: + title: Polymarket Perps HTTP API + version: 1.0.0 + description: HTTP API for Polymarket perpetual trading system. + license: + name: Apache 2.0 + url: https://www.apache.org/licenses/LICENSE-2.0.html +servers: + - url: https://api.perpetuals.polymarket.com + description: Production Perps HTTP API +security: [] +paths: + /v1/trade/orders: + delete: + summary: Cancel Orders + description: > + Cancel orders. + + Requires proxy signature, see [proxy + signing](/http/signing#2-proxy-signing). + operationId: cancelOrders + requestBody: + description: Cancel request. + content: + application/json: + schema: + $ref: '#/components/schemas/CancelRequest' + responses: + '200': + description: Cancel response. + content: + application/json: + schema: + type: array + items: + $ref: '#/components/schemas/CancelResponse' + '400': + $ref: '#/components/responses/Error400Response' + '429': + $ref: '#/components/responses/Error429Response' + '500': + $ref: '#/components/responses/Error500Response' + security: [] +components: + schemas: + CancelRequest: + allOf: + - type: object + required: + - op + properties: + op: + $ref: '#/components/schemas/OpCancelOrders' + - $ref: '#/components/schemas/BaseOp' + - type: object + properties: + exp: + $ref: '#/components/schemas/exp' + CancelResponse: + oneOf: + - $ref: '#/components/schemas/CancelAccepted' + - $ref: '#/components/schemas/CancelRejected' + OpCancelOrders: + type: object + required: + - type + - args + properties: + type: + type: string + enum: + - cancelOrders + args: + type: array + description: | + Array of order IDs to cancel. Cancelling an order that has attached + take-profit / stop-loss children (see `CreateOrder.tr`) cascades to + those children — they are cancelled with reason `ParentCancelled`. + items: + $ref: '#/components/schemas/oid' + BaseOp: + type: object + required: + - sig + - salt + - ts + properties: + sig: + $ref: '#/components/schemas/sig' + salt: + $ref: '#/components/schemas/salt' + ts: + $ref: '#/components/schemas/ts' + exp: + type: integer + description: >- + Command expiry timestamp in Unix milliseconds. If provided, it must be + in the future and within the gateway's default command timeout. It can + shorten request validity but cannot extend it. This is not an order + auto-cancel time. + example: 1767225600000 + CancelAccepted: + type: object + required: + - status + - oid + properties: + status: + type: string + enum: + - ok + oid: + $ref: '#/components/schemas/oid' + coid: + $ref: '#/components/schemas/coid' + description: Echoed only when the request carried a client_order_id. + CancelRejected: + type: object + required: + - status + - error + properties: + status: + type: string + enum: + - err + oid: + $ref: '#/components/schemas/oid' + coid: + $ref: '#/components/schemas/coid' + error: + $ref: '#/components/schemas/error' + Error400: + title: Error400 + type: object + required: + - status + - error + properties: + status: + type: string + enum: + - err + error: + $ref: '#/components/schemas/error' + Error429: + title: Error429 + type: object + required: + - status + - error + properties: + status: + type: string + enum: + - err + error: + $ref: '#/components/schemas/error' + Error500: + title: Error500 + type: object + required: + - status + - error + properties: + status: + type: string + enum: + - err + error: + $ref: '#/components/schemas/error' + oid: + type: integer + description: Order ID + example: 1234567890 + sig: + type: string + description: Signature in hex format + example: 0x1234567890... + salt: + type: integer + description: Salt + example: 1234567890 + ts: + type: integer + description: >- + Request timestamp. Unix milliseconds for most operations; Unix seconds + for withdrawals (must match the on-chain EIP-712 struct verified against + block.timestamp). + example: 1767225600000 + coid: + type: string + description: Client order ID + minLength: 32 + maxLength: 32 + pattern: ^[0-9a-f]{32}$ + example: 550e8400e29b41d4a716446655440000 + error: + type: string + description: >- + Error identifier. For domain rejections and transport errors + (`401`/`404`/`429`/`500`) this is a stable, machine-readable snake_case + identifier that is part of the API contract and safe to branch on, e.g. + `insufficient_margin`, `insufficient_balance`, `order_not_found`, + `reduce_only_invalid`, `unauthorized`, `not_found`. For `400` it is a + human-readable validation detail whose wording may change. See the Error + handling guide for the domain identifiers. (Post-only / Fill-or-Kill + outcomes are order statuses such as `post_only_rejected`, not + rejections.) + example: insufficient_margin + responses: + Error400Response: + description: | + Bad request — the request was malformed or failed validation (bad query + parameters, unparseable body, invalid signature, or a domain pre-check). + The `error` field is a human-readable validation detail. + content: + application/json: + schema: + $ref: '#/components/schemas/Error400' + Error429Response: + description: > + Too Many Requests. `error` distinguishes the limit that was hit: + + `ip_rate_limited` (per-IP token bucket), `action_rate_limited` + (per-account + + action rate), or `open_orders_limit` (resting open-order cap). + headers: + Retry-After: + description: > + Whole seconds to wait before retrying. Present only on token-bucket + + rate-limit rejections (`ip_rate_limited` and `action_rate_limited`); + a + + conservative estimate of when enough capacity will have refilled to + + admit the request. Absent on `open_orders_limit`, which is a + capacity + + limit, not a rate limit — waiting does not free order slots; cancel + + resting orders or wait for fills instead. + schema: + type: integer + example: 2 + content: + application/json: + schema: + $ref: '#/components/schemas/Error429' + Error500Response: + description: | + Internal server error. `error` is `internal_error`. + content: + application/json: + schema: + $ref: '#/components/schemas/Error500' + +```` \ No newline at end of file diff --git a/PolymarketDocumentation-main/docs/api-reference/check-invite-code.md b/PolymarketDocumentation-main/docs/api-reference/check-invite-code.md new file mode 100644 index 00000000..9b6e619c --- /dev/null +++ b/PolymarketDocumentation-main/docs/api-reference/check-invite-code.md @@ -0,0 +1,162 @@ +> ## Documentation Index +> Fetch the complete documentation index at: https://docs.polymarket.com/llms.txt +> Use this file to discover all available pages before exploring further. + +# Check Invite Code + +> Check whether an invite code can be used. When `address` is provided, the +response is invalid if that address already has an account. + + +Request Weight: **1** + + +## OpenAPI + +````yaml /api-spec/perps-openapi.json get /v1/info/invite +openapi: 3.0.3 +info: + title: Polymarket Perps HTTP API + version: 1.0.0 + description: HTTP API for Polymarket perpetual trading system. + license: + name: Apache 2.0 + url: https://www.apache.org/licenses/LICENSE-2.0.html +servers: + - url: https://api.perpetuals.polymarket.com + description: Production Perps HTTP API +security: [] +paths: + /v1/info/invite: + get: + summary: Check Invite Code + description: > + Check whether an invite code can be used. When `address` is provided, + the + + response is invalid if that address already has an account. + operationId: checkInviteCode + parameters: + - name: code + in: query + required: true + schema: + $ref: '#/components/schemas/code' + - name: address + in: query + required: false + schema: + $ref: '#/components/schemas/address' + responses: + '200': + description: Invite code validation response. + content: + application/json: + schema: + $ref: '#/components/schemas/InviteCheckResponse' + '429': + $ref: '#/components/responses/Error429Response' + '500': + $ref: '#/components/responses/Error500Response' + security: [] +components: + schemas: + code: + type: string + description: Referral or invite code + example: ABC123 + address: + type: string + description: Address + example: '0x1234567890abcdef1234567890abcdef12345678' + InviteCheckResponse: + type: object + required: + - valid + properties: + valid: + type: boolean + description: Whether the invite code can be used. + error: + type: string + description: Present when the invite code is invalid or unusable. + Error429: + title: Error429 + type: object + required: + - status + - error + properties: + status: + type: string + enum: + - err + error: + $ref: '#/components/schemas/error' + Error500: + title: Error500 + type: object + required: + - status + - error + properties: + status: + type: string + enum: + - err + error: + $ref: '#/components/schemas/error' + error: + type: string + description: >- + Error identifier. For domain rejections and transport errors + (`401`/`404`/`429`/`500`) this is a stable, machine-readable snake_case + identifier that is part of the API contract and safe to branch on, e.g. + `insufficient_margin`, `insufficient_balance`, `order_not_found`, + `reduce_only_invalid`, `unauthorized`, `not_found`. For `400` it is a + human-readable validation detail whose wording may change. See the Error + handling guide for the domain identifiers. (Post-only / Fill-or-Kill + outcomes are order statuses such as `post_only_rejected`, not + rejections.) + example: insufficient_margin + responses: + Error429Response: + description: > + Too Many Requests. `error` distinguishes the limit that was hit: + + `ip_rate_limited` (per-IP token bucket), `action_rate_limited` + (per-account + + action rate), or `open_orders_limit` (resting open-order cap). + headers: + Retry-After: + description: > + Whole seconds to wait before retrying. Present only on token-bucket + + rate-limit rejections (`ip_rate_limited` and `action_rate_limited`); + a + + conservative estimate of when enough capacity will have refilled to + + admit the request. Absent on `open_orders_limit`, which is a + capacity + + limit, not a rate limit — waiting does not free order slots; cancel + + resting orders or wait for fills instead. + schema: + type: integer + example: 2 + content: + application/json: + schema: + $ref: '#/components/schemas/Error429' + Error500Response: + description: | + Internal server error. `error` is `internal_error`. + content: + application/json: + schema: + $ref: '#/components/schemas/Error500' + +```` \ No newline at end of file diff --git a/PolymarketDocumentation-main/docs/api-reference/clients-sdks.md b/PolymarketDocumentation-main/docs/api-reference/clients-sdks.md new file mode 100644 index 00000000..af061da5 --- /dev/null +++ b/PolymarketDocumentation-main/docs/api-reference/clients-sdks.md @@ -0,0 +1,99 @@ +> ## Documentation Index +> Fetch the complete documentation index at: https://docs.polymarket.com/llms.txt +> Use this file to discover all available pages before exploring further. + +# Clients & SDKs + +> Official open-source libraries for interacting with Polymarket + +Polymarket provides official open-source clients in TypeScript, Python, and Rust. All three support the full CLOB API including market data, order management, and authentication. + +## Installation + + + ```bash TypeScript theme={null} + npm install @polymarket/clob-client-v2 viem + ``` + + ```bash Python theme={null} + pip install py-clob-client-v2 + ``` + + ```bash Rust theme={null} + cargo add polymarket_client_sdk_v2 --features clob + ``` + + +## Quick Example + + + ```typescript TypeScript theme={null} + import { ClobClient } from "@polymarket/clob-client-v2"; + + const client = new ClobClient({ + host: "https://clob.polymarket.com", + chain: 137, + signer, + creds: apiCreds, + }); + + const markets = await client.getMarkets(); + ``` + + ```python Python theme={null} + from py_clob_client_v2 import ClobClient + + client = ClobClient( + "https://clob.polymarket.com", + key=private_key, + chain_id=137, + creds=api_creds, + ) + + markets = client.get_markets() + ``` + + ```rust Rust theme={null} + use polymarket_client_sdk_v2::clob::{Client, Config}; + + let client = Client::new("https://clob.polymarket.com", Config::default())? + .authentication_builder(&signer) + .authenticate() + .await?; + + let markets = client.markets(None).await?; + ``` + + +## Source Code + +| Language | Package | Repository | +| ---------- | ---------------------------- | ------------------------------------------------------------------------------------------ | +| TypeScript | `@polymarket/clob-client-v2` | [github.com/Polymarket/clob-client-v2](https://github.com/Polymarket/clob-client-v2) | +| Python | `py-clob-client-v2` | [github.com/Polymarket/py-clob-client-v2](https://github.com/Polymarket/py-clob-client-v2) | +| Rust | `polymarket_client_sdk_v2` | [github.com/Polymarket/rs-clob-client-v2](https://github.com/Polymarket/rs-clob-client-v2) | + +Each repository includes working examples in the `/examples` directory. + +## Relayer SDK + +For [gasless transactions](/trading/gasless), the relayer client handles deposit +wallet creation and signed wallet batches for new API users. Existing Safe and +Proxy wallet flows remain supported. + +| Language | Package | Repository | +| ---------- | ------------------------------------ | ---------------------------------------------------------------------------------------------------------- | +| TypeScript | `@polymarket/builder-relayer-client` | [github.com/Polymarket/builder-relayer-client](https://github.com/Polymarket/builder-relayer-client) | +| Python | `py-builder-relayer-client` | [github.com/Polymarket/py-builder-relayer-client](https://github.com/Polymarket/py-builder-relayer-client) | + +## Next Steps + + + + Set up your client and place your first order. + + + + Understand L1/L2 auth and API credentials. + + diff --git a/PolymarketDocumentation-main/docs/api-reference/combo-markets/get-combo-markets.md b/PolymarketDocumentation-main/docs/api-reference/combo-markets/get-combo-markets.md new file mode 100644 index 00000000..693e009a --- /dev/null +++ b/PolymarketDocumentation-main/docs/api-reference/combo-markets/get-combo-markets.md @@ -0,0 +1,218 @@ +> ## Documentation Index +> Fetch the complete documentation index at: https://docs.polymarket.com/llms.txt +> Use this file to discover all available pages before exploring further. + +# Get combo markets + +> Returns active markets that can be used as combo legs, ordered by volume +descending. This endpoint is public and does not require CLOB +authentication. + +Entries in `position_ids`, `outcomes`, and `outcome_prices` correspond by +array index (`[0]` is YES, `[1]` is NO). Use `next_cursor` unchanged in +the next request; a value of `null` indicates the final page. + + + + +## OpenAPI + +````yaml /api-spec/combos-rfq-openapi.yaml get /v1/rfq/combo-markets +openapi: 3.1.0 +info: + title: Polymarket Combinatorial RFQ API + description: > + REST API for the combinatorial RFQ (Request for Quote) system. + + + This spec covers the publicly documented endpoints used by quoters (market + + makers): the combo-market catalog and the authenticated maker commands for + + submitting, cancelling, and confirming quotes. + + + Conventions: + + - All `*_e6` fields are six-decimal fixed-point values encoded as + **strings** + to avoid number precision issues. + - All timestamps are **Unix milliseconds** (integer); zero/omitted means + unset. + + - Errors return an HTTP status code with a body of the form `{ "error": + "..." }`. + license: + name: MIT + identifier: MIT + version: 1.0.0 +servers: + - url: https://combos-rfq-api.polymarket.com + description: Production combinatorial RFQ API +security: [] +tags: + - name: Combo Markets + description: Public catalog of markets that can be used as combo legs + - name: Maker + description: Authenticated quoter (maker) commands +paths: + /v1/rfq/combo-markets: + get: + tags: + - Combo Markets + summary: Get combo markets + description: > + Returns active markets that can be used as combo legs, ordered by volume + + descending. This endpoint is public and does not require CLOB + + authentication. + + + Entries in `position_ids`, `outcomes`, and `outcome_prices` correspond + by + + array index (`[0]` is YES, `[1]` is NO). Use `next_cursor` unchanged in + + the next request; a value of `null` indicates the final page. + operationId: getComboMarkets + parameters: + - name: limit + in: query + required: false + description: Number of markets to return. Defaults to `50`; maximum `100`. + schema: + type: integer + minimum: 1 + maximum: 100 + default: 50 + - name: cursor + in: query + required: false + description: Opaque cursor returned as `next_cursor` by the previous response. + schema: + type: string + - name: exclude + in: query + required: false + description: >- + Comma-separated condition IDs to omit, such as markets already + shown. + schema: + type: string + example: 0x4cd7...110ff,0x0391ab0e... + responses: + '200': + description: Catalog page of combo-able markets + content: + application/json: + schema: + $ref: '#/components/schemas/ComboMarketsResponse' + example: + markets: + - id: '1897034' + condition_id: 0x4cd7...110ff + position_ids: + - 1012585...362880 + - 1012585...362881 + slug: fifwc-mex-rsa-2026-06-11-mex + title: Will Mexico win on 2026-06-11? + outcomes: + - 'Yes' + - 'No' + outcome_prices: + - '0.685' + - '0.315' + image: https://... + volume: 330327.7128580074 + tags: + - sports + - soccer + - games + - world-cup + next_cursor: Mg + '400': + $ref: '#/components/responses/BadRequest' + security: [] +components: + schemas: + ComboMarketsResponse: + type: object + properties: + markets: + type: array + items: + $ref: '#/components/schemas/ComboMarket' + next_cursor: + type: + - string + - 'null' + description: Cursor for the next page, or `null` on the final page. + required: + - markets + - next_cursor + ComboMarket: + type: object + properties: + id: + type: string + condition_id: + type: string + position_ids: + type: array + description: Combo position IDs; `[0]` is YES, `[1]` is NO. + items: + type: string + slug: + type: string + title: + type: string + outcomes: + type: array + items: + type: string + outcome_prices: + type: array + items: + type: string + image: + type: string + volume: + type: number + format: double + tags: + type: array + items: + type: string + required: + - id + - condition_id + - position_ids + - slug + - title + - outcomes + - outcome_prices + - image + - volume + - tags + ErrorResponse: + type: object + properties: + error: + type: string + description: Human-readable error detail + required: + - error + responses: + BadRequest: + description: >- + Invalid request (malformed JSON, invalid parameters, or failed + validation) + content: + application/json: + schema: + $ref: '#/components/schemas/ErrorResponse' + example: + error: invalid quote + +```` \ No newline at end of file diff --git a/PolymarketDocumentation-main/docs/api-reference/comments/get-comments-by-comment-id.md b/PolymarketDocumentation-main/docs/api-reference/comments/get-comments-by-comment-id.md new file mode 100644 index 00000000..caf3a135 --- /dev/null +++ b/PolymarketDocumentation-main/docs/api-reference/comments/get-comments-by-comment-id.md @@ -0,0 +1,212 @@ +> ## Documentation Index +> Fetch the complete documentation index at: https://docs.polymarket.com/llms.txt +> Use this file to discover all available pages before exploring further. + +# Get comments by comment id + + + +## OpenAPI + +````yaml /api-spec/gamma-openapi.yaml get /comments/{id} +openapi: 3.0.3 +info: + title: Markets API + version: 1.0.0 + description: REST API specification for public endpoints used by the Markets service. +servers: + - url: https://gamma-api.polymarket.com + description: Polymarket Gamma API Production Server +security: [] +tags: + - name: Gamma Status + description: Gamma API status and health check + - name: Sports + description: Sports-related endpoints including teams and game data + - name: Tags + description: Tag management and related tag operations + - name: Events + description: Event management and event-related operations + - name: Markets + description: Market data and market-related operations + - name: Comments + description: Comment system and user interactions + - name: Series + description: Series management and related operations + - name: Profiles + description: User profile management + - name: Search + description: Search functionality across different entity types +paths: + /comments/{id}: + get: + tags: + - Comments + summary: Get comments by comment id + operationId: getCommentsById + parameters: + - name: id + in: path + required: true + schema: + type: integer + - name: get_positions + in: query + schema: + type: boolean + responses: + '200': + description: Comments + content: + application/json: + schema: + type: array + items: + $ref: '#/components/schemas/Comment' +components: + schemas: + Comment: + type: object + properties: + id: + type: string + body: + type: string + nullable: true + parentEntityType: + type: string + nullable: true + parentEntityID: + type: integer + nullable: true + parentCommentID: + type: string + nullable: true + userAddress: + type: string + nullable: true + replyAddress: + type: string + nullable: true + createdAt: + type: string + format: date-time + nullable: true + updatedAt: + type: string + format: date-time + nullable: true + profile: + $ref: '#/components/schemas/CommentProfile' + reactions: + type: array + items: + $ref: '#/components/schemas/Reaction' + reportCount: + type: integer + nullable: true + reactionCount: + type: integer + nullable: true + CommentProfile: + type: object + properties: + name: + type: string + nullable: true + pseudonym: + type: string + nullable: true + displayUsernamePublic: + type: boolean + nullable: true + bio: + type: string + nullable: true + isMod: + type: boolean + nullable: true + isCreator: + type: boolean + nullable: true + proxyWallet: + type: string + nullable: true + baseAddress: + type: string + nullable: true + profileImage: + type: string + nullable: true + profileImageOptimized: + $ref: '#/components/schemas/ImageOptimization' + positions: + type: array + items: + $ref: '#/components/schemas/CommentPosition' + Reaction: + type: object + properties: + id: + type: string + commentID: + type: integer + nullable: true + reactionType: + type: string + nullable: true + icon: + type: string + nullable: true + userAddress: + type: string + nullable: true + createdAt: + type: string + format: date-time + nullable: true + profile: + $ref: '#/components/schemas/CommentProfile' + ImageOptimization: + type: object + properties: + id: + type: string + imageUrlSource: + type: string + nullable: true + imageUrlOptimized: + type: string + nullable: true + imageSizeKbSource: + type: number + nullable: true + imageSizeKbOptimized: + type: number + nullable: true + imageOptimizedComplete: + type: boolean + nullable: true + imageOptimizedLastUpdated: + type: string + nullable: true + relID: + type: integer + nullable: true + field: + type: string + nullable: true + relname: + type: string + nullable: true + CommentPosition: + type: object + properties: + tokenId: + type: string + nullable: true + positionSize: + type: string + nullable: true + +```` \ No newline at end of file diff --git a/PolymarketDocumentation-main/docs/api-reference/comments/get-comments-by-user-address.md b/PolymarketDocumentation-main/docs/api-reference/comments/get-comments-by-user-address.md new file mode 100644 index 00000000..8524523e --- /dev/null +++ b/PolymarketDocumentation-main/docs/api-reference/comments/get-comments-by-user-address.md @@ -0,0 +1,237 @@ +> ## Documentation Index +> Fetch the complete documentation index at: https://docs.polymarket.com/llms.txt +> Use this file to discover all available pages before exploring further. + +# Get comments by user address + + + +## OpenAPI + +````yaml /api-spec/gamma-openapi.yaml get /comments/user_address/{user_address} +openapi: 3.0.3 +info: + title: Markets API + version: 1.0.0 + description: REST API specification for public endpoints used by the Markets service. +servers: + - url: https://gamma-api.polymarket.com + description: Polymarket Gamma API Production Server +security: [] +tags: + - name: Gamma Status + description: Gamma API status and health check + - name: Sports + description: Sports-related endpoints including teams and game data + - name: Tags + description: Tag management and related tag operations + - name: Events + description: Event management and event-related operations + - name: Markets + description: Market data and market-related operations + - name: Comments + description: Comment system and user interactions + - name: Series + description: Series management and related operations + - name: Profiles + description: User profile management + - name: Search + description: Search functionality across different entity types +paths: + /comments/user_address/{user_address}: + get: + tags: + - Comments + - Profiles + summary: Get comments by user address + operationId: getCommentsByUserAddress + parameters: + - name: user_address + in: path + required: true + schema: + type: string + - $ref: '#/components/parameters/limit' + - $ref: '#/components/parameters/offset' + - $ref: '#/components/parameters/order' + - $ref: '#/components/parameters/ascending' + responses: + '200': + description: Comments + content: + application/json: + schema: + type: array + items: + $ref: '#/components/schemas/Comment' +components: + parameters: + limit: + name: limit + in: query + schema: + type: integer + minimum: 0 + offset: + name: offset + in: query + schema: + type: integer + minimum: 0 + order: + name: order + in: query + schema: + type: string + description: Comma-separated list of fields to order by + ascending: + name: ascending + in: query + schema: + type: boolean + schemas: + Comment: + type: object + properties: + id: + type: string + body: + type: string + nullable: true + parentEntityType: + type: string + nullable: true + parentEntityID: + type: integer + nullable: true + parentCommentID: + type: string + nullable: true + userAddress: + type: string + nullable: true + replyAddress: + type: string + nullable: true + createdAt: + type: string + format: date-time + nullable: true + updatedAt: + type: string + format: date-time + nullable: true + profile: + $ref: '#/components/schemas/CommentProfile' + reactions: + type: array + items: + $ref: '#/components/schemas/Reaction' + reportCount: + type: integer + nullable: true + reactionCount: + type: integer + nullable: true + CommentProfile: + type: object + properties: + name: + type: string + nullable: true + pseudonym: + type: string + nullable: true + displayUsernamePublic: + type: boolean + nullable: true + bio: + type: string + nullable: true + isMod: + type: boolean + nullable: true + isCreator: + type: boolean + nullable: true + proxyWallet: + type: string + nullable: true + baseAddress: + type: string + nullable: true + profileImage: + type: string + nullable: true + profileImageOptimized: + $ref: '#/components/schemas/ImageOptimization' + positions: + type: array + items: + $ref: '#/components/schemas/CommentPosition' + Reaction: + type: object + properties: + id: + type: string + commentID: + type: integer + nullable: true + reactionType: + type: string + nullable: true + icon: + type: string + nullable: true + userAddress: + type: string + nullable: true + createdAt: + type: string + format: date-time + nullable: true + profile: + $ref: '#/components/schemas/CommentProfile' + ImageOptimization: + type: object + properties: + id: + type: string + imageUrlSource: + type: string + nullable: true + imageUrlOptimized: + type: string + nullable: true + imageSizeKbSource: + type: number + nullable: true + imageSizeKbOptimized: + type: number + nullable: true + imageOptimizedComplete: + type: boolean + nullable: true + imageOptimizedLastUpdated: + type: string + nullable: true + relID: + type: integer + nullable: true + field: + type: string + nullable: true + relname: + type: string + nullable: true + CommentPosition: + type: object + properties: + tokenId: + type: string + nullable: true + positionSize: + type: string + nullable: true + +```` \ No newline at end of file diff --git a/PolymarketDocumentation-main/docs/api-reference/comments/list-comments.md b/PolymarketDocumentation-main/docs/api-reference/comments/list-comments.md new file mode 100644 index 00000000..1872c9b5 --- /dev/null +++ b/PolymarketDocumentation-main/docs/api-reference/comments/list-comments.md @@ -0,0 +1,251 @@ +> ## Documentation Index +> Fetch the complete documentation index at: https://docs.polymarket.com/llms.txt +> Use this file to discover all available pages before exploring further. + +# List comments + + + +## OpenAPI + +````yaml /api-spec/gamma-openapi.yaml get /comments +openapi: 3.0.3 +info: + title: Markets API + version: 1.0.0 + description: REST API specification for public endpoints used by the Markets service. +servers: + - url: https://gamma-api.polymarket.com + description: Polymarket Gamma API Production Server +security: [] +tags: + - name: Gamma Status + description: Gamma API status and health check + - name: Sports + description: Sports-related endpoints including teams and game data + - name: Tags + description: Tag management and related tag operations + - name: Events + description: Event management and event-related operations + - name: Markets + description: Market data and market-related operations + - name: Comments + description: Comment system and user interactions + - name: Series + description: Series management and related operations + - name: Profiles + description: User profile management + - name: Search + description: Search functionality across different entity types +paths: + /comments: + get: + tags: + - Comments + summary: List comments + operationId: listComments + parameters: + - $ref: '#/components/parameters/limit' + - $ref: '#/components/parameters/offset' + - $ref: '#/components/parameters/order' + - $ref: '#/components/parameters/ascending' + - name: parent_entity_type + in: query + schema: + type: string + enum: + - Event + - Series + - market + - name: parent_entity_id + in: query + schema: + type: integer + - name: get_positions + in: query + schema: + type: boolean + - name: holders_only + in: query + schema: + type: boolean + responses: + '200': + description: List of comments + content: + application/json: + schema: + type: array + items: + $ref: '#/components/schemas/Comment' +components: + parameters: + limit: + name: limit + in: query + schema: + type: integer + minimum: 0 + offset: + name: offset + in: query + schema: + type: integer + minimum: 0 + order: + name: order + in: query + schema: + type: string + description: Comma-separated list of fields to order by + ascending: + name: ascending + in: query + schema: + type: boolean + schemas: + Comment: + type: object + properties: + id: + type: string + body: + type: string + nullable: true + parentEntityType: + type: string + nullable: true + parentEntityID: + type: integer + nullable: true + parentCommentID: + type: string + nullable: true + userAddress: + type: string + nullable: true + replyAddress: + type: string + nullable: true + createdAt: + type: string + format: date-time + nullable: true + updatedAt: + type: string + format: date-time + nullable: true + profile: + $ref: '#/components/schemas/CommentProfile' + reactions: + type: array + items: + $ref: '#/components/schemas/Reaction' + reportCount: + type: integer + nullable: true + reactionCount: + type: integer + nullable: true + CommentProfile: + type: object + properties: + name: + type: string + nullable: true + pseudonym: + type: string + nullable: true + displayUsernamePublic: + type: boolean + nullable: true + bio: + type: string + nullable: true + isMod: + type: boolean + nullable: true + isCreator: + type: boolean + nullable: true + proxyWallet: + type: string + nullable: true + baseAddress: + type: string + nullable: true + profileImage: + type: string + nullable: true + profileImageOptimized: + $ref: '#/components/schemas/ImageOptimization' + positions: + type: array + items: + $ref: '#/components/schemas/CommentPosition' + Reaction: + type: object + properties: + id: + type: string + commentID: + type: integer + nullable: true + reactionType: + type: string + nullable: true + icon: + type: string + nullable: true + userAddress: + type: string + nullable: true + createdAt: + type: string + format: date-time + nullable: true + profile: + $ref: '#/components/schemas/CommentProfile' + ImageOptimization: + type: object + properties: + id: + type: string + imageUrlSource: + type: string + nullable: true + imageUrlOptimized: + type: string + nullable: true + imageSizeKbSource: + type: number + nullable: true + imageSizeKbOptimized: + type: number + nullable: true + imageOptimizedComplete: + type: boolean + nullable: true + imageOptimizedLastUpdated: + type: string + nullable: true + relID: + type: integer + nullable: true + field: + type: string + nullable: true + relname: + type: string + nullable: true + CommentPosition: + type: object + properties: + tokenId: + type: string + nullable: true + positionSize: + type: string + nullable: true + +```` \ No newline at end of file diff --git a/PolymarketDocumentation-main/docs/api-reference/core/get-closed-positions-for-a-user.md b/PolymarketDocumentation-main/docs/api-reference/core/get-closed-positions-for-a-user.md new file mode 100644 index 00000000..fbb7a6ac --- /dev/null +++ b/PolymarketDocumentation-main/docs/api-reference/core/get-closed-positions-for-a-user.md @@ -0,0 +1,194 @@ +> ## Documentation Index +> Fetch the complete documentation index at: https://docs.polymarket.com/llms.txt +> Use this file to discover all available pages before exploring further. + +# Get closed positions for a user + + + +## OpenAPI + +````yaml /api-spec/data-openapi.yaml get /closed-positions +openapi: 3.0.3 +info: + title: Polymarket Data API + version: 1.0.0 + description: > + HTTP API for Polymarket data. This specification documents all public + routes. +servers: + - url: https://data-api.polymarket.com + description: Relative server (same host) +security: [] +tags: + - name: Data API Status + description: Data API health check + - name: Core + - name: Builders + - name: Misc +paths: + /closed-positions: + get: + tags: + - Core + summary: Get closed positions for a user + parameters: + - in: query + name: user + required: true + schema: + $ref: '#/components/schemas/Address' + description: The address of the user in question + - in: query + name: market + style: form + explode: false + schema: + type: array + items: + $ref: '#/components/schemas/Hash64' + description: >- + The conditionId of the market in question. Supports multiple csv + separated values. Cannot be used with the eventId param. + - in: query + name: title + schema: + type: string + maxLength: 100 + description: Filter by market title + - in: query + name: eventId + style: form + explode: false + schema: + type: array + items: + type: integer + minimum: 1 + description: >- + The event id of the event in question. Supports multiple csv + separated values. Returns positions for all markets for those event + ids. Cannot be used with the market param. + - in: query + name: limit + schema: + type: integer + default: 10 + minimum: 0 + maximum: 50 + description: The max number of positions to return + - in: query + name: offset + schema: + type: integer + default: 0 + minimum: 0 + maximum: 100000 + description: The starting index for pagination + - in: query + name: sortBy + schema: + type: string + enum: + - REALIZEDPNL + - TITLE + - PRICE + - AVGPRICE + - TIMESTAMP + default: REALIZEDPNL + description: The sort criteria + - in: query + name: sortDirection + schema: + type: string + enum: + - ASC + - DESC + default: DESC + description: The sort direction + responses: + '200': + description: Success + content: + application/json: + schema: + type: array + items: + $ref: '#/components/schemas/ClosedPosition' + '400': + description: Bad Request + content: + application/json: + schema: + $ref: '#/components/schemas/ErrorResponse' + '401': + description: Unauthorized + content: + application/json: + schema: + $ref: '#/components/schemas/ErrorResponse' + '500': + description: Server Error + content: + application/json: + schema: + $ref: '#/components/schemas/ErrorResponse' +components: + schemas: + Address: + type: string + description: User Profile Address (0x-prefixed, 40 hex chars) + pattern: ^0x[a-fA-F0-9]{40}$ + example: '0x56687bf447db6ffa42ffe2204a05edaa20f55839' + Hash64: + type: string + description: 0x-prefixed 64-hex string + pattern: ^0x[a-fA-F0-9]{64}$ + example: '0xdd22472e552920b8438158ea7238bfadfa4f736aa4cee91a6b86c39ead110917' + ClosedPosition: + type: object + properties: + proxyWallet: + $ref: '#/components/schemas/Address' + asset: + type: string + conditionId: + $ref: '#/components/schemas/Hash64' + avgPrice: + type: number + totalBought: + type: number + realizedPnl: + type: number + curPrice: + type: number + timestamp: + type: integer + format: int64 + title: + type: string + slug: + type: string + icon: + type: string + eventSlug: + type: string + outcome: + type: string + outcomeIndex: + type: integer + oppositeOutcome: + type: string + oppositeAsset: + type: string + endDate: + type: string + ErrorResponse: + type: object + properties: + error: + type: string + required: + - error + +```` \ No newline at end of file diff --git a/PolymarketDocumentation-main/docs/api-reference/core/get-current-positions-for-a-user.md b/PolymarketDocumentation-main/docs/api-reference/core/get-current-positions-for-a-user.md new file mode 100644 index 00000000..f53ef8a2 --- /dev/null +++ b/PolymarketDocumentation-main/docs/api-reference/core/get-current-positions-for-a-user.md @@ -0,0 +1,221 @@ +> ## Documentation Index +> Fetch the complete documentation index at: https://docs.polymarket.com/llms.txt +> Use this file to discover all available pages before exploring further. + +# Get current positions for a user + + + +## OpenAPI + +````yaml /api-spec/data-openapi.yaml get /positions +openapi: 3.0.3 +info: + title: Polymarket Data API + version: 1.0.0 + description: > + HTTP API for Polymarket data. This specification documents all public + routes. +servers: + - url: https://data-api.polymarket.com + description: Relative server (same host) +security: [] +tags: + - name: Data API Status + description: Data API health check + - name: Core + - name: Builders + - name: Misc +paths: + /positions: + get: + tags: + - Core + summary: Get current positions for a user + parameters: + - in: query + name: user + required: true + schema: + $ref: '#/components/schemas/Address' + description: User address (required) + - in: query + name: market + style: form + explode: false + schema: + type: array + items: + $ref: '#/components/schemas/Hash64' + description: >- + Comma-separated list of condition IDs. Mutually exclusive with + eventId. + - in: query + name: eventId + style: form + explode: false + schema: + type: array + items: + type: integer + minimum: 1 + description: Comma-separated list of event IDs. Mutually exclusive with market. + - in: query + name: sizeThreshold + schema: + type: number + default: 1 + minimum: 0 + - in: query + name: redeemable + schema: + type: boolean + default: false + - in: query + name: mergeable + schema: + type: boolean + default: false + - in: query + name: limit + schema: + type: integer + default: 100 + minimum: 0 + maximum: 500 + - in: query + name: offset + schema: + type: integer + default: 0 + minimum: 0 + maximum: 10000 + - in: query + name: sortBy + schema: + type: string + enum: + - CURRENT + - INITIAL + - TOKENS + - CASHPNL + - PERCENTPNL + - TITLE + - RESOLVING + - PRICE + - AVGPRICE + default: TOKENS + - in: query + name: sortDirection + schema: + type: string + enum: + - ASC + - DESC + default: DESC + - in: query + name: title + schema: + type: string + maxLength: 100 + responses: + '200': + description: Success + content: + application/json: + schema: + type: array + items: + $ref: '#/components/schemas/Position' + '400': + description: Bad Request + content: + application/json: + schema: + $ref: '#/components/schemas/ErrorResponse' + '401': + description: Unauthorized + content: + application/json: + schema: + $ref: '#/components/schemas/ErrorResponse' + '500': + description: Server Error + content: + application/json: + schema: + $ref: '#/components/schemas/ErrorResponse' +components: + schemas: + Address: + type: string + description: User Profile Address (0x-prefixed, 40 hex chars) + pattern: ^0x[a-fA-F0-9]{40}$ + example: '0x56687bf447db6ffa42ffe2204a05edaa20f55839' + Hash64: + type: string + description: 0x-prefixed 64-hex string + pattern: ^0x[a-fA-F0-9]{64}$ + example: '0xdd22472e552920b8438158ea7238bfadfa4f736aa4cee91a6b86c39ead110917' + Position: + type: object + properties: + proxyWallet: + $ref: '#/components/schemas/Address' + asset: + type: string + conditionId: + $ref: '#/components/schemas/Hash64' + size: + type: number + avgPrice: + type: number + initialValue: + type: number + currentValue: + type: number + cashPnl: + type: number + percentPnl: + type: number + totalBought: + type: number + realizedPnl: + type: number + percentRealizedPnl: + type: number + curPrice: + type: number + redeemable: + type: boolean + mergeable: + type: boolean + title: + type: string + slug: + type: string + icon: + type: string + eventSlug: + type: string + outcome: + type: string + outcomeIndex: + type: integer + oppositeOutcome: + type: string + oppositeAsset: + type: string + endDate: + type: string + negativeRisk: + type: boolean + ErrorResponse: + type: object + properties: + error: + type: string + required: + - error + +```` \ No newline at end of file diff --git a/PolymarketDocumentation-main/docs/api-reference/core/get-positions-for-a-market.md b/PolymarketDocumentation-main/docs/api-reference/core/get-positions-for-a-market.md new file mode 100644 index 00000000..cecef8fc --- /dev/null +++ b/PolymarketDocumentation-main/docs/api-reference/core/get-positions-for-a-market.md @@ -0,0 +1,193 @@ +> ## Documentation Index +> Fetch the complete documentation index at: https://docs.polymarket.com/llms.txt +> Use this file to discover all available pages before exploring further. + +# Get positions for a market + + + +## OpenAPI + +````yaml /api-spec/data-openapi.yaml get /v1/market-positions +openapi: 3.0.3 +info: + title: Polymarket Data API + version: 1.0.0 + description: > + HTTP API for Polymarket data. This specification documents all public + routes. +servers: + - url: https://data-api.polymarket.com + description: Relative server (same host) +security: [] +tags: + - name: Data API Status + description: Data API health check + - name: Core + - name: Builders + - name: Misc +paths: + /v1/market-positions: + get: + tags: + - Core + summary: Get positions for a market + parameters: + - in: query + name: market + required: true + schema: + $ref: '#/components/schemas/Hash64' + description: The condition ID of the market to query positions for + - in: query + name: user + schema: + $ref: '#/components/schemas/Address' + description: Filter to a single user by proxy wallet address + - in: query + name: status + schema: + type: string + enum: + - OPEN + - CLOSED + - ALL + default: ALL + description: | + Filter positions by status. + - `OPEN` — Only positions with size > 0.01 + - `CLOSED` — Only positions with size <= 0.01 + - `ALL` — All positions regardless of size + - in: query + name: sortBy + schema: + type: string + enum: + - TOKENS + - CASH_PNL + - REALIZED_PNL + - TOTAL_PNL + default: TOTAL_PNL + description: | + Sort positions by: + - `TOKENS` — Position size (number of tokens) + - `CASH_PNL` — Unrealized cash PnL + - `REALIZED_PNL` — Realized PnL + - `TOTAL_PNL` — Total PnL (cash_pnl + realized_pnl) + - in: query + name: sortDirection + schema: + type: string + enum: + - ASC + - DESC + default: DESC + - in: query + name: limit + schema: + type: integer + default: 50 + minimum: 0 + maximum: 500 + description: Max number of positions to return per outcome token + - in: query + name: offset + schema: + type: integer + default: 0 + minimum: 0 + maximum: 10000 + description: Pagination offset per outcome token + responses: + '200': + description: Success + content: + application/json: + schema: + type: array + items: + $ref: '#/components/schemas/MetaMarketPositionV1' + '400': + description: Bad Request + content: + application/json: + schema: + $ref: '#/components/schemas/ErrorResponse' + '401': + description: Unauthorized + content: + application/json: + schema: + $ref: '#/components/schemas/ErrorResponse' + '500': + description: Server Error + content: + application/json: + schema: + $ref: '#/components/schemas/ErrorResponse' +components: + schemas: + Hash64: + type: string + description: 0x-prefixed 64-hex string + pattern: ^0x[a-fA-F0-9]{64}$ + example: '0xdd22472e552920b8438158ea7238bfadfa4f736aa4cee91a6b86c39ead110917' + Address: + type: string + description: User Profile Address (0x-prefixed, 40 hex chars) + pattern: ^0x[a-fA-F0-9]{40}$ + example: '0x56687bf447db6ffa42ffe2204a05edaa20f55839' + MetaMarketPositionV1: + type: object + properties: + token: + type: string + description: The outcome token asset ID + positions: + type: array + items: + $ref: '#/components/schemas/MarketPositionV1' + ErrorResponse: + type: object + properties: + error: + type: string + required: + - error + MarketPositionV1: + type: object + properties: + proxyWallet: + $ref: '#/components/schemas/Address' + name: + type: string + profileImage: + type: string + verified: + type: boolean + asset: + type: string + conditionId: + $ref: '#/components/schemas/Hash64' + avgPrice: + type: number + size: + type: number + currPrice: + type: number + currentValue: + type: number + cashPnl: + type: number + totalBought: + type: number + realizedPnl: + type: number + totalPnl: + type: number + outcome: + type: string + outcomeIndex: + type: integer + +```` \ No newline at end of file diff --git a/PolymarketDocumentation-main/docs/api-reference/core/get-top-holders-for-markets.md b/PolymarketDocumentation-main/docs/api-reference/core/get-top-holders-for-markets.md new file mode 100644 index 00000000..3b3eea79 --- /dev/null +++ b/PolymarketDocumentation-main/docs/api-reference/core/get-top-holders-for-markets.md @@ -0,0 +1,140 @@ +> ## Documentation Index +> Fetch the complete documentation index at: https://docs.polymarket.com/llms.txt +> Use this file to discover all available pages before exploring further. + +# Get top holders for markets + + + +## OpenAPI + +````yaml /api-spec/data-openapi.yaml get /holders +openapi: 3.0.3 +info: + title: Polymarket Data API + version: 1.0.0 + description: > + HTTP API for Polymarket data. This specification documents all public + routes. +servers: + - url: https://data-api.polymarket.com + description: Relative server (same host) +security: [] +tags: + - name: Data API Status + description: Data API health check + - name: Core + - name: Builders + - name: Misc +paths: + /holders: + get: + tags: + - Core + summary: Get top holders for markets + parameters: + - in: query + name: limit + schema: + type: integer + default: 20 + minimum: 0 + maximum: 20 + description: Maximum number of holders to return per token. Capped at 20. + - in: query + name: market + required: true + style: form + explode: false + schema: + type: array + items: + $ref: '#/components/schemas/Hash64' + description: Comma-separated list of condition IDs. + - in: query + name: minBalance + schema: + type: integer + default: 1 + minimum: 0 + maximum: 999999 + responses: + '200': + description: Success + content: + application/json: + schema: + type: array + items: + $ref: '#/components/schemas/MetaHolder' + '400': + description: Bad Request + content: + application/json: + schema: + $ref: '#/components/schemas/ErrorResponse' + '401': + description: Unauthorized + content: + application/json: + schema: + $ref: '#/components/schemas/ErrorResponse' + '500': + description: Server Error + content: + application/json: + schema: + $ref: '#/components/schemas/ErrorResponse' +components: + schemas: + Hash64: + type: string + description: 0x-prefixed 64-hex string + pattern: ^0x[a-fA-F0-9]{64}$ + example: '0xdd22472e552920b8438158ea7238bfadfa4f736aa4cee91a6b86c39ead110917' + MetaHolder: + type: object + properties: + token: + type: string + holders: + type: array + items: + $ref: '#/components/schemas/Holder' + ErrorResponse: + type: object + properties: + error: + type: string + required: + - error + Holder: + type: object + properties: + proxyWallet: + $ref: '#/components/schemas/Address' + bio: + type: string + asset: + type: string + pseudonym: + type: string + amount: + type: number + displayUsernamePublic: + type: boolean + outcomeIndex: + type: integer + name: + type: string + profileImage: + type: string + profileImageOptimized: + type: string + Address: + type: string + description: User Profile Address (0x-prefixed, 40 hex chars) + pattern: ^0x[a-fA-F0-9]{40}$ + example: '0x56687bf447db6ffa42ffe2204a05edaa20f55839' + +```` \ No newline at end of file diff --git a/PolymarketDocumentation-main/docs/api-reference/core/get-total-value-of-a-users-positions.md b/PolymarketDocumentation-main/docs/api-reference/core/get-total-value-of-a-users-positions.md new file mode 100644 index 00000000..61227ec5 --- /dev/null +++ b/PolymarketDocumentation-main/docs/api-reference/core/get-total-value-of-a-users-positions.md @@ -0,0 +1,97 @@ +> ## Documentation Index +> Fetch the complete documentation index at: https://docs.polymarket.com/llms.txt +> Use this file to discover all available pages before exploring further. + +# Get total value of a user's positions + + + +## OpenAPI + +````yaml /api-spec/data-openapi.yaml get /value +openapi: 3.0.3 +info: + title: Polymarket Data API + version: 1.0.0 + description: > + HTTP API for Polymarket data. This specification documents all public + routes. +servers: + - url: https://data-api.polymarket.com + description: Relative server (same host) +security: [] +tags: + - name: Data API Status + description: Data API health check + - name: Core + - name: Builders + - name: Misc +paths: + /value: + get: + tags: + - Core + summary: Get total value of a user's positions + parameters: + - in: query + name: user + required: true + schema: + $ref: '#/components/schemas/Address' + - in: query + name: market + style: form + explode: false + schema: + type: array + items: + $ref: '#/components/schemas/Hash64' + responses: + '200': + description: Success + content: + application/json: + schema: + type: array + items: + $ref: '#/components/schemas/Value' + '400': + description: Bad Request + content: + application/json: + schema: + $ref: '#/components/schemas/ErrorResponse' + '500': + description: Server Error + content: + application/json: + schema: + $ref: '#/components/schemas/ErrorResponse' +components: + schemas: + Address: + type: string + description: User Profile Address (0x-prefixed, 40 hex chars) + pattern: ^0x[a-fA-F0-9]{40}$ + example: '0x56687bf447db6ffa42ffe2204a05edaa20f55839' + Hash64: + type: string + description: 0x-prefixed 64-hex string + pattern: ^0x[a-fA-F0-9]{64}$ + example: '0xdd22472e552920b8438158ea7238bfadfa4f736aa4cee91a6b86c39ead110917' + Value: + type: object + properties: + user: + $ref: '#/components/schemas/Address' + value: + type: number + ErrorResponse: + type: object + properties: + error: + type: string + required: + - error + +```` \ No newline at end of file diff --git a/PolymarketDocumentation-main/docs/api-reference/core/get-trader-leaderboard-rankings.md b/PolymarketDocumentation-main/docs/api-reference/core/get-trader-leaderboard-rankings.md new file mode 100644 index 00000000..ab9cc29b --- /dev/null +++ b/PolymarketDocumentation-main/docs/api-reference/core/get-trader-leaderboard-rankings.md @@ -0,0 +1,162 @@ +> ## Documentation Index +> Fetch the complete documentation index at: https://docs.polymarket.com/llms.txt +> Use this file to discover all available pages before exploring further. + +# Get trader leaderboard rankings + + + +## OpenAPI + +````yaml /api-spec/data-openapi.yaml get /v1/leaderboard +openapi: 3.0.3 +info: + title: Polymarket Data API + version: 1.0.0 + description: > + HTTP API for Polymarket data. This specification documents all public + routes. +servers: + - url: https://data-api.polymarket.com + description: Relative server (same host) +security: [] +tags: + - name: Data API Status + description: Data API health check + - name: Core + - name: Builders + - name: Misc +paths: + /v1/leaderboard: + get: + tags: + - Core + summary: Get trader leaderboard rankings + parameters: + - in: query + name: category + schema: + type: string + enum: + - OVERALL + - POLITICS + - SPORTS + - ESPORTS + - CRYPTO + - CULTURE + - MENTIONS + - WEATHER + - ECONOMICS + - TECH + - FINANCE + default: OVERALL + description: Market category for the leaderboard + - in: query + name: timePeriod + schema: + type: string + enum: + - DAY + - WEEK + - MONTH + - ALL + default: DAY + description: Time period for leaderboard results + - in: query + name: orderBy + schema: + type: string + enum: + - PNL + - VOL + default: PNL + description: Leaderboard ordering criteria + - in: query + name: limit + schema: + type: integer + default: 25 + minimum: 1 + maximum: 50 + description: Max number of leaderboard traders to return + - in: query + name: offset + schema: + type: integer + default: 0 + minimum: 0 + maximum: 1000 + description: Starting index for pagination + - in: query + name: user + schema: + $ref: '#/components/schemas/Address' + description: Limit leaderboard to a single user by address + - in: query + name: userName + schema: + type: string + description: Limit leaderboard to a single username + responses: + '200': + description: Success + content: + application/json: + schema: + type: array + items: + $ref: '#/components/schemas/TraderLeaderboardEntry' + '400': + description: Bad Request + content: + application/json: + schema: + $ref: '#/components/schemas/ErrorResponse' + '500': + description: Server Error + content: + application/json: + schema: + $ref: '#/components/schemas/ErrorResponse' +components: + schemas: + Address: + type: string + description: User Profile Address (0x-prefixed, 40 hex chars) + pattern: ^0x[a-fA-F0-9]{40}$ + example: '0x56687bf447db6ffa42ffe2204a05edaa20f55839' + TraderLeaderboardEntry: + type: object + properties: + rank: + type: string + description: The rank position of the trader + proxyWallet: + $ref: '#/components/schemas/Address' + userName: + type: string + description: The trader's username + vol: + type: number + description: Trading volume for this trader + pnl: + type: number + description: Profit and loss for this trader + profileImage: + type: string + description: URL to the trader's profile image + xUsername: + type: string + description: The trader's X (Twitter) username + verifiedBadge: + type: boolean + description: Whether the trader has a verified badge + ErrorResponse: + type: object + properties: + error: + type: string + required: + - error + +```` \ No newline at end of file diff --git a/PolymarketDocumentation-main/docs/api-reference/core/get-trades-for-a-user-or-markets.md b/PolymarketDocumentation-main/docs/api-reference/core/get-trades-for-a-user-or-markets.md new file mode 100644 index 00000000..b22ff2a0 --- /dev/null +++ b/PolymarketDocumentation-main/docs/api-reference/core/get-trades-for-a-user-or-markets.md @@ -0,0 +1,210 @@ +> ## Documentation Index +> Fetch the complete documentation index at: https://docs.polymarket.com/llms.txt +> Use this file to discover all available pages before exploring further. + +# Get trades for a user or markets + + + +## OpenAPI + +````yaml /api-spec/data-openapi.yaml get /trades +openapi: 3.0.3 +info: + title: Polymarket Data API + version: 1.0.0 + description: > + HTTP API for Polymarket data. This specification documents all public + routes. +servers: + - url: https://data-api.polymarket.com + description: Relative server (same host) +security: [] +tags: + - name: Data API Status + description: Data API health check + - name: Core + - name: Builders + - name: Misc +paths: + /trades: + get: + tags: + - Core + summary: Get trades for a user or markets + parameters: + - in: query + name: limit + schema: + type: integer + default: 100 + minimum: 0 + maximum: 10000 + - in: query + name: offset + schema: + type: integer + default: 0 + minimum: 0 + maximum: 10000 + - in: query + name: takerOnly + schema: + type: boolean + default: true + - in: query + name: filterType + schema: + type: string + enum: + - CASH + - TOKENS + description: Must be provided together with filterAmount. + - in: query + name: filterAmount + schema: + type: number + minimum: 0 + description: Must be provided together with filterType. + - in: query + name: market + style: form + explode: false + schema: + type: array + items: + $ref: '#/components/schemas/Hash64' + description: >- + Comma-separated list of condition IDs. Mutually exclusive with + eventId. + - in: query + name: eventId + style: form + explode: false + schema: + type: array + items: + type: integer + minimum: 1 + description: Comma-separated list of event IDs. Mutually exclusive with market. + - in: query + name: user + schema: + $ref: '#/components/schemas/Address' + - in: query + name: side + schema: + type: string + enum: + - BUY + - SELL + - in: query + name: start + schema: + type: integer + minimum: 0 + description: >- + Lower-bound timestamp (epoch seconds) for the trade window. Omit or + pass `0` for the default window (most recent ~3 years); pass a + positive epoch (e.g. `1`) to retrieve full history. + - in: query + name: end + schema: + type: integer + minimum: 0 + description: >- + Upper-bound timestamp (epoch seconds) for the trade window. Omit for + the default (current time); rows newer than `end` are excluded. + responses: + '200': + description: Success + content: + application/json: + schema: + type: array + items: + $ref: '#/components/schemas/Trade' + '400': + description: Bad Request + content: + application/json: + schema: + $ref: '#/components/schemas/ErrorResponse' + '401': + description: Unauthorized + content: + application/json: + schema: + $ref: '#/components/schemas/ErrorResponse' + '500': + description: Server Error + content: + application/json: + schema: + $ref: '#/components/schemas/ErrorResponse' +components: + schemas: + Hash64: + type: string + description: 0x-prefixed 64-hex string + pattern: ^0x[a-fA-F0-9]{64}$ + example: '0xdd22472e552920b8438158ea7238bfadfa4f736aa4cee91a6b86c39ead110917' + Address: + type: string + description: User Profile Address (0x-prefixed, 40 hex chars) + pattern: ^0x[a-fA-F0-9]{40}$ + example: '0x56687bf447db6ffa42ffe2204a05edaa20f55839' + Trade: + type: object + properties: + proxyWallet: + $ref: '#/components/schemas/Address' + side: + type: string + enum: + - BUY + - SELL + asset: + type: string + conditionId: + $ref: '#/components/schemas/Hash64' + size: + type: number + price: + type: number + timestamp: + type: integer + format: int64 + title: + type: string + slug: + type: string + icon: + type: string + eventSlug: + type: string + outcome: + type: string + outcomeIndex: + type: integer + name: + type: string + pseudonym: + type: string + bio: + type: string + profileImage: + type: string + profileImageOptimized: + type: string + transactionHash: + type: string + ErrorResponse: + type: object + properties: + error: + type: string + required: + - error + +```` \ No newline at end of file diff --git a/PolymarketDocumentation-main/docs/api-reference/core/get-user-activity.md b/PolymarketDocumentation-main/docs/api-reference/core/get-user-activity.md new file mode 100644 index 00000000..4001432d --- /dev/null +++ b/PolymarketDocumentation-main/docs/api-reference/core/get-user-activity.md @@ -0,0 +1,255 @@ +> ## Documentation Index +> Fetch the complete documentation index at: https://docs.polymarket.com/llms.txt +> Use this file to discover all available pages before exploring further. + +# Get user activity + + + +## OpenAPI + +````yaml /api-spec/data-openapi.yaml get /activity +openapi: 3.0.3 +info: + title: Polymarket Data API + version: 1.0.0 + description: > + HTTP API for Polymarket data. This specification documents all public + routes. +servers: + - url: https://data-api.polymarket.com + description: Relative server (same host) +security: [] +tags: + - name: Data API Status + description: Data API health check + - name: Core + - name: Builders + - name: Misc +paths: + /activity: + get: + tags: + - Core + summary: Get user activity + parameters: + - in: query + name: limit + schema: + type: integer + default: 100 + minimum: 0 + maximum: 500 + - in: query + name: offset + schema: + type: integer + default: 0 + minimum: 0 + maximum: 10000 + - in: query + name: user + required: true + schema: + $ref: '#/components/schemas/Address' + - in: query + name: market + style: form + explode: false + schema: + type: array + items: + $ref: '#/components/schemas/Hash64' + description: >- + Comma-separated list of condition IDs. Mutually exclusive with + eventId. + - in: query + name: eventId + style: form + explode: false + schema: + type: array + items: + type: integer + minimum: 1 + description: Comma-separated list of event IDs. Mutually exclusive with market. + - in: query + name: type + style: form + explode: false + schema: + type: array + items: + type: string + enum: + - TRADE + - SPLIT + - MERGE + - REDEEM + - REWARD + - CONVERSION + - DEPOSIT + - WITHDRAWAL + - YIELD + - MAKER_REBATE + - TAKER_REBATE + - REFERRAL_REWARD + - in: query + name: start + schema: + type: integer + minimum: 0 + description: >- + Lower-bound timestamp (epoch seconds) for the activity window. Omit + or pass `0` for the default window (most recent ~3 years); pass a + positive epoch (e.g. `1`) to retrieve full history. + - in: query + name: end + schema: + type: integer + minimum: 0 + description: >- + Upper-bound timestamp (epoch seconds) for the activity window. Omit + for the default (current time); rows newer than `end` are excluded. + - in: query + name: sortBy + schema: + type: string + enum: + - TIMESTAMP + - TOKENS + - CASH + default: TIMESTAMP + - in: query + name: sortDirection + schema: + type: string + enum: + - ASC + - DESC + default: DESC + - in: query + name: side + schema: + type: string + enum: + - BUY + - SELL + responses: + '200': + description: Success + content: + application/json: + schema: + type: array + items: + $ref: '#/components/schemas/Activity' + '400': + description: Bad Request + content: + application/json: + schema: + $ref: '#/components/schemas/ErrorResponse' + '401': + description: Unauthorized + content: + application/json: + schema: + $ref: '#/components/schemas/ErrorResponse' + '500': + description: Server Error + content: + application/json: + schema: + $ref: '#/components/schemas/ErrorResponse' +components: + schemas: + Address: + type: string + description: User Profile Address (0x-prefixed, 40 hex chars) + pattern: ^0x[a-fA-F0-9]{40}$ + example: '0x56687bf447db6ffa42ffe2204a05edaa20f55839' + Hash64: + type: string + description: 0x-prefixed 64-hex string + pattern: ^0x[a-fA-F0-9]{64}$ + example: '0xdd22472e552920b8438158ea7238bfadfa4f736aa4cee91a6b86c39ead110917' + Activity: + type: object + properties: + proxyWallet: + $ref: '#/components/schemas/Address' + timestamp: + type: integer + format: int64 + conditionId: + $ref: '#/components/schemas/Hash64' + type: + type: string + enum: + - TRADE + - SPLIT + - MERGE + - REDEEM + - REWARD + - CONVERSION + - DEPOSIT + - WITHDRAWAL + - YIELD + - MAKER_REBATE + - TAKER_REBATE + - REFERRAL_REWARD + size: + type: number + usdcSize: + type: number + transactionHash: + type: string + price: + type: number + asset: + type: string + side: + type: string + enum: + - BUY + - SELL + outcomeIndex: + type: integer + title: + type: string + slug: + type: string + icon: + type: string + eventSlug: + type: string + outcome: + type: string + name: + type: string + pseudonym: + type: string + bio: + type: string + profileImage: + type: string + profileImageOptimized: + type: string + isCombo: + type: boolean + description: >- + True when this row is part of a combinatorial (multi-market) + position. Flag only — combo detail is not embedded here. The row's + conditionId equals the combo's combo_condition_id; pass it to + /v1/activity/combos or /v1/positions/combos via market_id to fetch + legs and detail. Omitted on non-combo rows. + ErrorResponse: + type: object + properties: + error: + type: string + required: + - error + +```` \ No newline at end of file diff --git a/PolymarketDocumentation-main/docs/api-reference/core/get-user-combo-activity.md b/PolymarketDocumentation-main/docs/api-reference/core/get-user-combo-activity.md new file mode 100644 index 00000000..5fdc1155 --- /dev/null +++ b/PolymarketDocumentation-main/docs/api-reference/core/get-user-combo-activity.md @@ -0,0 +1,280 @@ +> ## Documentation Index +> Fetch the complete documentation index at: https://docs.polymarket.com/llms.txt +> Use this file to discover all available pages before exploring further. + +# Get user combo activity + +> Combo lifecycle and redeem events (split / merge / convert / compress / wrap / unwrap / redeem) for a user, with per-leg breakdown. The combo counterpart to /activity trade rows. Also available at /v1/data/user/{address}/activity/combos (address from the path). + + + +## OpenAPI + +````yaml /api-spec/data-openapi.yaml get /v1/activity/combos +openapi: 3.0.3 +info: + title: Polymarket Data API + version: 1.0.0 + description: > + HTTP API for Polymarket data. This specification documents all public + routes. +servers: + - url: https://data-api.polymarket.com + description: Relative server (same host) +security: [] +tags: + - name: Data API Status + description: Data API health check + - name: Core + - name: Builders + - name: Misc +paths: + /v1/activity/combos: + get: + tags: + - Core + summary: Get user combo activity + description: >- + Combo lifecycle and redeem events (split / merge / convert / compress / + wrap / unwrap / redeem) for a user, with per-leg breakdown. The combo + counterpart to /activity trade rows. Also available at + /v1/data/user/{address}/activity/combos (address from the path). + parameters: + - in: query + name: user + required: true + schema: + $ref: '#/components/schemas/Address' + - in: query + name: market_id + style: form + explode: false + schema: + type: array + items: + $ref: '#/components/schemas/ComboConditionId' + description: >- + Comma-separated combo_condition_id values to filter to specific + combos. These equal the market_id of isCombo rows on /activity. Omit + for all of the user's combo activity. + - in: query + name: limit + schema: + type: integer + default: 50 + minimum: 0 + maximum: 500 + - in: query + name: offset + schema: + type: integer + default: 0 + minimum: 0 + maximum: 10000 + - in: query + name: cursor + schema: + type: string + description: >- + Opaque continuation token from a previous response's + pagination.next_cursor. When present it supersedes offset (which is + ignored). Invalid, tampered, or cross-endpoint tokens return 400. + responses: + '200': + description: Success + content: + application/json: + schema: + $ref: '#/components/schemas/CombosActivityResponse' + '400': + description: Bad Request + content: + application/json: + schema: + $ref: '#/components/schemas/ErrorResponse' + '401': + description: Unauthorized + content: + application/json: + schema: + $ref: '#/components/schemas/ErrorResponse' + '500': + description: Server Error + content: + application/json: + schema: + $ref: '#/components/schemas/ErrorResponse' +components: + schemas: + Address: + type: string + description: User Profile Address (0x-prefixed, 40 hex chars) + pattern: ^0x[a-fA-F0-9]{40}$ + example: '0x56687bf447db6ffa42ffe2204a05edaa20f55839' + ComboConditionId: + type: string + description: >- + Combo condition ID (0x-prefixed, 62 hex chars / bytes31). Equals the + market_id (unified) / conditionId (legacy) of isCombo rows on /activity. + pattern: ^0x[a-fA-F0-9]{62}$ + example: '0x0391ab0ebea17b65ba87e071b0566e816b0000000000000000000000000000' + CombosActivityResponse: + type: object + properties: + activity: + type: array + items: + $ref: '#/components/schemas/ComboActivity' + pagination: + $ref: '#/components/schemas/Pagination' + ErrorResponse: + type: object + properties: + error: + type: string + required: + - error + ComboActivity: + type: object + properties: + id: + type: string + event_kind: + type: string + description: >- + Raw on-chain event, e.g. PositionsSplit, PositionsMerged, + PositionRedeemed. + side: + type: string + description: Normalized label for rendering. + enum: + - Split + - Merge + - Convert + - Compress + - Wrap + - Unwrap + - Redeem + module_kind: + type: string + description: Always Combinatorial. + user_address: + $ref: '#/components/schemas/Address' + combo_condition_id: + $ref: '#/components/schemas/ComboConditionId' + combo_position_id: + type: string + module_id: + type: integer + amount_usdc: + type: number + nullable: true + description: Lifecycle amount; null on redeems. + payout_usdc: + type: number + nullable: true + description: Redeem payout; null on lifecycle events. + timestamp: + type: integer + format: int64 + tx_dttm: + type: string + description: RFC3339 UTC + tx_hash: + type: string + log_index: + type: integer + block_number: + type: integer + format: int64 + legs: + type: array + items: + $ref: '#/components/schemas/ComboLeg' + Pagination: + type: object + description: >- + Standard pagination metadata. No total count; has_more is derived from + page fullness. next_cursor is opaque. + properties: + limit: + type: integer + offset: + type: integer + has_more: + type: boolean + next_cursor: + type: string + nullable: true + description: >- + Opaque signed cursor for the next page; null when has_more is false. + Pass it back verbatim as ?cursor= on the next request (keep the same + sort where the endpoint has one). Never parse or construct it. On + cursor-enabled endpoints this makes deep pagination O(page) and + stable against concurrent inserts. + ComboLeg: + type: object + properties: + leg_index: + type: integer + leg_position_id: + type: string + leg_condition_id: + type: string + description: The leg market's condition ID (distinct from the combo's). + leg_outcome_index: + type: integer + leg_outcome_label: + type: string + leg_status: + type: string + description: Placeholder (OPEN) until leg-resolution integration ships. + leg_resolved_at: + type: string + nullable: true + leg_current_price: + type: string + description: Placeholder ("0") until live-price integration ships. + market: + $ref: '#/components/schemas/ComboMarket' + ComboMarket: + type: object + properties: + market_id: + type: string + slug: + type: string + title: + type: string + outcome: + type: string + image_url: + type: string + icon_url: + type: string + category: + type: string + subcategory: + type: string + tags: + type: array + items: + type: string + end_date: + type: string + description: RFC3339 UTC + event: + $ref: '#/components/schemas/ComboEvent' + ComboEvent: + type: object + properties: + event_id: + type: string + event_slug: + type: string + event_title: + type: string + event_image: + type: string + +```` \ No newline at end of file diff --git a/PolymarketDocumentation-main/docs/api-reference/core/get-user-combo-positions.md b/PolymarketDocumentation-main/docs/api-reference/core/get-user-combo-positions.md new file mode 100644 index 00000000..9e406007 --- /dev/null +++ b/PolymarketDocumentation-main/docs/api-reference/core/get-user-combo-positions.md @@ -0,0 +1,329 @@ +> ## Documentation Index +> Fetch the complete documentation index at: https://docs.polymarket.com/llms.txt +> Use this file to discover all available pages before exploring further. + +# Get user combo positions + +> Combinatorial (multi-market) positions held by a user, with per-leg breakdown. Also available at /v1/data/user/{address}/positions/combos (address from the path). + + + +## OpenAPI + +````yaml /api-spec/data-openapi.yaml get /v1/positions/combos +openapi: 3.0.3 +info: + title: Polymarket Data API + version: 1.0.0 + description: > + HTTP API for Polymarket data. This specification documents all public + routes. +servers: + - url: https://data-api.polymarket.com + description: Relative server (same host) +security: [] +tags: + - name: Data API Status + description: Data API health check + - name: Core + - name: Builders + - name: Misc +paths: + /v1/positions/combos: + get: + tags: + - Core + summary: Get user combo positions + description: >- + Combinatorial (multi-market) positions held by a user, with per-leg + breakdown. Also available at /v1/data/user/{address}/positions/combos + (address from the path). + parameters: + - in: query + name: user + required: true + schema: + $ref: '#/components/schemas/Address' + - in: query + name: status + schema: + type: string + enum: + - OPEN + - PARTIAL + - RESOLVED_WIN + - RESOLVED_LOSS + - in: query + name: sort + schema: + type: string + enum: + - current_value_desc + - first_entry_desc + - entry_cost_desc + - resolved_at_desc + - updated_asc + default: current_value_desc + - in: query + name: market_id + style: form + explode: false + schema: + type: array + items: + $ref: '#/components/schemas/ComboConditionId' + description: >- + Comma-separated combo_condition_id values to filter to specific + combos. These equal the market_id of isCombo rows on /activity. Omit + for all of the user's combos. + - in: query + name: limit + schema: + type: integer + default: 20 + minimum: 0 + maximum: 1000 + - in: query + name: offset + schema: + type: integer + default: 0 + minimum: 0 + maximum: 100000 + - in: query + name: updatedAfter + schema: + type: integer + description: >- + Incremental-sync watermark (epoch seconds, inclusive): only rows + whose updated_at is at or after this time. Positions mutate on + resolution and redemption, so this catches changes a creation-time + filter cannot. In sync mode + (updatedAfter/updatedBefore/sort=updated_asc) every live row is + returned regardless of balance, and the effective upper bound is + clamped ~90s behind now (commit-visibility safety lag) — very recent + rows appear on the next poll. Rows at the boundary may re-deliver: + upsert by (combo_condition_id, combo_position_id). + - in: query + name: updatedBefore + schema: + type: integer + description: >- + Optional upper bound (epoch seconds, inclusive) for updated_at; + clamped to the safety lag. Must be >= updatedAfter. + - in: query + name: cursor + schema: + type: string + description: >- + Opaque continuation token from a previous response's + pagination.next_cursor. When present it supersedes offset (which is + ignored). Invalid, tampered, or cross-endpoint tokens return 400. + responses: + '200': + description: Success + content: + application/json: + schema: + $ref: '#/components/schemas/CombosResponse' + '400': + description: Bad Request + content: + application/json: + schema: + $ref: '#/components/schemas/ErrorResponse' + '401': + description: Unauthorized + content: + application/json: + schema: + $ref: '#/components/schemas/ErrorResponse' + '500': + description: Server Error + content: + application/json: + schema: + $ref: '#/components/schemas/ErrorResponse' +components: + schemas: + Address: + type: string + description: User Profile Address (0x-prefixed, 40 hex chars) + pattern: ^0x[a-fA-F0-9]{40}$ + example: '0x56687bf447db6ffa42ffe2204a05edaa20f55839' + ComboConditionId: + type: string + description: >- + Combo condition ID (0x-prefixed, 62 hex chars / bytes31). Equals the + market_id (unified) / conditionId (legacy) of isCombo rows on /activity. + pattern: ^0x[a-fA-F0-9]{62}$ + example: '0x0391ab0ebea17b65ba87e071b0566e816b0000000000000000000000000000' + CombosResponse: + type: object + properties: + combos: + type: array + items: + $ref: '#/components/schemas/ComboPosition' + pagination: + $ref: '#/components/schemas/Pagination' + ErrorResponse: + type: object + properties: + error: + type: string + required: + - error + ComboPosition: + type: object + properties: + combo_condition_id: + $ref: '#/components/schemas/ComboConditionId' + combo_position_id: + type: string + module_id: + type: integer + description: 3 = Combinatorial + user_address: + $ref: '#/components/schemas/Address' + shares_balance: + type: string + description: Decimal string (precision-preserving). + entry_avg_price_usdc: + type: string + entry_cost_usdc: + type: string + description: >- + REMAINING cost basis (entry_avg_price × shares_balance). Reads ~0 + after a winning combo is redeemed — use total_cost_usdc to display + what was paid on closed positions. + realized_payout_usdc: + type: string + description: >- + Gross redemption proceeds (winning combo shares redeem 1:1 at $1). + "0.00" while OPEN / unredeemed / RESOLVED_LOSS; accumulates under + PARTIAL. Gross payout, not net PnL — net = realized_payout_usdc − + total_cost_usdc. + total_cost_usdc: + type: string + description: >- + Original cost basis = entry_avg_price × (shares_balance + + realized_payout). Survives redemption burning the shares; equals + entry_cost_usdc while OPEN. + status: + type: string + enum: + - OPEN + - PARTIAL + - RESOLVED_WIN + - RESOLVED_LOSS + first_entry_at: + type: string + description: RFC3339 UTC + resolved_at: + type: string + nullable: true + updated_at: + type: string + description: >- + Last-modified time (UTC, ISO 8601). Bumps on any recompute of the + row (trade, redemption, resolution classification) — the + incremental-sync watermark field. Omitted on responses served by the + legacy backend. + legs_total: + type: integer + legs_resolved: + type: integer + legs_pending: + type: integer + legs: + type: array + items: + $ref: '#/components/schemas/ComboLeg' + Pagination: + type: object + description: >- + Standard pagination metadata. No total count; has_more is derived from + page fullness. next_cursor is opaque. + properties: + limit: + type: integer + offset: + type: integer + has_more: + type: boolean + next_cursor: + type: string + nullable: true + description: >- + Opaque signed cursor for the next page; null when has_more is false. + Pass it back verbatim as ?cursor= on the next request (keep the same + sort where the endpoint has one). Never parse or construct it. On + cursor-enabled endpoints this makes deep pagination O(page) and + stable against concurrent inserts. + ComboLeg: + type: object + properties: + leg_index: + type: integer + leg_position_id: + type: string + leg_condition_id: + type: string + description: The leg market's condition ID (distinct from the combo's). + leg_outcome_index: + type: integer + leg_outcome_label: + type: string + leg_status: + type: string + description: Placeholder (OPEN) until leg-resolution integration ships. + leg_resolved_at: + type: string + nullable: true + leg_current_price: + type: string + description: Placeholder ("0") until live-price integration ships. + market: + $ref: '#/components/schemas/ComboMarket' + ComboMarket: + type: object + properties: + market_id: + type: string + slug: + type: string + title: + type: string + outcome: + type: string + image_url: + type: string + icon_url: + type: string + category: + type: string + subcategory: + type: string + tags: + type: array + items: + type: string + end_date: + type: string + description: RFC3339 UTC + event: + $ref: '#/components/schemas/ComboEvent' + ComboEvent: + type: object + properties: + event_id: + type: string + event_slug: + type: string + event_title: + type: string + event_image: + type: string + +```` \ No newline at end of file diff --git a/PolymarketDocumentation-main/docs/api-reference/create-account-invite.md b/PolymarketDocumentation-main/docs/api-reference/create-account-invite.md new file mode 100644 index 00000000..49ed06aa --- /dev/null +++ b/PolymarketDocumentation-main/docs/api-reference/create-account-invite.md @@ -0,0 +1,236 @@ +> ## Documentation Index +> Fetch the complete documentation index at: https://docs.polymarket.com/llms.txt +> Use this file to discover all available pages before exploring further. + +# Create Account Invite + +> Create or return the authenticated account's primary invite code. The call +is idempotent for accounts that already have a primary invite code. + + +Request Weight: **1** + + +## OpenAPI + +````yaml /api-spec/perps-openapi.json post /v1/account/invite +openapi: 3.0.3 +info: + title: Polymarket Perps HTTP API + version: 1.0.0 + description: HTTP API for Polymarket perpetual trading system. + license: + name: Apache 2.0 + url: https://www.apache.org/licenses/LICENSE-2.0.html +servers: + - url: https://api.perpetuals.polymarket.com + description: Production Perps HTTP API +security: [] +paths: + /v1/account/invite: + post: + summary: Create Account Invite + description: > + Create or return the authenticated account's primary invite code. The + call + + is idempotent for accounts that already have a primary invite code. + operationId: createAccountInvite + requestBody: + description: Empty invite creation request. + content: + application/json: + schema: + $ref: '#/components/schemas/CreateInviteRequest' + examples: + createAccountInvite: + summary: Create or get the authenticated account invite code + value: {} + responses: + '200': + description: Account invite response. + content: + application/json: + schema: + $ref: '#/components/schemas/CreateInviteResponse' + '400': + $ref: '#/components/responses/Error400Response' + '401': + $ref: '#/components/responses/Error401Response' + '429': + $ref: '#/components/responses/Error429Response' + '500': + $ref: '#/components/responses/Error500Response' + security: + - polymarket_proxy: [] + polymarket_secret: [] +components: + schemas: + CreateInviteRequest: + type: object + additionalProperties: false + CreateInviteResponse: + type: object + required: + - status + - code + - referrals_available + - cooldown_ms + properties: + status: + type: string + enum: + - ok + code: + $ref: '#/components/schemas/code' + referrals_available: + type: integer + minimum: 0 + description: Remaining lifetime referrals for this invite code. + cooldown_ms: + type: integer + nullable: true + minimum: 0 + description: >- + Milliseconds until referrals become available again. Null for + lifetime caps because no windowed cooldown applies. + code: + type: string + description: Referral or invite code + example: ABC123 + Error400: + title: Error400 + type: object + required: + - status + - error + properties: + status: + type: string + enum: + - err + error: + $ref: '#/components/schemas/error' + Error401: + title: Error401 + type: object + required: + - status + - error + properties: + status: + type: string + enum: + - err + error: + $ref: '#/components/schemas/error' + Error429: + title: Error429 + type: object + required: + - status + - error + properties: + status: + type: string + enum: + - err + error: + $ref: '#/components/schemas/error' + Error500: + title: Error500 + type: object + required: + - status + - error + properties: + status: + type: string + enum: + - err + error: + $ref: '#/components/schemas/error' + error: + type: string + description: >- + Error identifier. For domain rejections and transport errors + (`401`/`404`/`429`/`500`) this is a stable, machine-readable snake_case + identifier that is part of the API contract and safe to branch on, e.g. + `insufficient_margin`, `insufficient_balance`, `order_not_found`, + `reduce_only_invalid`, `unauthorized`, `not_found`. For `400` it is a + human-readable validation detail whose wording may change. See the Error + handling guide for the domain identifiers. (Post-only / Fill-or-Kill + outcomes are order statuses such as `post_only_rejected`, not + rejections.) + example: insufficient_margin + responses: + Error400Response: + description: | + Bad request — the request was malformed or failed validation (bad query + parameters, unparseable body, invalid signature, or a domain pre-check). + The `error` field is a human-readable validation detail. + content: + application/json: + schema: + $ref: '#/components/schemas/Error400' + Error401Response: + description: > + Unauthorized — missing or invalid `POLYMARKET-PROXY` / + `POLYMARKET-SECRET` + + credentials. `error` is `unauthorized`. + content: + application/json: + schema: + $ref: '#/components/schemas/Error401' + Error429Response: + description: > + Too Many Requests. `error` distinguishes the limit that was hit: + + `ip_rate_limited` (per-IP token bucket), `action_rate_limited` + (per-account + + action rate), or `open_orders_limit` (resting open-order cap). + headers: + Retry-After: + description: > + Whole seconds to wait before retrying. Present only on token-bucket + + rate-limit rejections (`ip_rate_limited` and `action_rate_limited`); + a + + conservative estimate of when enough capacity will have refilled to + + admit the request. Absent on `open_orders_limit`, which is a + capacity + + limit, not a rate limit — waiting does not free order slots; cancel + + resting orders or wait for fills instead. + schema: + type: integer + example: 2 + content: + application/json: + schema: + $ref: '#/components/schemas/Error429' + Error500Response: + description: | + Internal server error. `error` is `internal_error`. + content: + application/json: + schema: + $ref: '#/components/schemas/Error500' + securitySchemes: + polymarket_proxy: + type: apiKey + name: POLYMARKET-PROXY + in: header + description: Proxy address + polymarket_secret: + type: apiKey + name: POLYMARKET-SECRET + in: header + description: Correponding proxy secret + +```` \ No newline at end of file diff --git a/PolymarketDocumentation-main/docs/api-reference/create-orders.md b/PolymarketDocumentation-main/docs/api-reference/create-orders.md new file mode 100644 index 00000000..7c2fd4c6 --- /dev/null +++ b/PolymarketDocumentation-main/docs/api-reference/create-orders.md @@ -0,0 +1,362 @@ +> ## Documentation Index +> Fetch the complete documentation index at: https://docs.polymarket.com/llms.txt +> Use this file to discover all available pages before exploring further. + +# Create Orders + +> Create new orders. +Requires proxy signature, see [proxy signing](/http/signing#2-proxy-signing). + + +Request Weight: **1 + floor(n / 20)** Action Weight: **1 / order** + + +## OpenAPI + +````yaml /api-spec/perps-openapi.json post /v1/trade/orders +openapi: 3.0.3 +info: + title: Polymarket Perps HTTP API + version: 1.0.0 + description: HTTP API for Polymarket perpetual trading system. + license: + name: Apache 2.0 + url: https://www.apache.org/licenses/LICENSE-2.0.html +servers: + - url: https://api.perpetuals.polymarket.com + description: Production Perps HTTP API +security: [] +paths: + /v1/trade/orders: + post: + summary: Create Orders + description: > + Create new orders. + + Requires proxy signature, see [proxy + signing](/http/signing#2-proxy-signing). + operationId: createOrders + requestBody: + description: Order request. + content: + application/json: + schema: + $ref: '#/components/schemas/OrderRequest' + responses: + '200': + description: >- + Order ACK response. Order result should be fetched using the get + orders endpoint. + content: + application/json: + schema: + type: array + items: + $ref: '#/components/schemas/OrderResponse' + '400': + $ref: '#/components/responses/Error400Response' + '429': + $ref: '#/components/responses/Error429Response' + '500': + $ref: '#/components/responses/Error500Response' + security: [] +components: + schemas: + OrderRequest: + allOf: + - type: object + required: + - op + properties: + op: + $ref: '#/components/schemas/OpCreateOrders' + - $ref: '#/components/schemas/BaseOp' + - type: object + properties: + exp: + $ref: '#/components/schemas/exp' + OrderResponse: + oneOf: + - $ref: '#/components/schemas/OrderAccepted' + - $ref: '#/components/schemas/OrderRejected' + OpCreateOrders: + type: object + required: + - type + - args + properties: + type: + type: string + enum: + - createOrders + args: + type: array + items: + $ref: '#/components/schemas/CreateOrder' + grp: + $ref: '#/components/schemas/grp' + BaseOp: + type: object + required: + - sig + - salt + - ts + properties: + sig: + $ref: '#/components/schemas/sig' + salt: + $ref: '#/components/schemas/salt' + ts: + $ref: '#/components/schemas/ts' + exp: + type: integer + description: >- + Command expiry timestamp in Unix milliseconds. If provided, it must be + in the future and within the gateway's default command timeout. It can + shorten request validity but cannot extend it. This is not an order + auto-cancel time. + example: 1767225600000 + OrderAccepted: + type: object + required: + - status + - oid + properties: + status: + type: string + enum: + - ok + oid: + $ref: '#/components/schemas/oid' + coid: + $ref: '#/components/schemas/coid' + description: Echoed only when the request carried a client_order_id. + OrderRejected: + type: object + required: + - status + - error + properties: + status: + type: string + enum: + - err + oid: + $ref: '#/components/schemas/oid' + coid: + $ref: '#/components/schemas/coid' + error: + $ref: '#/components/schemas/error' + Error400: + title: Error400 + type: object + required: + - status + - error + properties: + status: + type: string + enum: + - err + error: + $ref: '#/components/schemas/error' + Error429: + title: Error429 + type: object + required: + - status + - error + properties: + status: + type: string + enum: + - err + error: + $ref: '#/components/schemas/error' + Error500: + title: Error500 + type: object + required: + - status + - error + properties: + status: + type: string + enum: + - err + error: + $ref: '#/components/schemas/error' + CreateOrder: + type: object + required: + - iid + - buy + - qty + properties: + iid: + $ref: '#/components/schemas/iid' + buy: + $ref: '#/components/schemas/buy' + p: + $ref: '#/components/schemas/p' + qty: + $ref: '#/components/schemas/qty' + tif: + $ref: '#/components/schemas/tif' + po: + $ref: '#/components/schemas/po' + ro: + $ref: '#/components/schemas/ro' + c: + $ref: '#/components/schemas/coid' + tr: + type: object + description: Optional trigger attached to this order. + properties: + market: + $ref: '#/components/schemas/market' + trp: + $ref: '#/components/schemas/trp' + tpsl: + $ref: '#/components/schemas/tpsl' + grp: + type: string + description: TPSL grouping + enum: + - order + - position + sig: + type: string + description: Signature in hex format + example: 0x1234567890... + salt: + type: integer + description: Salt + example: 1234567890 + ts: + type: integer + description: >- + Request timestamp. Unix milliseconds for most operations; Unix seconds + for withdrawals (must match the on-chain EIP-712 struct verified against + block.timestamp). + example: 1767225600000 + oid: + type: integer + description: Order ID + example: 1234567890 + coid: + type: string + description: Client order ID + minLength: 32 + maxLength: 32 + pattern: ^[0-9a-f]{32}$ + example: 550e8400e29b41d4a716446655440000 + error: + type: string + description: >- + Error identifier. For domain rejections and transport errors + (`401`/`404`/`429`/`500`) this is a stable, machine-readable snake_case + identifier that is part of the API contract and safe to branch on, e.g. + `insufficient_margin`, `insufficient_balance`, `order_not_found`, + `reduce_only_invalid`, `unauthorized`, `not_found`. For `400` it is a + human-readable validation detail whose wording may change. See the Error + handling guide for the domain identifiers. (Post-only / Fill-or-Kill + outcomes are order statuses such as `post_only_rejected`, not + rejections.) + example: insufficient_margin + iid: + type: integer + description: Instrument ID + example: 1 + buy: + type: boolean + description: Is buy + example: true + p: + type: string + description: Price + example: '100.00' + qty: + type: string + description: Quantity in no. of contracts + example: '10.00' + tif: + type: string + description: Time in force + enum: + - gtc + - ioc + - fok + po: + type: boolean + description: Post only + default: false + example: false + ro: + type: boolean + description: Reduce only + example: false + default: false + market: + type: boolean + description: Whether the trigger executes as a market order + trp: + type: string + description: Trigger price + example: '110.00' + tpsl: + type: string + description: Trigger type + enum: + - tp + - sl + responses: + Error400Response: + description: | + Bad request — the request was malformed or failed validation (bad query + parameters, unparseable body, invalid signature, or a domain pre-check). + The `error` field is a human-readable validation detail. + content: + application/json: + schema: + $ref: '#/components/schemas/Error400' + Error429Response: + description: > + Too Many Requests. `error` distinguishes the limit that was hit: + + `ip_rate_limited` (per-IP token bucket), `action_rate_limited` + (per-account + + action rate), or `open_orders_limit` (resting open-order cap). + headers: + Retry-After: + description: > + Whole seconds to wait before retrying. Present only on token-bucket + + rate-limit rejections (`ip_rate_limited` and `action_rate_limited`); + a + + conservative estimate of when enough capacity will have refilled to + + admit the request. Absent on `open_orders_limit`, which is a + capacity + + limit, not a rate limit — waiting does not free order slots; cancel + + resting orders or wait for fills instead. + schema: + type: integer + example: 2 + content: + application/json: + schema: + $ref: '#/components/schemas/Error429' + Error500Response: + description: | + Internal server error. `error` is `internal_error`. + content: + application/json: + schema: + $ref: '#/components/schemas/Error500' + +```` \ No newline at end of file diff --git a/PolymarketDocumentation-main/docs/api-reference/create-proxy.md b/PolymarketDocumentation-main/docs/api-reference/create-proxy.md new file mode 100644 index 00000000..a327027d --- /dev/null +++ b/PolymarketDocumentation-main/docs/api-reference/create-proxy.md @@ -0,0 +1,302 @@ +> ## Documentation Index +> Fetch the complete documentation index at: https://docs.polymarket.com/llms.txt +> Use this file to discover all available pages before exploring further. + +# Create Proxy + +> Create a new proxy to sign orders. Returns an API secret for private account access. +Requires EOA signature, see [EOA signing](/http/signing#1-eoa-signing). + + +Request Weight: **1** + + +## OpenAPI + +````yaml /api-spec/perps-openapi.json post /v1/account/proxy +openapi: 3.0.3 +info: + title: Polymarket Perps HTTP API + version: 1.0.0 + description: HTTP API for Polymarket perpetual trading system. + license: + name: Apache 2.0 + url: https://www.apache.org/licenses/LICENSE-2.0.html +servers: + - url: https://api.perpetuals.polymarket.com + description: Production Perps HTTP API +security: [] +paths: + /v1/account/proxy: + post: + summary: Create Proxy + description: > + Create a new proxy to sign orders. Returns an API secret for private + account access. + + Requires EOA signature, see [EOA signing](/http/signing#1-eoa-signing). + operationId: createProxy + requestBody: + description: Proxy creation request. + content: + application/json: + schema: + $ref: '#/components/schemas/ProxyRequest' + examples: + createProxy: + summary: Create a proxy + value: + op: + type: createProxy + args: + owner: '0xf39Fd6e51aad88F6F4ce6aB8827279cffFb92266' + proxy: '0x70997970C51812dc3A010C7d01b50e0d17dc79C8' + expiry: 1767225600000 + sig: >- + 0x4d11d89f6d8e2f0fd22fb5dd9e6e88a35f3a2c0f3a9e4ff9f8f0da5e6c5f241d2ed7d173f7fcb15726b8a7e7f1f1277ec54c060f5b3ab4d72dbf4d0e40ee6e9a1c + salt: 123456789 + ts: 1767000000000 + responses: + '200': + description: Proxy creation response. + content: + application/json: + schema: + $ref: '#/components/schemas/ProxyResponse' + '400': + $ref: '#/components/responses/Error400Response' + '422': + $ref: '#/components/responses/Error422Response' + '429': + $ref: '#/components/responses/Error429Response' + '500': + $ref: '#/components/responses/Error500Response' + security: [] +components: + schemas: + ProxyRequest: + allOf: + - type: object + required: + - op + properties: + op: + $ref: '#/components/schemas/OpCreateProxy' + - $ref: '#/components/schemas/BaseOp' + - type: object + properties: + label: + $ref: '#/components/schemas/label' + code: + $ref: '#/components/schemas/code' + ProxyResponse: + type: object + required: + - status + - secret + properties: + status: + type: string + enum: + - ok + secret: + $ref: '#/components/schemas/secret' + OpCreateProxy: + type: object + required: + - type + - args + properties: + type: + type: string + enum: + - createProxy + args: + type: object + required: + - owner + - proxy + - expiry + properties: + owner: + $ref: '#/components/schemas/owner' + proxy: + $ref: '#/components/schemas/proxy' + expiry: + $ref: '#/components/schemas/expiry' + BaseOp: + type: object + required: + - sig + - salt + - ts + properties: + sig: + $ref: '#/components/schemas/sig' + salt: + $ref: '#/components/schemas/salt' + ts: + $ref: '#/components/schemas/ts' + label: + type: string + description: Human-readable label for a proxy key or internal transfer + example: trading-bot + code: + type: string + description: Referral or invite code + example: ABC123 + secret: + type: string + description: API secret + example: wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY + Error400: + title: Error400 + type: object + required: + - status + - error + properties: + status: + type: string + enum: + - err + error: + $ref: '#/components/schemas/error' + GenericRejected: + type: object + required: + - status + - error + properties: + status: + type: string + enum: + - err + error: + $ref: '#/components/schemas/error' + Error429: + title: Error429 + type: object + required: + - status + - error + properties: + status: + type: string + enum: + - err + error: + $ref: '#/components/schemas/error' + Error500: + title: Error500 + type: object + required: + - status + - error + properties: + status: + type: string + enum: + - err + error: + $ref: '#/components/schemas/error' + owner: + type: string + description: Owner address in hex format + example: '0x1234567890abcdef1234567890abcdef12345678' + proxy: + type: string + description: Proxy address in hex format + example: '0x70997970C51812dc3A010C7d01b50e0d17dc79C8' + expiry: + type: integer + description: Expiry timestamp in milliseconds + example: 1767225600000 + sig: + type: string + description: Signature in hex format + example: 0x1234567890... + salt: + type: integer + description: Salt + example: 1234567890 + ts: + type: integer + description: >- + Request timestamp. Unix milliseconds for most operations; Unix seconds + for withdrawals (must match the on-chain EIP-712 struct verified against + block.timestamp). + example: 1767225600000 + error: + type: string + description: >- + Error identifier. For domain rejections and transport errors + (`401`/`404`/`429`/`500`) this is a stable, machine-readable snake_case + identifier that is part of the API contract and safe to branch on, e.g. + `insufficient_margin`, `insufficient_balance`, `order_not_found`, + `reduce_only_invalid`, `unauthorized`, `not_found`. For `400` it is a + human-readable validation detail whose wording may change. See the Error + handling guide for the domain identifiers. (Post-only / Fill-or-Kill + outcomes are order statuses such as `post_only_rejected`, not + rejections.) + example: insufficient_margin + responses: + Error400Response: + description: | + Bad request — the request was malformed or failed validation (bad query + parameters, unparseable body, invalid signature, or a domain pre-check). + The `error` field is a human-readable validation detail. + content: + application/json: + schema: + $ref: '#/components/schemas/Error400' + Error422Response: + description: | + Unprocessable Entity — the request was well-formed but a domain rule + rejected it on its merits (insufficient balance, invalid leverage, + proxy already exists, …). The body is the discriminated rejection + (`status: err`) with the engine error identifier in `error`. + content: + application/json: + schema: + $ref: '#/components/schemas/GenericRejected' + Error429Response: + description: > + Too Many Requests. `error` distinguishes the limit that was hit: + + `ip_rate_limited` (per-IP token bucket), `action_rate_limited` + (per-account + + action rate), or `open_orders_limit` (resting open-order cap). + headers: + Retry-After: + description: > + Whole seconds to wait before retrying. Present only on token-bucket + + rate-limit rejections (`ip_rate_limited` and `action_rate_limited`); + a + + conservative estimate of when enough capacity will have refilled to + + admit the request. Absent on `open_orders_limit`, which is a + capacity + + limit, not a rate limit — waiting does not free order slots; cancel + + resting orders or wait for fills instead. + schema: + type: integer + example: 2 + content: + application/json: + schema: + $ref: '#/components/schemas/Error429' + Error500Response: + description: | + Internal server error. `error` is `internal_error`. + content: + application/json: + schema: + $ref: '#/components/schemas/Error500' + +```` \ No newline at end of file diff --git a/PolymarketDocumentation-main/docs/api-reference/data/get-midpoint-price.md b/PolymarketDocumentation-main/docs/api-reference/data/get-midpoint-price.md new file mode 100644 index 00000000..cb12e764 --- /dev/null +++ b/PolymarketDocumentation-main/docs/api-reference/data/get-midpoint-price.md @@ -0,0 +1,111 @@ +> ## Documentation Index +> Fetch the complete documentation index at: https://docs.polymarket.com/llms.txt +> Use this file to discover all available pages before exploring further. + +# Get midpoint price + +> Retrieves the midpoint price for a specific token ID. +The midpoint is calculated as the average of the best bid and best ask prices. + + + + +## OpenAPI + +````yaml /api-spec/clob-openapi.yaml get /midpoint +openapi: 3.1.0 +info: + title: Polymarket CLOB API + description: Polymarket CLOB API Reference + license: + name: MIT + identifier: MIT + version: 1.0.0 +servers: + - url: https://clob.polymarket.com + description: Production CLOB API + - url: https://clob-staging.polymarket.com + description: Staging CLOB API +security: [] +tags: + - name: Trade + description: Trade endpoints + - name: Markets + description: Market data endpoints + - name: Account + description: Account and authentication endpoints + - name: Notifications + description: User notification endpoints + - name: Rewards + description: Rewards and earnings endpoints + - name: Rebates + description: Maker rebate endpoints +paths: + /midpoint: + get: + tags: + - Data + summary: Get midpoint price + description: > + Retrieves the midpoint price for a specific token ID. + + The midpoint is calculated as the average of the best bid and best ask + prices. + operationId: getMidpoint + parameters: + - name: token_id + in: query + description: Token ID (asset ID) + required: true + schema: + type: string + example: 0xabc123def456... + responses: + '200': + description: Successfully retrieved midpoint price + content: + application/json: + schema: + type: object + required: + - mid_price + properties: + mid_price: + type: string + description: Midpoint price as a string + example: '0.45' + '400': + description: Bad request - Invalid token id + content: + application/json: + schema: + $ref: '#/components/schemas/ErrorResponse' + example: + error: Invalid token id + '404': + description: Not found - No orderbook exists for the requested token id + content: + application/json: + schema: + $ref: '#/components/schemas/ErrorResponse' + example: + error: No orderbook exists for the requested token id + security: [] +components: + schemas: + ErrorResponse: + type: object + required: + - error + properties: + error: + type: string + description: Error message + code: + type: string + description: Machine-readable error code, when provided + retry_after_seconds: + type: integer + description: Number of seconds to wait before retrying, when provided + +```` \ No newline at end of file diff --git a/PolymarketDocumentation-main/docs/api-reference/data/get-server-time.md b/PolymarketDocumentation-main/docs/api-reference/data/get-server-time.md new file mode 100644 index 00000000..6d5400ab --- /dev/null +++ b/PolymarketDocumentation-main/docs/api-reference/data/get-server-time.md @@ -0,0 +1,87 @@ +> ## Documentation Index +> Fetch the complete documentation index at: https://docs.polymarket.com/llms.txt +> Use this file to discover all available pages before exploring further. + +# Get server time + +> Returns the current Unix timestamp of the server. +This can be used to synchronize client time with server time. + + + + +## OpenAPI + +````yaml /api-spec/clob-openapi.yaml get /time +openapi: 3.1.0 +info: + title: Polymarket CLOB API + description: Polymarket CLOB API Reference + license: + name: MIT + identifier: MIT + version: 1.0.0 +servers: + - url: https://clob.polymarket.com + description: Production CLOB API + - url: https://clob-staging.polymarket.com + description: Staging CLOB API +security: [] +tags: + - name: Trade + description: Trade endpoints + - name: Markets + description: Market data endpoints + - name: Account + description: Account and authentication endpoints + - name: Notifications + description: User notification endpoints + - name: Rewards + description: Rewards and earnings endpoints + - name: Rebates + description: Maker rebate endpoints +paths: + /time: + get: + tags: + - Data + summary: Get server time + description: | + Returns the current Unix timestamp of the server. + This can be used to synchronize client time with server time. + operationId: getTime + responses: + '200': + description: Successfully retrieved server time + content: + application/json: + schema: + type: integer + format: int64 + description: Unix timestamp (seconds since epoch) + example: 1234567890 + '400': + description: Bad request + content: + application/json: + schema: + $ref: '#/components/schemas/ErrorResponse' + security: [] +components: + schemas: + ErrorResponse: + type: object + required: + - error + properties: + error: + type: string + description: Error message + code: + type: string + description: Machine-readable error code, when provided + retry_after_seconds: + type: integer + description: Number of seconds to wait before retrying, when provided + +```` \ No newline at end of file diff --git a/PolymarketDocumentation-main/docs/api-reference/delete-proxy.md b/PolymarketDocumentation-main/docs/api-reference/delete-proxy.md new file mode 100644 index 00000000..b6caa38c --- /dev/null +++ b/PolymarketDocumentation-main/docs/api-reference/delete-proxy.md @@ -0,0 +1,263 @@ +> ## Documentation Index +> Fetch the complete documentation index at: https://docs.polymarket.com/llms.txt +> Use this file to discover all available pages before exploring further. + +# Delete Proxy + +> Delete a proxy by address. +Requires EOA signature, see [EOA signing](/http/signing#1-eoa-signing). + + +Request Weight: **1** + + +## OpenAPI + +````yaml /api-spec/perps-openapi.json delete /v1/account/proxy +openapi: 3.0.3 +info: + title: Polymarket Perps HTTP API + version: 1.0.0 + description: HTTP API for Polymarket perpetual trading system. + license: + name: Apache 2.0 + url: https://www.apache.org/licenses/LICENSE-2.0.html +servers: + - url: https://api.perpetuals.polymarket.com + description: Production Perps HTTP API +security: [] +paths: + /v1/account/proxy: + delete: + summary: Delete Proxy + description: | + Delete a proxy by address. + Requires EOA signature, see [EOA signing](/http/signing#1-eoa-signing). + operationId: deleteProxy + requestBody: + description: Delete proxy request. + content: + application/json: + schema: + $ref: '#/components/schemas/DeleteProxyRequest' + examples: + deleteProxy: + summary: Delete a proxy + value: + op: + type: deleteProxy + args: + proxy: '0x70997970C51812dc3A010C7d01b50e0d17dc79C8' + sig: >- + 0x9a0b1c2d3e4f5a6b7c8d9e0f1a2b3c4d5e6f7a8b9c0d1e2f3a4b5c6d7e8f9a0b1c2d3e4f5a6b7c8d9e0f1a2b3c4d5e6f7a8b9c0d1e2f3a4b5c6d7e8f9a1c + salt: 888888888 + ts: 1767000020000 + responses: + '200': + description: Delete proxy response. + content: + application/json: + schema: + $ref: '#/components/schemas/GenericAccepted' + '400': + $ref: '#/components/responses/Error400Response' + '422': + $ref: '#/components/responses/Error422Response' + '429': + $ref: '#/components/responses/Error429Response' + '500': + $ref: '#/components/responses/Error500Response' + security: [] +components: + schemas: + DeleteProxyRequest: + allOf: + - type: object + required: + - op + properties: + op: + $ref: '#/components/schemas/OpDeleteProxy' + - $ref: '#/components/schemas/BaseOp' + GenericAccepted: + type: object + required: + - status + properties: + status: + type: string + enum: + - ok + OpDeleteProxy: + type: object + required: + - type + - args + properties: + type: + type: string + enum: + - deleteProxy + args: + type: object + required: + - proxy + properties: + proxy: + $ref: '#/components/schemas/proxy' + BaseOp: + type: object + required: + - sig + - salt + - ts + properties: + sig: + $ref: '#/components/schemas/sig' + salt: + $ref: '#/components/schemas/salt' + ts: + $ref: '#/components/schemas/ts' + Error400: + title: Error400 + type: object + required: + - status + - error + properties: + status: + type: string + enum: + - err + error: + $ref: '#/components/schemas/error' + GenericRejected: + type: object + required: + - status + - error + properties: + status: + type: string + enum: + - err + error: + $ref: '#/components/schemas/error' + Error429: + title: Error429 + type: object + required: + - status + - error + properties: + status: + type: string + enum: + - err + error: + $ref: '#/components/schemas/error' + Error500: + title: Error500 + type: object + required: + - status + - error + properties: + status: + type: string + enum: + - err + error: + $ref: '#/components/schemas/error' + proxy: + type: string + description: Proxy address in hex format + example: '0x70997970C51812dc3A010C7d01b50e0d17dc79C8' + sig: + type: string + description: Signature in hex format + example: 0x1234567890... + salt: + type: integer + description: Salt + example: 1234567890 + ts: + type: integer + description: >- + Request timestamp. Unix milliseconds for most operations; Unix seconds + for withdrawals (must match the on-chain EIP-712 struct verified against + block.timestamp). + example: 1767225600000 + error: + type: string + description: >- + Error identifier. For domain rejections and transport errors + (`401`/`404`/`429`/`500`) this is a stable, machine-readable snake_case + identifier that is part of the API contract and safe to branch on, e.g. + `insufficient_margin`, `insufficient_balance`, `order_not_found`, + `reduce_only_invalid`, `unauthorized`, `not_found`. For `400` it is a + human-readable validation detail whose wording may change. See the Error + handling guide for the domain identifiers. (Post-only / Fill-or-Kill + outcomes are order statuses such as `post_only_rejected`, not + rejections.) + example: insufficient_margin + responses: + Error400Response: + description: | + Bad request — the request was malformed or failed validation (bad query + parameters, unparseable body, invalid signature, or a domain pre-check). + The `error` field is a human-readable validation detail. + content: + application/json: + schema: + $ref: '#/components/schemas/Error400' + Error422Response: + description: | + Unprocessable Entity — the request was well-formed but a domain rule + rejected it on its merits (insufficient balance, invalid leverage, + proxy already exists, …). The body is the discriminated rejection + (`status: err`) with the engine error identifier in `error`. + content: + application/json: + schema: + $ref: '#/components/schemas/GenericRejected' + Error429Response: + description: > + Too Many Requests. `error` distinguishes the limit that was hit: + + `ip_rate_limited` (per-IP token bucket), `action_rate_limited` + (per-account + + action rate), or `open_orders_limit` (resting open-order cap). + headers: + Retry-After: + description: > + Whole seconds to wait before retrying. Present only on token-bucket + + rate-limit rejections (`ip_rate_limited` and `action_rate_limited`); + a + + conservative estimate of when enough capacity will have refilled to + + admit the request. Absent on `open_orders_limit`, which is a + capacity + + limit, not a rate limit — waiting does not free order slots; cancel + + resting orders or wait for fills instead. + schema: + type: integer + example: 2 + content: + application/json: + schema: + $ref: '#/components/schemas/Error429' + Error500Response: + description: | + Internal server error. `error` is `internal_error`. + content: + application/json: + schema: + $ref: '#/components/schemas/Error500' + +```` \ No newline at end of file diff --git a/PolymarketDocumentation-main/docs/api-reference/events/get-event-by-id.md b/PolymarketDocumentation-main/docs/api-reference/events/get-event-by-id.md new file mode 100644 index 00000000..ccea68b2 --- /dev/null +++ b/PolymarketDocumentation-main/docs/api-reference/events/get-event-by-id.md @@ -0,0 +1,1213 @@ +> ## Documentation Index +> Fetch the complete documentation index at: https://docs.polymarket.com/llms.txt +> Use this file to discover all available pages before exploring further. + +# Get event by id + + + +## OpenAPI + +````yaml /api-spec/gamma-openapi.yaml get /events/{id} +openapi: 3.0.3 +info: + title: Markets API + version: 1.0.0 + description: REST API specification for public endpoints used by the Markets service. +servers: + - url: https://gamma-api.polymarket.com + description: Polymarket Gamma API Production Server +security: [] +tags: + - name: Gamma Status + description: Gamma API status and health check + - name: Sports + description: Sports-related endpoints including teams and game data + - name: Tags + description: Tag management and related tag operations + - name: Events + description: Event management and event-related operations + - name: Markets + description: Market data and market-related operations + - name: Comments + description: Comment system and user interactions + - name: Series + description: Series management and related operations + - name: Profiles + description: User profile management + - name: Search + description: Search functionality across different entity types +paths: + /events/{id}: + get: + tags: + - Events + summary: Get event by id + operationId: getEvent + parameters: + - $ref: '#/components/parameters/pathId' + - name: include_chat + in: query + schema: + type: boolean + - name: include_template + in: query + schema: + type: boolean + responses: + '200': + description: Event + content: + application/json: + schema: + $ref: '#/components/schemas/Event' + '404': + description: Not found +components: + parameters: + pathId: + name: id + in: path + required: true + schema: + type: integer + schemas: + Event: + type: object + properties: + id: + type: string + ticker: + type: string + nullable: true + slug: + type: string + nullable: true + title: + type: string + nullable: true + subtitle: + type: string + nullable: true + description: + type: string + nullable: true + resolutionSource: + type: string + nullable: true + startDate: + type: string + format: date-time + nullable: true + creationDate: + type: string + format: date-time + nullable: true + endDate: + type: string + format: date-time + nullable: true + image: + type: string + nullable: true + icon: + type: string + nullable: true + active: + type: boolean + nullable: true + closed: + type: boolean + nullable: true + archived: + type: boolean + nullable: true + new: + type: boolean + nullable: true + featured: + type: boolean + nullable: true + restricted: + type: boolean + nullable: true + liquidity: + type: number + nullable: true + volume: + type: number + nullable: true + openInterest: + type: number + nullable: true + sortBy: + type: string + nullable: true + category: + type: string + nullable: true + subcategory: + type: string + nullable: true + isTemplate: + type: boolean + nullable: true + templateVariables: + type: string + nullable: true + published_at: + type: string + nullable: true + createdBy: + type: string + nullable: true + updatedBy: + type: string + nullable: true + createdAt: + type: string + format: date-time + nullable: true + updatedAt: + type: string + format: date-time + nullable: true + commentsEnabled: + type: boolean + nullable: true + competitive: + type: number + nullable: true + volume24hr: + type: number + nullable: true + volume1wk: + type: number + nullable: true + volume1mo: + type: number + nullable: true + volume1yr: + type: number + nullable: true + featuredImage: + type: string + nullable: true + disqusThread: + type: string + nullable: true + parentEvent: + type: string + nullable: true + enableOrderBook: + type: boolean + nullable: true + liquidityAmm: + type: number + nullable: true + liquidityClob: + type: number + nullable: true + negRisk: + type: boolean + nullable: true + negRiskMarketID: + type: string + nullable: true + negRiskFeeBips: + type: integer + nullable: true + commentCount: + type: integer + nullable: true + imageOptimized: + $ref: '#/components/schemas/ImageOptimization' + iconOptimized: + $ref: '#/components/schemas/ImageOptimization' + featuredImageOptimized: + $ref: '#/components/schemas/ImageOptimization' + subEvents: + type: array + items: + type: string + nullable: true + markets: + type: array + items: + $ref: '#/components/schemas/Market' + series: + type: array + items: + $ref: '#/components/schemas/Series' + categories: + type: array + items: + $ref: '#/components/schemas/Category' + collections: + type: array + items: + $ref: '#/components/schemas/Collection' + tags: + type: array + items: + $ref: '#/components/schemas/Tag' + cyom: + type: boolean + nullable: true + closedTime: + type: string + format: date-time + nullable: true + showAllOutcomes: + type: boolean + nullable: true + showMarketImages: + type: boolean + nullable: true + automaticallyResolved: + type: boolean + nullable: true + enableNegRisk: + type: boolean + nullable: true + automaticallyActive: + type: boolean + nullable: true + eventDate: + type: string + nullable: true + startTime: + type: string + format: date-time + nullable: true + eventWeek: + type: integer + nullable: true + seriesSlug: + type: string + nullable: true + score: + type: string + nullable: true + elapsed: + type: string + nullable: true + period: + type: string + nullable: true + live: + type: boolean + nullable: true + ended: + type: boolean + nullable: true + finishedTimestamp: + type: string + format: date-time + nullable: true + gmpChartMode: + type: string + nullable: true + eventCreators: + type: array + items: + $ref: '#/components/schemas/EventCreator' + tweetCount: + type: integer + nullable: true + chats: + type: array + items: + $ref: '#/components/schemas/Chat' + featuredOrder: + type: integer + nullable: true + estimateValue: + type: boolean + nullable: true + cantEstimate: + type: boolean + nullable: true + estimatedValue: + type: string + nullable: true + templates: + type: array + items: + $ref: '#/components/schemas/Template' + spreadsMainLine: + type: number + nullable: true + totalsMainLine: + type: number + nullable: true + carouselMap: + type: string + nullable: true + pendingDeployment: + type: boolean + nullable: true + deploying: + type: boolean + nullable: true + deployingTimestamp: + type: string + format: date-time + nullable: true + scheduledDeploymentTimestamp: + type: string + format: date-time + nullable: true + gameStatus: + type: string + nullable: true + ImageOptimization: + type: object + properties: + id: + type: string + imageUrlSource: + type: string + nullable: true + imageUrlOptimized: + type: string + nullable: true + imageSizeKbSource: + type: number + nullable: true + imageSizeKbOptimized: + type: number + nullable: true + imageOptimizedComplete: + type: boolean + nullable: true + imageOptimizedLastUpdated: + type: string + nullable: true + relID: + type: integer + nullable: true + field: + type: string + nullable: true + relname: + type: string + nullable: true + Market: + type: object + properties: + id: + type: string + question: + type: string + nullable: true + conditionId: + type: string + slug: + type: string + nullable: true + twitterCardImage: + type: string + nullable: true + resolutionSource: + type: string + nullable: true + endDate: + type: string + format: date-time + nullable: true + category: + type: string + nullable: true + ammType: + type: string + nullable: true + liquidity: + type: string + nullable: true + sponsorName: + type: string + nullable: true + sponsorImage: + type: string + nullable: true + startDate: + type: string + format: date-time + nullable: true + xAxisValue: + type: string + nullable: true + yAxisValue: + type: string + nullable: true + denominationToken: + type: string + nullable: true + fee: + type: string + nullable: true + image: + type: string + nullable: true + icon: + type: string + nullable: true + lowerBound: + type: string + nullable: true + upperBound: + type: string + nullable: true + description: + type: string + nullable: true + outcomes: + type: string + nullable: true + outcomePrices: + type: string + nullable: true + volume: + type: string + nullable: true + active: + type: boolean + nullable: true + marketType: + type: string + nullable: true + formatType: + type: string + nullable: true + lowerBoundDate: + type: string + nullable: true + upperBoundDate: + type: string + nullable: true + closed: + type: boolean + nullable: true + marketMakerAddress: + type: string + createdBy: + type: integer + nullable: true + updatedBy: + type: integer + nullable: true + createdAt: + type: string + format: date-time + nullable: true + updatedAt: + type: string + format: date-time + nullable: true + closedTime: + type: string + nullable: true + wideFormat: + type: boolean + nullable: true + new: + type: boolean + nullable: true + mailchimpTag: + type: string + nullable: true + featured: + type: boolean + nullable: true + archived: + type: boolean + nullable: true + resolvedBy: + type: string + nullable: true + restricted: + type: boolean + nullable: true + marketGroup: + type: integer + nullable: true + groupItemTitle: + type: string + nullable: true + groupItemThreshold: + type: string + nullable: true + questionID: + type: string + nullable: true + umaEndDate: + type: string + nullable: true + enableOrderBook: + type: boolean + nullable: true + orderPriceMinTickSize: + type: number + nullable: true + orderMinSize: + type: number + nullable: true + umaResolutionStatus: + type: string + nullable: true + curationOrder: + type: integer + nullable: true + volumeNum: + type: number + nullable: true + liquidityNum: + type: number + nullable: true + endDateIso: + type: string + nullable: true + startDateIso: + type: string + nullable: true + umaEndDateIso: + type: string + nullable: true + hasReviewedDates: + type: boolean + nullable: true + readyForCron: + type: boolean + nullable: true + commentsEnabled: + type: boolean + nullable: true + volume24hr: + type: number + nullable: true + volume1wk: + type: number + nullable: true + volume1mo: + type: number + nullable: true + volume1yr: + type: number + nullable: true + gameStartTime: + type: string + nullable: true + secondsDelay: + type: integer + nullable: true + clobTokenIds: + type: string + nullable: true + disqusThread: + type: string + nullable: true + shortOutcomes: + type: string + nullable: true + teamAID: + type: string + nullable: true + teamBID: + type: string + nullable: true + umaBond: + type: string + nullable: true + umaReward: + type: string + nullable: true + fpmmLive: + type: boolean + nullable: true + volume24hrAmm: + type: number + nullable: true + volume1wkAmm: + type: number + nullable: true + volume1moAmm: + type: number + nullable: true + volume1yrAmm: + type: number + nullable: true + volume24hrClob: + type: number + nullable: true + volume1wkClob: + type: number + nullable: true + volume1moClob: + type: number + nullable: true + volume1yrClob: + type: number + nullable: true + volumeAmm: + type: number + nullable: true + volumeClob: + type: number + nullable: true + liquidityAmm: + type: number + nullable: true + liquidityClob: + type: number + nullable: true + makerBaseFee: + type: integer + nullable: true + takerBaseFee: + type: integer + nullable: true + customLiveness: + type: integer + nullable: true + acceptingOrders: + type: boolean + nullable: true + notificationsEnabled: + type: boolean + nullable: true + score: + type: integer + nullable: true + imageOptimized: + $ref: '#/components/schemas/ImageOptimization' + iconOptimized: + $ref: '#/components/schemas/ImageOptimization' + events: + type: array + items: + $ref: '#/components/schemas/Event' + categories: + type: array + items: + $ref: '#/components/schemas/Category' + tags: + type: array + items: + $ref: '#/components/schemas/Tag' + creator: + type: string + nullable: true + ready: + type: boolean + nullable: true + funded: + type: boolean + nullable: true + pastSlugs: + type: string + nullable: true + readyTimestamp: + type: string + format: date-time + nullable: true + fundedTimestamp: + type: string + format: date-time + nullable: true + acceptingOrdersTimestamp: + type: string + format: date-time + nullable: true + competitive: + type: number + nullable: true + rewardsMinSize: + type: number + nullable: true + rewardsMaxSpread: + type: number + nullable: true + spread: + type: number + nullable: true + automaticallyResolved: + type: boolean + nullable: true + oneDayPriceChange: + type: number + nullable: true + oneHourPriceChange: + type: number + nullable: true + oneWeekPriceChange: + type: number + nullable: true + oneMonthPriceChange: + type: number + nullable: true + oneYearPriceChange: + type: number + nullable: true + lastTradePrice: + type: number + nullable: true + bestBid: + type: number + nullable: true + bestAsk: + type: number + nullable: true + automaticallyActive: + type: boolean + nullable: true + clearBookOnStart: + type: boolean + nullable: true + chartColor: + type: string + nullable: true + seriesColor: + type: string + nullable: true + showGmpSeries: + type: boolean + nullable: true + showGmpOutcome: + type: boolean + nullable: true + manualActivation: + type: boolean + nullable: true + negRiskOther: + type: boolean + nullable: true + gameId: + type: string + nullable: true + groupItemRange: + type: string + nullable: true + sportsMarketType: + type: string + nullable: true + line: + type: number + nullable: true + umaResolutionStatuses: + type: string + nullable: true + pendingDeployment: + type: boolean + nullable: true + deploying: + type: boolean + nullable: true + deployingTimestamp: + type: string + format: date-time + nullable: true + scheduledDeploymentTimestamp: + type: string + format: date-time + nullable: true + rfqEnabled: + type: boolean + nullable: true + eventStartTime: + type: string + format: date-time + nullable: true + feesEnabled: + type: boolean + nullable: true + feeSchedule: + $ref: '#/components/schemas/FeeSchedule' + Series: + type: object + properties: + id: + type: string + ticker: + type: string + nullable: true + slug: + type: string + nullable: true + title: + type: string + nullable: true + subtitle: + type: string + nullable: true + seriesType: + type: string + nullable: true + recurrence: + type: string + nullable: true + description: + type: string + nullable: true + image: + type: string + nullable: true + icon: + type: string + nullable: true + layout: + type: string + nullable: true + active: + type: boolean + nullable: true + closed: + type: boolean + nullable: true + archived: + type: boolean + nullable: true + new: + type: boolean + nullable: true + featured: + type: boolean + nullable: true + restricted: + type: boolean + nullable: true + isTemplate: + type: boolean + nullable: true + templateVariables: + type: boolean + nullable: true + publishedAt: + type: string + nullable: true + createdBy: + type: string + nullable: true + updatedBy: + type: string + nullable: true + createdAt: + type: string + format: date-time + nullable: true + updatedAt: + type: string + format: date-time + nullable: true + commentsEnabled: + type: boolean + nullable: true + competitive: + type: string + nullable: true + volume24hr: + type: number + nullable: true + volume: + type: number + nullable: true + liquidity: + type: number + nullable: true + startDate: + type: string + format: date-time + nullable: true + pythTokenID: + type: string + nullable: true + cgAssetName: + type: string + nullable: true + score: + type: integer + nullable: true + events: + type: array + items: + $ref: '#/components/schemas/Event' + collections: + type: array + items: + $ref: '#/components/schemas/Collection' + categories: + type: array + items: + $ref: '#/components/schemas/Category' + tags: + type: array + items: + $ref: '#/components/schemas/Tag' + commentCount: + type: integer + nullable: true + chats: + type: array + items: + $ref: '#/components/schemas/Chat' + Category: + type: object + properties: + id: + type: string + label: + type: string + nullable: true + parentCategory: + type: string + nullable: true + slug: + type: string + nullable: true + publishedAt: + type: string + nullable: true + createdBy: + type: string + nullable: true + updatedBy: + type: string + nullable: true + createdAt: + type: string + format: date-time + nullable: true + updatedAt: + type: string + format: date-time + nullable: true + Collection: + type: object + properties: + id: + type: string + ticker: + type: string + nullable: true + slug: + type: string + nullable: true + title: + type: string + nullable: true + subtitle: + type: string + nullable: true + collectionType: + type: string + nullable: true + description: + type: string + nullable: true + tags: + type: string + nullable: true + image: + type: string + nullable: true + icon: + type: string + nullable: true + headerImage: + type: string + nullable: true + layout: + type: string + nullable: true + active: + type: boolean + nullable: true + closed: + type: boolean + nullable: true + archived: + type: boolean + nullable: true + new: + type: boolean + nullable: true + featured: + type: boolean + nullable: true + restricted: + type: boolean + nullable: true + isTemplate: + type: boolean + nullable: true + templateVariables: + type: string + nullable: true + publishedAt: + type: string + nullable: true + createdBy: + type: string + nullable: true + updatedBy: + type: string + nullable: true + createdAt: + type: string + format: date-time + nullable: true + updatedAt: + type: string + format: date-time + nullable: true + commentsEnabled: + type: boolean + nullable: true + imageOptimized: + $ref: '#/components/schemas/ImageOptimization' + iconOptimized: + $ref: '#/components/schemas/ImageOptimization' + headerImageOptimized: + $ref: '#/components/schemas/ImageOptimization' + Tag: + type: object + properties: + id: + type: string + label: + type: string + nullable: true + slug: + type: string + nullable: true + forceShow: + type: boolean + nullable: true + publishedAt: + type: string + nullable: true + createdBy: + type: integer + nullable: true + updatedBy: + type: integer + nullable: true + createdAt: + type: string + format: date-time + nullable: true + updatedAt: + type: string + format: date-time + nullable: true + forceHide: + type: boolean + nullable: true + isCarousel: + type: boolean + nullable: true + EventCreator: + type: object + properties: + id: + type: string + creatorName: + type: string + nullable: true + creatorHandle: + type: string + nullable: true + creatorUrl: + type: string + nullable: true + creatorImage: + type: string + nullable: true + createdAt: + type: string + format: date-time + nullable: true + updatedAt: + type: string + format: date-time + nullable: true + Chat: + type: object + properties: + id: + type: string + channelId: + type: string + nullable: true + channelName: + type: string + nullable: true + channelImage: + type: string + nullable: true + live: + type: boolean + nullable: true + startTime: + type: string + format: date-time + nullable: true + endTime: + type: string + format: date-time + nullable: true + Template: + type: object + properties: + id: + type: string + eventTitle: + type: string + nullable: true + eventSlug: + type: string + nullable: true + eventImage: + type: string + nullable: true + marketTitle: + type: string + nullable: true + description: + type: string + nullable: true + resolutionSource: + type: string + nullable: true + negRisk: + type: boolean + nullable: true + sortBy: + type: string + nullable: true + showMarketImages: + type: boolean + nullable: true + seriesSlug: + type: string + nullable: true + outcomes: + type: string + nullable: true + FeeSchedule: + type: object + properties: + exponent: + type: number + nullable: true + rate: + type: number + nullable: true + takerOnly: + type: boolean + nullable: true + rebateRate: + type: number + nullable: true + +```` \ No newline at end of file diff --git a/PolymarketDocumentation-main/docs/api-reference/events/get-event-by-slug.md b/PolymarketDocumentation-main/docs/api-reference/events/get-event-by-slug.md new file mode 100644 index 00000000..5a724600 --- /dev/null +++ b/PolymarketDocumentation-main/docs/api-reference/events/get-event-by-slug.md @@ -0,0 +1,1213 @@ +> ## Documentation Index +> Fetch the complete documentation index at: https://docs.polymarket.com/llms.txt +> Use this file to discover all available pages before exploring further. + +# Get event by slug + + + +## OpenAPI + +````yaml /api-spec/gamma-openapi.yaml get /events/slug/{slug} +openapi: 3.0.3 +info: + title: Markets API + version: 1.0.0 + description: REST API specification for public endpoints used by the Markets service. +servers: + - url: https://gamma-api.polymarket.com + description: Polymarket Gamma API Production Server +security: [] +tags: + - name: Gamma Status + description: Gamma API status and health check + - name: Sports + description: Sports-related endpoints including teams and game data + - name: Tags + description: Tag management and related tag operations + - name: Events + description: Event management and event-related operations + - name: Markets + description: Market data and market-related operations + - name: Comments + description: Comment system and user interactions + - name: Series + description: Series management and related operations + - name: Profiles + description: User profile management + - name: Search + description: Search functionality across different entity types +paths: + /events/slug/{slug}: + get: + tags: + - Events + summary: Get event by slug + operationId: getEventBySlug + parameters: + - $ref: '#/components/parameters/pathSlug' + - name: include_chat + in: query + schema: + type: boolean + - name: include_template + in: query + schema: + type: boolean + responses: + '200': + description: Event + content: + application/json: + schema: + $ref: '#/components/schemas/Event' + '404': + description: Not found +components: + parameters: + pathSlug: + name: slug + in: path + required: true + schema: + type: string + schemas: + Event: + type: object + properties: + id: + type: string + ticker: + type: string + nullable: true + slug: + type: string + nullable: true + title: + type: string + nullable: true + subtitle: + type: string + nullable: true + description: + type: string + nullable: true + resolutionSource: + type: string + nullable: true + startDate: + type: string + format: date-time + nullable: true + creationDate: + type: string + format: date-time + nullable: true + endDate: + type: string + format: date-time + nullable: true + image: + type: string + nullable: true + icon: + type: string + nullable: true + active: + type: boolean + nullable: true + closed: + type: boolean + nullable: true + archived: + type: boolean + nullable: true + new: + type: boolean + nullable: true + featured: + type: boolean + nullable: true + restricted: + type: boolean + nullable: true + liquidity: + type: number + nullable: true + volume: + type: number + nullable: true + openInterest: + type: number + nullable: true + sortBy: + type: string + nullable: true + category: + type: string + nullable: true + subcategory: + type: string + nullable: true + isTemplate: + type: boolean + nullable: true + templateVariables: + type: string + nullable: true + published_at: + type: string + nullable: true + createdBy: + type: string + nullable: true + updatedBy: + type: string + nullable: true + createdAt: + type: string + format: date-time + nullable: true + updatedAt: + type: string + format: date-time + nullable: true + commentsEnabled: + type: boolean + nullable: true + competitive: + type: number + nullable: true + volume24hr: + type: number + nullable: true + volume1wk: + type: number + nullable: true + volume1mo: + type: number + nullable: true + volume1yr: + type: number + nullable: true + featuredImage: + type: string + nullable: true + disqusThread: + type: string + nullable: true + parentEvent: + type: string + nullable: true + enableOrderBook: + type: boolean + nullable: true + liquidityAmm: + type: number + nullable: true + liquidityClob: + type: number + nullable: true + negRisk: + type: boolean + nullable: true + negRiskMarketID: + type: string + nullable: true + negRiskFeeBips: + type: integer + nullable: true + commentCount: + type: integer + nullable: true + imageOptimized: + $ref: '#/components/schemas/ImageOptimization' + iconOptimized: + $ref: '#/components/schemas/ImageOptimization' + featuredImageOptimized: + $ref: '#/components/schemas/ImageOptimization' + subEvents: + type: array + items: + type: string + nullable: true + markets: + type: array + items: + $ref: '#/components/schemas/Market' + series: + type: array + items: + $ref: '#/components/schemas/Series' + categories: + type: array + items: + $ref: '#/components/schemas/Category' + collections: + type: array + items: + $ref: '#/components/schemas/Collection' + tags: + type: array + items: + $ref: '#/components/schemas/Tag' + cyom: + type: boolean + nullable: true + closedTime: + type: string + format: date-time + nullable: true + showAllOutcomes: + type: boolean + nullable: true + showMarketImages: + type: boolean + nullable: true + automaticallyResolved: + type: boolean + nullable: true + enableNegRisk: + type: boolean + nullable: true + automaticallyActive: + type: boolean + nullable: true + eventDate: + type: string + nullable: true + startTime: + type: string + format: date-time + nullable: true + eventWeek: + type: integer + nullable: true + seriesSlug: + type: string + nullable: true + score: + type: string + nullable: true + elapsed: + type: string + nullable: true + period: + type: string + nullable: true + live: + type: boolean + nullable: true + ended: + type: boolean + nullable: true + finishedTimestamp: + type: string + format: date-time + nullable: true + gmpChartMode: + type: string + nullable: true + eventCreators: + type: array + items: + $ref: '#/components/schemas/EventCreator' + tweetCount: + type: integer + nullable: true + chats: + type: array + items: + $ref: '#/components/schemas/Chat' + featuredOrder: + type: integer + nullable: true + estimateValue: + type: boolean + nullable: true + cantEstimate: + type: boolean + nullable: true + estimatedValue: + type: string + nullable: true + templates: + type: array + items: + $ref: '#/components/schemas/Template' + spreadsMainLine: + type: number + nullable: true + totalsMainLine: + type: number + nullable: true + carouselMap: + type: string + nullable: true + pendingDeployment: + type: boolean + nullable: true + deploying: + type: boolean + nullable: true + deployingTimestamp: + type: string + format: date-time + nullable: true + scheduledDeploymentTimestamp: + type: string + format: date-time + nullable: true + gameStatus: + type: string + nullable: true + ImageOptimization: + type: object + properties: + id: + type: string + imageUrlSource: + type: string + nullable: true + imageUrlOptimized: + type: string + nullable: true + imageSizeKbSource: + type: number + nullable: true + imageSizeKbOptimized: + type: number + nullable: true + imageOptimizedComplete: + type: boolean + nullable: true + imageOptimizedLastUpdated: + type: string + nullable: true + relID: + type: integer + nullable: true + field: + type: string + nullable: true + relname: + type: string + nullable: true + Market: + type: object + properties: + id: + type: string + question: + type: string + nullable: true + conditionId: + type: string + slug: + type: string + nullable: true + twitterCardImage: + type: string + nullable: true + resolutionSource: + type: string + nullable: true + endDate: + type: string + format: date-time + nullable: true + category: + type: string + nullable: true + ammType: + type: string + nullable: true + liquidity: + type: string + nullable: true + sponsorName: + type: string + nullable: true + sponsorImage: + type: string + nullable: true + startDate: + type: string + format: date-time + nullable: true + xAxisValue: + type: string + nullable: true + yAxisValue: + type: string + nullable: true + denominationToken: + type: string + nullable: true + fee: + type: string + nullable: true + image: + type: string + nullable: true + icon: + type: string + nullable: true + lowerBound: + type: string + nullable: true + upperBound: + type: string + nullable: true + description: + type: string + nullable: true + outcomes: + type: string + nullable: true + outcomePrices: + type: string + nullable: true + volume: + type: string + nullable: true + active: + type: boolean + nullable: true + marketType: + type: string + nullable: true + formatType: + type: string + nullable: true + lowerBoundDate: + type: string + nullable: true + upperBoundDate: + type: string + nullable: true + closed: + type: boolean + nullable: true + marketMakerAddress: + type: string + createdBy: + type: integer + nullable: true + updatedBy: + type: integer + nullable: true + createdAt: + type: string + format: date-time + nullable: true + updatedAt: + type: string + format: date-time + nullable: true + closedTime: + type: string + nullable: true + wideFormat: + type: boolean + nullable: true + new: + type: boolean + nullable: true + mailchimpTag: + type: string + nullable: true + featured: + type: boolean + nullable: true + archived: + type: boolean + nullable: true + resolvedBy: + type: string + nullable: true + restricted: + type: boolean + nullable: true + marketGroup: + type: integer + nullable: true + groupItemTitle: + type: string + nullable: true + groupItemThreshold: + type: string + nullable: true + questionID: + type: string + nullable: true + umaEndDate: + type: string + nullable: true + enableOrderBook: + type: boolean + nullable: true + orderPriceMinTickSize: + type: number + nullable: true + orderMinSize: + type: number + nullable: true + umaResolutionStatus: + type: string + nullable: true + curationOrder: + type: integer + nullable: true + volumeNum: + type: number + nullable: true + liquidityNum: + type: number + nullable: true + endDateIso: + type: string + nullable: true + startDateIso: + type: string + nullable: true + umaEndDateIso: + type: string + nullable: true + hasReviewedDates: + type: boolean + nullable: true + readyForCron: + type: boolean + nullable: true + commentsEnabled: + type: boolean + nullable: true + volume24hr: + type: number + nullable: true + volume1wk: + type: number + nullable: true + volume1mo: + type: number + nullable: true + volume1yr: + type: number + nullable: true + gameStartTime: + type: string + nullable: true + secondsDelay: + type: integer + nullable: true + clobTokenIds: + type: string + nullable: true + disqusThread: + type: string + nullable: true + shortOutcomes: + type: string + nullable: true + teamAID: + type: string + nullable: true + teamBID: + type: string + nullable: true + umaBond: + type: string + nullable: true + umaReward: + type: string + nullable: true + fpmmLive: + type: boolean + nullable: true + volume24hrAmm: + type: number + nullable: true + volume1wkAmm: + type: number + nullable: true + volume1moAmm: + type: number + nullable: true + volume1yrAmm: + type: number + nullable: true + volume24hrClob: + type: number + nullable: true + volume1wkClob: + type: number + nullable: true + volume1moClob: + type: number + nullable: true + volume1yrClob: + type: number + nullable: true + volumeAmm: + type: number + nullable: true + volumeClob: + type: number + nullable: true + liquidityAmm: + type: number + nullable: true + liquidityClob: + type: number + nullable: true + makerBaseFee: + type: integer + nullable: true + takerBaseFee: + type: integer + nullable: true + customLiveness: + type: integer + nullable: true + acceptingOrders: + type: boolean + nullable: true + notificationsEnabled: + type: boolean + nullable: true + score: + type: integer + nullable: true + imageOptimized: + $ref: '#/components/schemas/ImageOptimization' + iconOptimized: + $ref: '#/components/schemas/ImageOptimization' + events: + type: array + items: + $ref: '#/components/schemas/Event' + categories: + type: array + items: + $ref: '#/components/schemas/Category' + tags: + type: array + items: + $ref: '#/components/schemas/Tag' + creator: + type: string + nullable: true + ready: + type: boolean + nullable: true + funded: + type: boolean + nullable: true + pastSlugs: + type: string + nullable: true + readyTimestamp: + type: string + format: date-time + nullable: true + fundedTimestamp: + type: string + format: date-time + nullable: true + acceptingOrdersTimestamp: + type: string + format: date-time + nullable: true + competitive: + type: number + nullable: true + rewardsMinSize: + type: number + nullable: true + rewardsMaxSpread: + type: number + nullable: true + spread: + type: number + nullable: true + automaticallyResolved: + type: boolean + nullable: true + oneDayPriceChange: + type: number + nullable: true + oneHourPriceChange: + type: number + nullable: true + oneWeekPriceChange: + type: number + nullable: true + oneMonthPriceChange: + type: number + nullable: true + oneYearPriceChange: + type: number + nullable: true + lastTradePrice: + type: number + nullable: true + bestBid: + type: number + nullable: true + bestAsk: + type: number + nullable: true + automaticallyActive: + type: boolean + nullable: true + clearBookOnStart: + type: boolean + nullable: true + chartColor: + type: string + nullable: true + seriesColor: + type: string + nullable: true + showGmpSeries: + type: boolean + nullable: true + showGmpOutcome: + type: boolean + nullable: true + manualActivation: + type: boolean + nullable: true + negRiskOther: + type: boolean + nullable: true + gameId: + type: string + nullable: true + groupItemRange: + type: string + nullable: true + sportsMarketType: + type: string + nullable: true + line: + type: number + nullable: true + umaResolutionStatuses: + type: string + nullable: true + pendingDeployment: + type: boolean + nullable: true + deploying: + type: boolean + nullable: true + deployingTimestamp: + type: string + format: date-time + nullable: true + scheduledDeploymentTimestamp: + type: string + format: date-time + nullable: true + rfqEnabled: + type: boolean + nullable: true + eventStartTime: + type: string + format: date-time + nullable: true + feesEnabled: + type: boolean + nullable: true + feeSchedule: + $ref: '#/components/schemas/FeeSchedule' + Series: + type: object + properties: + id: + type: string + ticker: + type: string + nullable: true + slug: + type: string + nullable: true + title: + type: string + nullable: true + subtitle: + type: string + nullable: true + seriesType: + type: string + nullable: true + recurrence: + type: string + nullable: true + description: + type: string + nullable: true + image: + type: string + nullable: true + icon: + type: string + nullable: true + layout: + type: string + nullable: true + active: + type: boolean + nullable: true + closed: + type: boolean + nullable: true + archived: + type: boolean + nullable: true + new: + type: boolean + nullable: true + featured: + type: boolean + nullable: true + restricted: + type: boolean + nullable: true + isTemplate: + type: boolean + nullable: true + templateVariables: + type: boolean + nullable: true + publishedAt: + type: string + nullable: true + createdBy: + type: string + nullable: true + updatedBy: + type: string + nullable: true + createdAt: + type: string + format: date-time + nullable: true + updatedAt: + type: string + format: date-time + nullable: true + commentsEnabled: + type: boolean + nullable: true + competitive: + type: string + nullable: true + volume24hr: + type: number + nullable: true + volume: + type: number + nullable: true + liquidity: + type: number + nullable: true + startDate: + type: string + format: date-time + nullable: true + pythTokenID: + type: string + nullable: true + cgAssetName: + type: string + nullable: true + score: + type: integer + nullable: true + events: + type: array + items: + $ref: '#/components/schemas/Event' + collections: + type: array + items: + $ref: '#/components/schemas/Collection' + categories: + type: array + items: + $ref: '#/components/schemas/Category' + tags: + type: array + items: + $ref: '#/components/schemas/Tag' + commentCount: + type: integer + nullable: true + chats: + type: array + items: + $ref: '#/components/schemas/Chat' + Category: + type: object + properties: + id: + type: string + label: + type: string + nullable: true + parentCategory: + type: string + nullable: true + slug: + type: string + nullable: true + publishedAt: + type: string + nullable: true + createdBy: + type: string + nullable: true + updatedBy: + type: string + nullable: true + createdAt: + type: string + format: date-time + nullable: true + updatedAt: + type: string + format: date-time + nullable: true + Collection: + type: object + properties: + id: + type: string + ticker: + type: string + nullable: true + slug: + type: string + nullable: true + title: + type: string + nullable: true + subtitle: + type: string + nullable: true + collectionType: + type: string + nullable: true + description: + type: string + nullable: true + tags: + type: string + nullable: true + image: + type: string + nullable: true + icon: + type: string + nullable: true + headerImage: + type: string + nullable: true + layout: + type: string + nullable: true + active: + type: boolean + nullable: true + closed: + type: boolean + nullable: true + archived: + type: boolean + nullable: true + new: + type: boolean + nullable: true + featured: + type: boolean + nullable: true + restricted: + type: boolean + nullable: true + isTemplate: + type: boolean + nullable: true + templateVariables: + type: string + nullable: true + publishedAt: + type: string + nullable: true + createdBy: + type: string + nullable: true + updatedBy: + type: string + nullable: true + createdAt: + type: string + format: date-time + nullable: true + updatedAt: + type: string + format: date-time + nullable: true + commentsEnabled: + type: boolean + nullable: true + imageOptimized: + $ref: '#/components/schemas/ImageOptimization' + iconOptimized: + $ref: '#/components/schemas/ImageOptimization' + headerImageOptimized: + $ref: '#/components/schemas/ImageOptimization' + Tag: + type: object + properties: + id: + type: string + label: + type: string + nullable: true + slug: + type: string + nullable: true + forceShow: + type: boolean + nullable: true + publishedAt: + type: string + nullable: true + createdBy: + type: integer + nullable: true + updatedBy: + type: integer + nullable: true + createdAt: + type: string + format: date-time + nullable: true + updatedAt: + type: string + format: date-time + nullable: true + forceHide: + type: boolean + nullable: true + isCarousel: + type: boolean + nullable: true + EventCreator: + type: object + properties: + id: + type: string + creatorName: + type: string + nullable: true + creatorHandle: + type: string + nullable: true + creatorUrl: + type: string + nullable: true + creatorImage: + type: string + nullable: true + createdAt: + type: string + format: date-time + nullable: true + updatedAt: + type: string + format: date-time + nullable: true + Chat: + type: object + properties: + id: + type: string + channelId: + type: string + nullable: true + channelName: + type: string + nullable: true + channelImage: + type: string + nullable: true + live: + type: boolean + nullable: true + startTime: + type: string + format: date-time + nullable: true + endTime: + type: string + format: date-time + nullable: true + Template: + type: object + properties: + id: + type: string + eventTitle: + type: string + nullable: true + eventSlug: + type: string + nullable: true + eventImage: + type: string + nullable: true + marketTitle: + type: string + nullable: true + description: + type: string + nullable: true + resolutionSource: + type: string + nullable: true + negRisk: + type: boolean + nullable: true + sortBy: + type: string + nullable: true + showMarketImages: + type: boolean + nullable: true + seriesSlug: + type: string + nullable: true + outcomes: + type: string + nullable: true + FeeSchedule: + type: object + properties: + exponent: + type: number + nullable: true + rate: + type: number + nullable: true + takerOnly: + type: boolean + nullable: true + rebateRate: + type: number + nullable: true + +```` \ No newline at end of file diff --git a/PolymarketDocumentation-main/docs/api-reference/events/get-event-tags.md b/PolymarketDocumentation-main/docs/api-reference/events/get-event-tags.md new file mode 100644 index 00000000..102a5a3a --- /dev/null +++ b/PolymarketDocumentation-main/docs/api-reference/events/get-event-tags.md @@ -0,0 +1,108 @@ +> ## Documentation Index +> Fetch the complete documentation index at: https://docs.polymarket.com/llms.txt +> Use this file to discover all available pages before exploring further. + +# Get event tags + + + +## OpenAPI + +````yaml /api-spec/gamma-openapi.yaml get /events/{id}/tags +openapi: 3.0.3 +info: + title: Markets API + version: 1.0.0 + description: REST API specification for public endpoints used by the Markets service. +servers: + - url: https://gamma-api.polymarket.com + description: Polymarket Gamma API Production Server +security: [] +tags: + - name: Gamma Status + description: Gamma API status and health check + - name: Sports + description: Sports-related endpoints including teams and game data + - name: Tags + description: Tag management and related tag operations + - name: Events + description: Event management and event-related operations + - name: Markets + description: Market data and market-related operations + - name: Comments + description: Comment system and user interactions + - name: Series + description: Series management and related operations + - name: Profiles + description: User profile management + - name: Search + description: Search functionality across different entity types +paths: + /events/{id}/tags: + get: + tags: + - Events + - Tags + summary: Get event tags + operationId: getEventTags + parameters: + - $ref: '#/components/parameters/pathId' + responses: + '200': + description: Tags attached to the event + content: + application/json: + schema: + type: array + items: + $ref: '#/components/schemas/Tag' + '404': + description: Not found +components: + parameters: + pathId: + name: id + in: path + required: true + schema: + type: integer + schemas: + Tag: + type: object + properties: + id: + type: string + label: + type: string + nullable: true + slug: + type: string + nullable: true + forceShow: + type: boolean + nullable: true + publishedAt: + type: string + nullable: true + createdBy: + type: integer + nullable: true + updatedBy: + type: integer + nullable: true + createdAt: + type: string + format: date-time + nullable: true + updatedAt: + type: string + format: date-time + nullable: true + forceHide: + type: boolean + nullable: true + isCarousel: + type: boolean + nullable: true + +```` \ No newline at end of file diff --git a/PolymarketDocumentation-main/docs/api-reference/events/list-events-keyset-pagination.md b/PolymarketDocumentation-main/docs/api-reference/events/list-events-keyset-pagination.md new file mode 100644 index 00000000..e2e96447 --- /dev/null +++ b/PolymarketDocumentation-main/docs/api-reference/events/list-events-keyset-pagination.md @@ -0,0 +1,1471 @@ +> ## Documentation Index +> Fetch the complete documentation index at: https://docs.polymarket.com/llms.txt +> Use this file to discover all available pages before exploring further. + +# List events (keyset pagination) + +> Returns events using cursor-based (keyset) pagination for stable, efficient paging through large result sets. Use `next_cursor` from each response as `after_cursor` in the next request. The `offset` parameter is explicitly rejected; use `after_cursor` instead. + + + + +## OpenAPI + +````yaml /api-spec/gamma-openapi.yaml get /events/keyset +openapi: 3.0.3 +info: + title: Markets API + version: 1.0.0 + description: REST API specification for public endpoints used by the Markets service. +servers: + - url: https://gamma-api.polymarket.com + description: Polymarket Gamma API Production Server +security: [] +tags: + - name: Gamma Status + description: Gamma API status and health check + - name: Sports + description: Sports-related endpoints including teams and game data + - name: Tags + description: Tag management and related tag operations + - name: Events + description: Event management and event-related operations + - name: Markets + description: Market data and market-related operations + - name: Comments + description: Comment system and user interactions + - name: Series + description: Series management and related operations + - name: Profiles + description: User profile management + - name: Search + description: Search functionality across different entity types +paths: + /events/keyset: + get: + tags: + - Events + summary: List events (keyset pagination) + description: > + Returns events using cursor-based (keyset) pagination for stable, + efficient paging through large result sets. Use `next_cursor` from each + response as `after_cursor` in the next request. The `offset` parameter + is explicitly rejected; use `after_cursor` instead. + operationId: listEventsKeyset + parameters: + - name: limit + in: query + description: Maximum number of results to return (max 500) + schema: + type: integer + minimum: 1 + maximum: 500 + default: 20 + - name: order + in: query + description: Comma-separated list of JSON field names to order by + schema: + type: string + - name: ascending + in: query + description: Sort direction. Only used when order is set. + schema: + type: boolean + default: true + - name: after_cursor + in: query + description: Opaque cursor token from a previous response's next_cursor + schema: + type: string + - name: offset + in: query + description: Not allowed. Returns 422 if provided. + schema: + type: integer + - name: id + in: query + schema: + type: array + items: + type: integer + - name: slug + in: query + schema: + type: array + items: + type: string + - name: closed + in: query + schema: + type: boolean + - name: live + in: query + schema: + type: boolean + - name: featured + in: query + schema: + type: boolean + - name: cyom + in: query + schema: + type: boolean + - name: title_search + in: query + schema: + type: string + - name: liquidity_min + in: query + schema: + type: number + - name: liquidity_max + in: query + schema: + type: number + - name: volume_min + in: query + schema: + type: number + - name: volume_max + in: query + schema: + type: number + - name: start_date_min + in: query + schema: + type: string + format: date-time + - name: start_date_max + in: query + schema: + type: string + format: date-time + - name: end_date_min + in: query + schema: + type: string + format: date-time + - name: end_date_max + in: query + schema: + type: string + format: date-time + - name: start_time_min + in: query + schema: + type: string + format: date-time + - name: start_time_max + in: query + schema: + type: string + format: date-time + - name: tag_id + in: query + schema: + type: array + items: + type: integer + - name: tag_slug + in: query + schema: + type: string + - name: exclude_tag_id + in: query + description: Tag IDs to exclude. Cannot overlap with tag_id. + schema: + type: array + items: + type: integer + - name: related_tags + in: query + schema: + type: boolean + - name: tag_match + in: query + schema: + type: string + - name: series_id + in: query + schema: + type: array + items: + type: integer + - name: game_id + in: query + schema: + type: array + items: + type: integer + - name: event_date + in: query + schema: + type: string + format: date-time + - name: event_week + in: query + schema: + type: integer + - name: featured_order + in: query + schema: + type: boolean + - name: recurrence + in: query + schema: + type: string + - name: created_by + in: query + schema: + type: array + items: + type: string + - name: parent_event_id + in: query + schema: + type: integer + - name: include_children + in: query + schema: + type: boolean + - name: partner_slug + in: query + description: When set, external_partners are attached to matching events + schema: + type: string + - name: include_chat + in: query + description: When true, includes Chats and Series.Chats relations + schema: + type: boolean + - name: include_template + in: query + description: When true, includes Templates relation + schema: + type: boolean + - name: include_best_lines + in: query + description: When true, includes BestLines relation + schema: + type: boolean + - name: locale + in: query + schema: + type: string + responses: + '200': + description: > + Paginated list of events. Always includes Series, Tags, Markets, and + EventCreators relations. Chats/Series.Chats, Templates, and + BestLines are optional via their respective include_ flags. Nested + markets include clob_rewards and fee_schedule. Teams are enriched + automatically. external_partners attached only when partner_slug is + set. + content: + application/json: + schema: + $ref: '#/components/schemas/KeysetEventsResponse' + '422': + description: > + Validation error. Returned when offset is provided, cursor is + invalid, order fields are not valid, tag_id overlaps with + exclude_tag_id, invalid recurrence, or other filter validation + fails. + content: + application/json: + schema: + $ref: '#/components/schemas/ValidationError' + '500': + description: Internal server error (DB failures, cursor encode failures) + content: + application/json: + schema: + $ref: '#/components/schemas/InternalError' + '503': + description: Service unavailable when keyset pagination is not configured + content: + application/json: + schema: + $ref: '#/components/schemas/ServiceUnavailableError' +components: + schemas: + KeysetEventsResponse: + type: object + properties: + events: + type: array + description: Array of Event objects. Empty array if none found. + items: + $ref: '#/components/schemas/Event' + next_cursor: + type: string + description: > + Opaque cursor token for fetching the next page. Present only when + the number of returned events equals the effective limit. Omitted on + the last page. + ValidationError: + type: object + properties: + type: + type: string + example: validation error + error: + type: string + example: offset is not allowed on keyset endpoints + InternalError: + type: object + properties: + type: + type: string + example: internal error + error: + type: string + example: cannot get the information + ServiceUnavailableError: + type: object + properties: + type: + type: string + example: service unavailable + error: + type: string + example: keyset pagination is not configured + Event: + type: object + properties: + id: + type: string + ticker: + type: string + nullable: true + slug: + type: string + nullable: true + title: + type: string + nullable: true + subtitle: + type: string + nullable: true + description: + type: string + nullable: true + resolutionSource: + type: string + nullable: true + startDate: + type: string + format: date-time + nullable: true + creationDate: + type: string + format: date-time + nullable: true + endDate: + type: string + format: date-time + nullable: true + image: + type: string + nullable: true + icon: + type: string + nullable: true + active: + type: boolean + nullable: true + closed: + type: boolean + nullable: true + archived: + type: boolean + nullable: true + new: + type: boolean + nullable: true + featured: + type: boolean + nullable: true + restricted: + type: boolean + nullable: true + liquidity: + type: number + nullable: true + volume: + type: number + nullable: true + openInterest: + type: number + nullable: true + sortBy: + type: string + nullable: true + category: + type: string + nullable: true + subcategory: + type: string + nullable: true + isTemplate: + type: boolean + nullable: true + templateVariables: + type: string + nullable: true + published_at: + type: string + nullable: true + createdBy: + type: string + nullable: true + updatedBy: + type: string + nullable: true + createdAt: + type: string + format: date-time + nullable: true + updatedAt: + type: string + format: date-time + nullable: true + commentsEnabled: + type: boolean + nullable: true + competitive: + type: number + nullable: true + volume24hr: + type: number + nullable: true + volume1wk: + type: number + nullable: true + volume1mo: + type: number + nullable: true + volume1yr: + type: number + nullable: true + featuredImage: + type: string + nullable: true + disqusThread: + type: string + nullable: true + parentEvent: + type: string + nullable: true + enableOrderBook: + type: boolean + nullable: true + liquidityAmm: + type: number + nullable: true + liquidityClob: + type: number + nullable: true + negRisk: + type: boolean + nullable: true + negRiskMarketID: + type: string + nullable: true + negRiskFeeBips: + type: integer + nullable: true + commentCount: + type: integer + nullable: true + imageOptimized: + $ref: '#/components/schemas/ImageOptimization' + iconOptimized: + $ref: '#/components/schemas/ImageOptimization' + featuredImageOptimized: + $ref: '#/components/schemas/ImageOptimization' + subEvents: + type: array + items: + type: string + nullable: true + markets: + type: array + items: + $ref: '#/components/schemas/Market' + series: + type: array + items: + $ref: '#/components/schemas/Series' + categories: + type: array + items: + $ref: '#/components/schemas/Category' + collections: + type: array + items: + $ref: '#/components/schemas/Collection' + tags: + type: array + items: + $ref: '#/components/schemas/Tag' + cyom: + type: boolean + nullable: true + closedTime: + type: string + format: date-time + nullable: true + showAllOutcomes: + type: boolean + nullable: true + showMarketImages: + type: boolean + nullable: true + automaticallyResolved: + type: boolean + nullable: true + enableNegRisk: + type: boolean + nullable: true + automaticallyActive: + type: boolean + nullable: true + eventDate: + type: string + nullable: true + startTime: + type: string + format: date-time + nullable: true + eventWeek: + type: integer + nullable: true + seriesSlug: + type: string + nullable: true + score: + type: string + nullable: true + elapsed: + type: string + nullable: true + period: + type: string + nullable: true + live: + type: boolean + nullable: true + ended: + type: boolean + nullable: true + finishedTimestamp: + type: string + format: date-time + nullable: true + gmpChartMode: + type: string + nullable: true + eventCreators: + type: array + items: + $ref: '#/components/schemas/EventCreator' + tweetCount: + type: integer + nullable: true + chats: + type: array + items: + $ref: '#/components/schemas/Chat' + featuredOrder: + type: integer + nullable: true + estimateValue: + type: boolean + nullable: true + cantEstimate: + type: boolean + nullable: true + estimatedValue: + type: string + nullable: true + templates: + type: array + items: + $ref: '#/components/schemas/Template' + spreadsMainLine: + type: number + nullable: true + totalsMainLine: + type: number + nullable: true + carouselMap: + type: string + nullable: true + pendingDeployment: + type: boolean + nullable: true + deploying: + type: boolean + nullable: true + deployingTimestamp: + type: string + format: date-time + nullable: true + scheduledDeploymentTimestamp: + type: string + format: date-time + nullable: true + gameStatus: + type: string + nullable: true + ImageOptimization: + type: object + properties: + id: + type: string + imageUrlSource: + type: string + nullable: true + imageUrlOptimized: + type: string + nullable: true + imageSizeKbSource: + type: number + nullable: true + imageSizeKbOptimized: + type: number + nullable: true + imageOptimizedComplete: + type: boolean + nullable: true + imageOptimizedLastUpdated: + type: string + nullable: true + relID: + type: integer + nullable: true + field: + type: string + nullable: true + relname: + type: string + nullable: true + Market: + type: object + properties: + id: + type: string + question: + type: string + nullable: true + conditionId: + type: string + slug: + type: string + nullable: true + twitterCardImage: + type: string + nullable: true + resolutionSource: + type: string + nullable: true + endDate: + type: string + format: date-time + nullable: true + category: + type: string + nullable: true + ammType: + type: string + nullable: true + liquidity: + type: string + nullable: true + sponsorName: + type: string + nullable: true + sponsorImage: + type: string + nullable: true + startDate: + type: string + format: date-time + nullable: true + xAxisValue: + type: string + nullable: true + yAxisValue: + type: string + nullable: true + denominationToken: + type: string + nullable: true + fee: + type: string + nullable: true + image: + type: string + nullable: true + icon: + type: string + nullable: true + lowerBound: + type: string + nullable: true + upperBound: + type: string + nullable: true + description: + type: string + nullable: true + outcomes: + type: string + nullable: true + outcomePrices: + type: string + nullable: true + volume: + type: string + nullable: true + active: + type: boolean + nullable: true + marketType: + type: string + nullable: true + formatType: + type: string + nullable: true + lowerBoundDate: + type: string + nullable: true + upperBoundDate: + type: string + nullable: true + closed: + type: boolean + nullable: true + marketMakerAddress: + type: string + createdBy: + type: integer + nullable: true + updatedBy: + type: integer + nullable: true + createdAt: + type: string + format: date-time + nullable: true + updatedAt: + type: string + format: date-time + nullable: true + closedTime: + type: string + nullable: true + wideFormat: + type: boolean + nullable: true + new: + type: boolean + nullable: true + mailchimpTag: + type: string + nullable: true + featured: + type: boolean + nullable: true + archived: + type: boolean + nullable: true + resolvedBy: + type: string + nullable: true + restricted: + type: boolean + nullable: true + marketGroup: + type: integer + nullable: true + groupItemTitle: + type: string + nullable: true + groupItemThreshold: + type: string + nullable: true + questionID: + type: string + nullable: true + umaEndDate: + type: string + nullable: true + enableOrderBook: + type: boolean + nullable: true + orderPriceMinTickSize: + type: number + nullable: true + orderMinSize: + type: number + nullable: true + umaResolutionStatus: + type: string + nullable: true + curationOrder: + type: integer + nullable: true + volumeNum: + type: number + nullable: true + liquidityNum: + type: number + nullable: true + endDateIso: + type: string + nullable: true + startDateIso: + type: string + nullable: true + umaEndDateIso: + type: string + nullable: true + hasReviewedDates: + type: boolean + nullable: true + readyForCron: + type: boolean + nullable: true + commentsEnabled: + type: boolean + nullable: true + volume24hr: + type: number + nullable: true + volume1wk: + type: number + nullable: true + volume1mo: + type: number + nullable: true + volume1yr: + type: number + nullable: true + gameStartTime: + type: string + nullable: true + secondsDelay: + type: integer + nullable: true + clobTokenIds: + type: string + nullable: true + disqusThread: + type: string + nullable: true + shortOutcomes: + type: string + nullable: true + teamAID: + type: string + nullable: true + teamBID: + type: string + nullable: true + umaBond: + type: string + nullable: true + umaReward: + type: string + nullable: true + fpmmLive: + type: boolean + nullable: true + volume24hrAmm: + type: number + nullable: true + volume1wkAmm: + type: number + nullable: true + volume1moAmm: + type: number + nullable: true + volume1yrAmm: + type: number + nullable: true + volume24hrClob: + type: number + nullable: true + volume1wkClob: + type: number + nullable: true + volume1moClob: + type: number + nullable: true + volume1yrClob: + type: number + nullable: true + volumeAmm: + type: number + nullable: true + volumeClob: + type: number + nullable: true + liquidityAmm: + type: number + nullable: true + liquidityClob: + type: number + nullable: true + makerBaseFee: + type: integer + nullable: true + takerBaseFee: + type: integer + nullable: true + customLiveness: + type: integer + nullable: true + acceptingOrders: + type: boolean + nullable: true + notificationsEnabled: + type: boolean + nullable: true + score: + type: integer + nullable: true + imageOptimized: + $ref: '#/components/schemas/ImageOptimization' + iconOptimized: + $ref: '#/components/schemas/ImageOptimization' + events: + type: array + items: + $ref: '#/components/schemas/Event' + categories: + type: array + items: + $ref: '#/components/schemas/Category' + tags: + type: array + items: + $ref: '#/components/schemas/Tag' + creator: + type: string + nullable: true + ready: + type: boolean + nullable: true + funded: + type: boolean + nullable: true + pastSlugs: + type: string + nullable: true + readyTimestamp: + type: string + format: date-time + nullable: true + fundedTimestamp: + type: string + format: date-time + nullable: true + acceptingOrdersTimestamp: + type: string + format: date-time + nullable: true + competitive: + type: number + nullable: true + rewardsMinSize: + type: number + nullable: true + rewardsMaxSpread: + type: number + nullable: true + spread: + type: number + nullable: true + automaticallyResolved: + type: boolean + nullable: true + oneDayPriceChange: + type: number + nullable: true + oneHourPriceChange: + type: number + nullable: true + oneWeekPriceChange: + type: number + nullable: true + oneMonthPriceChange: + type: number + nullable: true + oneYearPriceChange: + type: number + nullable: true + lastTradePrice: + type: number + nullable: true + bestBid: + type: number + nullable: true + bestAsk: + type: number + nullable: true + automaticallyActive: + type: boolean + nullable: true + clearBookOnStart: + type: boolean + nullable: true + chartColor: + type: string + nullable: true + seriesColor: + type: string + nullable: true + showGmpSeries: + type: boolean + nullable: true + showGmpOutcome: + type: boolean + nullable: true + manualActivation: + type: boolean + nullable: true + negRiskOther: + type: boolean + nullable: true + gameId: + type: string + nullable: true + groupItemRange: + type: string + nullable: true + sportsMarketType: + type: string + nullable: true + line: + type: number + nullable: true + umaResolutionStatuses: + type: string + nullable: true + pendingDeployment: + type: boolean + nullable: true + deploying: + type: boolean + nullable: true + deployingTimestamp: + type: string + format: date-time + nullable: true + scheduledDeploymentTimestamp: + type: string + format: date-time + nullable: true + rfqEnabled: + type: boolean + nullable: true + eventStartTime: + type: string + format: date-time + nullable: true + feesEnabled: + type: boolean + nullable: true + feeSchedule: + $ref: '#/components/schemas/FeeSchedule' + Series: + type: object + properties: + id: + type: string + ticker: + type: string + nullable: true + slug: + type: string + nullable: true + title: + type: string + nullable: true + subtitle: + type: string + nullable: true + seriesType: + type: string + nullable: true + recurrence: + type: string + nullable: true + description: + type: string + nullable: true + image: + type: string + nullable: true + icon: + type: string + nullable: true + layout: + type: string + nullable: true + active: + type: boolean + nullable: true + closed: + type: boolean + nullable: true + archived: + type: boolean + nullable: true + new: + type: boolean + nullable: true + featured: + type: boolean + nullable: true + restricted: + type: boolean + nullable: true + isTemplate: + type: boolean + nullable: true + templateVariables: + type: boolean + nullable: true + publishedAt: + type: string + nullable: true + createdBy: + type: string + nullable: true + updatedBy: + type: string + nullable: true + createdAt: + type: string + format: date-time + nullable: true + updatedAt: + type: string + format: date-time + nullable: true + commentsEnabled: + type: boolean + nullable: true + competitive: + type: string + nullable: true + volume24hr: + type: number + nullable: true + volume: + type: number + nullable: true + liquidity: + type: number + nullable: true + startDate: + type: string + format: date-time + nullable: true + pythTokenID: + type: string + nullable: true + cgAssetName: + type: string + nullable: true + score: + type: integer + nullable: true + events: + type: array + items: + $ref: '#/components/schemas/Event' + collections: + type: array + items: + $ref: '#/components/schemas/Collection' + categories: + type: array + items: + $ref: '#/components/schemas/Category' + tags: + type: array + items: + $ref: '#/components/schemas/Tag' + commentCount: + type: integer + nullable: true + chats: + type: array + items: + $ref: '#/components/schemas/Chat' + Category: + type: object + properties: + id: + type: string + label: + type: string + nullable: true + parentCategory: + type: string + nullable: true + slug: + type: string + nullable: true + publishedAt: + type: string + nullable: true + createdBy: + type: string + nullable: true + updatedBy: + type: string + nullable: true + createdAt: + type: string + format: date-time + nullable: true + updatedAt: + type: string + format: date-time + nullable: true + Collection: + type: object + properties: + id: + type: string + ticker: + type: string + nullable: true + slug: + type: string + nullable: true + title: + type: string + nullable: true + subtitle: + type: string + nullable: true + collectionType: + type: string + nullable: true + description: + type: string + nullable: true + tags: + type: string + nullable: true + image: + type: string + nullable: true + icon: + type: string + nullable: true + headerImage: + type: string + nullable: true + layout: + type: string + nullable: true + active: + type: boolean + nullable: true + closed: + type: boolean + nullable: true + archived: + type: boolean + nullable: true + new: + type: boolean + nullable: true + featured: + type: boolean + nullable: true + restricted: + type: boolean + nullable: true + isTemplate: + type: boolean + nullable: true + templateVariables: + type: string + nullable: true + publishedAt: + type: string + nullable: true + createdBy: + type: string + nullable: true + updatedBy: + type: string + nullable: true + createdAt: + type: string + format: date-time + nullable: true + updatedAt: + type: string + format: date-time + nullable: true + commentsEnabled: + type: boolean + nullable: true + imageOptimized: + $ref: '#/components/schemas/ImageOptimization' + iconOptimized: + $ref: '#/components/schemas/ImageOptimization' + headerImageOptimized: + $ref: '#/components/schemas/ImageOptimization' + Tag: + type: object + properties: + id: + type: string + label: + type: string + nullable: true + slug: + type: string + nullable: true + forceShow: + type: boolean + nullable: true + publishedAt: + type: string + nullable: true + createdBy: + type: integer + nullable: true + updatedBy: + type: integer + nullable: true + createdAt: + type: string + format: date-time + nullable: true + updatedAt: + type: string + format: date-time + nullable: true + forceHide: + type: boolean + nullable: true + isCarousel: + type: boolean + nullable: true + EventCreator: + type: object + properties: + id: + type: string + creatorName: + type: string + nullable: true + creatorHandle: + type: string + nullable: true + creatorUrl: + type: string + nullable: true + creatorImage: + type: string + nullable: true + createdAt: + type: string + format: date-time + nullable: true + updatedAt: + type: string + format: date-time + nullable: true + Chat: + type: object + properties: + id: + type: string + channelId: + type: string + nullable: true + channelName: + type: string + nullable: true + channelImage: + type: string + nullable: true + live: + type: boolean + nullable: true + startTime: + type: string + format: date-time + nullable: true + endTime: + type: string + format: date-time + nullable: true + Template: + type: object + properties: + id: + type: string + eventTitle: + type: string + nullable: true + eventSlug: + type: string + nullable: true + eventImage: + type: string + nullable: true + marketTitle: + type: string + nullable: true + description: + type: string + nullable: true + resolutionSource: + type: string + nullable: true + negRisk: + type: boolean + nullable: true + sortBy: + type: string + nullable: true + showMarketImages: + type: boolean + nullable: true + seriesSlug: + type: string + nullable: true + outcomes: + type: string + nullable: true + FeeSchedule: + type: object + properties: + exponent: + type: number + nullable: true + rate: + type: number + nullable: true + takerOnly: + type: boolean + nullable: true + rebateRate: + type: number + nullable: true + +```` \ No newline at end of file diff --git a/PolymarketDocumentation-main/docs/api-reference/events/list-events.md b/PolymarketDocumentation-main/docs/api-reference/events/list-events.md new file mode 100644 index 00000000..ec3c8887 --- /dev/null +++ b/PolymarketDocumentation-main/docs/api-reference/events/list-events.md @@ -0,0 +1,1323 @@ +> ## Documentation Index +> Fetch the complete documentation index at: https://docs.polymarket.com/llms.txt +> Use this file to discover all available pages before exploring further. + +# List events + + + +## OpenAPI + +````yaml /api-spec/gamma-openapi.yaml get /events +openapi: 3.0.3 +info: + title: Markets API + version: 1.0.0 + description: REST API specification for public endpoints used by the Markets service. +servers: + - url: https://gamma-api.polymarket.com + description: Polymarket Gamma API Production Server +security: [] +tags: + - name: Gamma Status + description: Gamma API status and health check + - name: Sports + description: Sports-related endpoints including teams and game data + - name: Tags + description: Tag management and related tag operations + - name: Events + description: Event management and event-related operations + - name: Markets + description: Market data and market-related operations + - name: Comments + description: Comment system and user interactions + - name: Series + description: Series management and related operations + - name: Profiles + description: User profile management + - name: Search + description: Search functionality across different entity types +paths: + /events: + get: + tags: + - Events + summary: List events + operationId: listEvents + parameters: + - $ref: '#/components/parameters/limit' + - $ref: '#/components/parameters/offset' + - $ref: '#/components/parameters/order' + - $ref: '#/components/parameters/ascending' + - name: id + in: query + schema: + type: array + items: + type: integer + - name: tag_id + in: query + schema: + type: integer + - name: exclude_tag_id + in: query + schema: + type: array + items: + type: integer + - name: slug + in: query + schema: + type: array + items: + type: string + - name: tag_slug + in: query + schema: + type: string + - name: related_tags + in: query + schema: + type: boolean + - name: active + in: query + schema: + type: boolean + - name: archived + in: query + schema: + type: boolean + - name: featured + in: query + schema: + type: boolean + - name: cyom + in: query + schema: + type: boolean + - name: include_chat + in: query + schema: + type: boolean + - name: include_template + in: query + schema: + type: boolean + - name: recurrence + in: query + schema: + type: string + - name: closed + in: query + schema: + type: boolean + - name: liquidity_min + in: query + schema: + type: number + - name: liquidity_max + in: query + schema: + type: number + - name: volume_min + in: query + schema: + type: number + - name: volume_max + in: query + schema: + type: number + - name: start_date_min + in: query + schema: + type: string + format: date-time + - name: start_date_max + in: query + schema: + type: string + format: date-time + - name: end_date_min + in: query + schema: + type: string + format: date-time + - name: end_date_max + in: query + schema: + type: string + format: date-time + responses: + '200': + description: List of events + content: + application/json: + schema: + type: array + items: + $ref: '#/components/schemas/Event' +components: + parameters: + limit: + name: limit + in: query + schema: + type: integer + minimum: 0 + offset: + name: offset + in: query + schema: + type: integer + minimum: 0 + order: + name: order + in: query + schema: + type: string + description: Comma-separated list of fields to order by + ascending: + name: ascending + in: query + schema: + type: boolean + schemas: + Event: + type: object + properties: + id: + type: string + ticker: + type: string + nullable: true + slug: + type: string + nullable: true + title: + type: string + nullable: true + subtitle: + type: string + nullable: true + description: + type: string + nullable: true + resolutionSource: + type: string + nullable: true + startDate: + type: string + format: date-time + nullable: true + creationDate: + type: string + format: date-time + nullable: true + endDate: + type: string + format: date-time + nullable: true + image: + type: string + nullable: true + icon: + type: string + nullable: true + active: + type: boolean + nullable: true + closed: + type: boolean + nullable: true + archived: + type: boolean + nullable: true + new: + type: boolean + nullable: true + featured: + type: boolean + nullable: true + restricted: + type: boolean + nullable: true + liquidity: + type: number + nullable: true + volume: + type: number + nullable: true + openInterest: + type: number + nullable: true + sortBy: + type: string + nullable: true + category: + type: string + nullable: true + subcategory: + type: string + nullable: true + isTemplate: + type: boolean + nullable: true + templateVariables: + type: string + nullable: true + published_at: + type: string + nullable: true + createdBy: + type: string + nullable: true + updatedBy: + type: string + nullable: true + createdAt: + type: string + format: date-time + nullable: true + updatedAt: + type: string + format: date-time + nullable: true + commentsEnabled: + type: boolean + nullable: true + competitive: + type: number + nullable: true + volume24hr: + type: number + nullable: true + volume1wk: + type: number + nullable: true + volume1mo: + type: number + nullable: true + volume1yr: + type: number + nullable: true + featuredImage: + type: string + nullable: true + disqusThread: + type: string + nullable: true + parentEvent: + type: string + nullable: true + enableOrderBook: + type: boolean + nullable: true + liquidityAmm: + type: number + nullable: true + liquidityClob: + type: number + nullable: true + negRisk: + type: boolean + nullable: true + negRiskMarketID: + type: string + nullable: true + negRiskFeeBips: + type: integer + nullable: true + commentCount: + type: integer + nullable: true + imageOptimized: + $ref: '#/components/schemas/ImageOptimization' + iconOptimized: + $ref: '#/components/schemas/ImageOptimization' + featuredImageOptimized: + $ref: '#/components/schemas/ImageOptimization' + subEvents: + type: array + items: + type: string + nullable: true + markets: + type: array + items: + $ref: '#/components/schemas/Market' + series: + type: array + items: + $ref: '#/components/schemas/Series' + categories: + type: array + items: + $ref: '#/components/schemas/Category' + collections: + type: array + items: + $ref: '#/components/schemas/Collection' + tags: + type: array + items: + $ref: '#/components/schemas/Tag' + cyom: + type: boolean + nullable: true + closedTime: + type: string + format: date-time + nullable: true + showAllOutcomes: + type: boolean + nullable: true + showMarketImages: + type: boolean + nullable: true + automaticallyResolved: + type: boolean + nullable: true + enableNegRisk: + type: boolean + nullable: true + automaticallyActive: + type: boolean + nullable: true + eventDate: + type: string + nullable: true + startTime: + type: string + format: date-time + nullable: true + eventWeek: + type: integer + nullable: true + seriesSlug: + type: string + nullable: true + score: + type: string + nullable: true + elapsed: + type: string + nullable: true + period: + type: string + nullable: true + live: + type: boolean + nullable: true + ended: + type: boolean + nullable: true + finishedTimestamp: + type: string + format: date-time + nullable: true + gmpChartMode: + type: string + nullable: true + eventCreators: + type: array + items: + $ref: '#/components/schemas/EventCreator' + tweetCount: + type: integer + nullable: true + chats: + type: array + items: + $ref: '#/components/schemas/Chat' + featuredOrder: + type: integer + nullable: true + estimateValue: + type: boolean + nullable: true + cantEstimate: + type: boolean + nullable: true + estimatedValue: + type: string + nullable: true + templates: + type: array + items: + $ref: '#/components/schemas/Template' + spreadsMainLine: + type: number + nullable: true + totalsMainLine: + type: number + nullable: true + carouselMap: + type: string + nullable: true + pendingDeployment: + type: boolean + nullable: true + deploying: + type: boolean + nullable: true + deployingTimestamp: + type: string + format: date-time + nullable: true + scheduledDeploymentTimestamp: + type: string + format: date-time + nullable: true + gameStatus: + type: string + nullable: true + ImageOptimization: + type: object + properties: + id: + type: string + imageUrlSource: + type: string + nullable: true + imageUrlOptimized: + type: string + nullable: true + imageSizeKbSource: + type: number + nullable: true + imageSizeKbOptimized: + type: number + nullable: true + imageOptimizedComplete: + type: boolean + nullable: true + imageOptimizedLastUpdated: + type: string + nullable: true + relID: + type: integer + nullable: true + field: + type: string + nullable: true + relname: + type: string + nullable: true + Market: + type: object + properties: + id: + type: string + question: + type: string + nullable: true + conditionId: + type: string + slug: + type: string + nullable: true + twitterCardImage: + type: string + nullable: true + resolutionSource: + type: string + nullable: true + endDate: + type: string + format: date-time + nullable: true + category: + type: string + nullable: true + ammType: + type: string + nullable: true + liquidity: + type: string + nullable: true + sponsorName: + type: string + nullable: true + sponsorImage: + type: string + nullable: true + startDate: + type: string + format: date-time + nullable: true + xAxisValue: + type: string + nullable: true + yAxisValue: + type: string + nullable: true + denominationToken: + type: string + nullable: true + fee: + type: string + nullable: true + image: + type: string + nullable: true + icon: + type: string + nullable: true + lowerBound: + type: string + nullable: true + upperBound: + type: string + nullable: true + description: + type: string + nullable: true + outcomes: + type: string + nullable: true + outcomePrices: + type: string + nullable: true + volume: + type: string + nullable: true + active: + type: boolean + nullable: true + marketType: + type: string + nullable: true + formatType: + type: string + nullable: true + lowerBoundDate: + type: string + nullable: true + upperBoundDate: + type: string + nullable: true + closed: + type: boolean + nullable: true + marketMakerAddress: + type: string + createdBy: + type: integer + nullable: true + updatedBy: + type: integer + nullable: true + createdAt: + type: string + format: date-time + nullable: true + updatedAt: + type: string + format: date-time + nullable: true + closedTime: + type: string + nullable: true + wideFormat: + type: boolean + nullable: true + new: + type: boolean + nullable: true + mailchimpTag: + type: string + nullable: true + featured: + type: boolean + nullable: true + archived: + type: boolean + nullable: true + resolvedBy: + type: string + nullable: true + restricted: + type: boolean + nullable: true + marketGroup: + type: integer + nullable: true + groupItemTitle: + type: string + nullable: true + groupItemThreshold: + type: string + nullable: true + questionID: + type: string + nullable: true + umaEndDate: + type: string + nullable: true + enableOrderBook: + type: boolean + nullable: true + orderPriceMinTickSize: + type: number + nullable: true + orderMinSize: + type: number + nullable: true + umaResolutionStatus: + type: string + nullable: true + curationOrder: + type: integer + nullable: true + volumeNum: + type: number + nullable: true + liquidityNum: + type: number + nullable: true + endDateIso: + type: string + nullable: true + startDateIso: + type: string + nullable: true + umaEndDateIso: + type: string + nullable: true + hasReviewedDates: + type: boolean + nullable: true + readyForCron: + type: boolean + nullable: true + commentsEnabled: + type: boolean + nullable: true + volume24hr: + type: number + nullable: true + volume1wk: + type: number + nullable: true + volume1mo: + type: number + nullable: true + volume1yr: + type: number + nullable: true + gameStartTime: + type: string + nullable: true + secondsDelay: + type: integer + nullable: true + clobTokenIds: + type: string + nullable: true + disqusThread: + type: string + nullable: true + shortOutcomes: + type: string + nullable: true + teamAID: + type: string + nullable: true + teamBID: + type: string + nullable: true + umaBond: + type: string + nullable: true + umaReward: + type: string + nullable: true + fpmmLive: + type: boolean + nullable: true + volume24hrAmm: + type: number + nullable: true + volume1wkAmm: + type: number + nullable: true + volume1moAmm: + type: number + nullable: true + volume1yrAmm: + type: number + nullable: true + volume24hrClob: + type: number + nullable: true + volume1wkClob: + type: number + nullable: true + volume1moClob: + type: number + nullable: true + volume1yrClob: + type: number + nullable: true + volumeAmm: + type: number + nullable: true + volumeClob: + type: number + nullable: true + liquidityAmm: + type: number + nullable: true + liquidityClob: + type: number + nullable: true + makerBaseFee: + type: integer + nullable: true + takerBaseFee: + type: integer + nullable: true + customLiveness: + type: integer + nullable: true + acceptingOrders: + type: boolean + nullable: true + notificationsEnabled: + type: boolean + nullable: true + score: + type: integer + nullable: true + imageOptimized: + $ref: '#/components/schemas/ImageOptimization' + iconOptimized: + $ref: '#/components/schemas/ImageOptimization' + events: + type: array + items: + $ref: '#/components/schemas/Event' + categories: + type: array + items: + $ref: '#/components/schemas/Category' + tags: + type: array + items: + $ref: '#/components/schemas/Tag' + creator: + type: string + nullable: true + ready: + type: boolean + nullable: true + funded: + type: boolean + nullable: true + pastSlugs: + type: string + nullable: true + readyTimestamp: + type: string + format: date-time + nullable: true + fundedTimestamp: + type: string + format: date-time + nullable: true + acceptingOrdersTimestamp: + type: string + format: date-time + nullable: true + competitive: + type: number + nullable: true + rewardsMinSize: + type: number + nullable: true + rewardsMaxSpread: + type: number + nullable: true + spread: + type: number + nullable: true + automaticallyResolved: + type: boolean + nullable: true + oneDayPriceChange: + type: number + nullable: true + oneHourPriceChange: + type: number + nullable: true + oneWeekPriceChange: + type: number + nullable: true + oneMonthPriceChange: + type: number + nullable: true + oneYearPriceChange: + type: number + nullable: true + lastTradePrice: + type: number + nullable: true + bestBid: + type: number + nullable: true + bestAsk: + type: number + nullable: true + automaticallyActive: + type: boolean + nullable: true + clearBookOnStart: + type: boolean + nullable: true + chartColor: + type: string + nullable: true + seriesColor: + type: string + nullable: true + showGmpSeries: + type: boolean + nullable: true + showGmpOutcome: + type: boolean + nullable: true + manualActivation: + type: boolean + nullable: true + negRiskOther: + type: boolean + nullable: true + gameId: + type: string + nullable: true + groupItemRange: + type: string + nullable: true + sportsMarketType: + type: string + nullable: true + line: + type: number + nullable: true + umaResolutionStatuses: + type: string + nullable: true + pendingDeployment: + type: boolean + nullable: true + deploying: + type: boolean + nullable: true + deployingTimestamp: + type: string + format: date-time + nullable: true + scheduledDeploymentTimestamp: + type: string + format: date-time + nullable: true + rfqEnabled: + type: boolean + nullable: true + eventStartTime: + type: string + format: date-time + nullable: true + feesEnabled: + type: boolean + nullable: true + feeSchedule: + $ref: '#/components/schemas/FeeSchedule' + Series: + type: object + properties: + id: + type: string + ticker: + type: string + nullable: true + slug: + type: string + nullable: true + title: + type: string + nullable: true + subtitle: + type: string + nullable: true + seriesType: + type: string + nullable: true + recurrence: + type: string + nullable: true + description: + type: string + nullable: true + image: + type: string + nullable: true + icon: + type: string + nullable: true + layout: + type: string + nullable: true + active: + type: boolean + nullable: true + closed: + type: boolean + nullable: true + archived: + type: boolean + nullable: true + new: + type: boolean + nullable: true + featured: + type: boolean + nullable: true + restricted: + type: boolean + nullable: true + isTemplate: + type: boolean + nullable: true + templateVariables: + type: boolean + nullable: true + publishedAt: + type: string + nullable: true + createdBy: + type: string + nullable: true + updatedBy: + type: string + nullable: true + createdAt: + type: string + format: date-time + nullable: true + updatedAt: + type: string + format: date-time + nullable: true + commentsEnabled: + type: boolean + nullable: true + competitive: + type: string + nullable: true + volume24hr: + type: number + nullable: true + volume: + type: number + nullable: true + liquidity: + type: number + nullable: true + startDate: + type: string + format: date-time + nullable: true + pythTokenID: + type: string + nullable: true + cgAssetName: + type: string + nullable: true + score: + type: integer + nullable: true + events: + type: array + items: + $ref: '#/components/schemas/Event' + collections: + type: array + items: + $ref: '#/components/schemas/Collection' + categories: + type: array + items: + $ref: '#/components/schemas/Category' + tags: + type: array + items: + $ref: '#/components/schemas/Tag' + commentCount: + type: integer + nullable: true + chats: + type: array + items: + $ref: '#/components/schemas/Chat' + Category: + type: object + properties: + id: + type: string + label: + type: string + nullable: true + parentCategory: + type: string + nullable: true + slug: + type: string + nullable: true + publishedAt: + type: string + nullable: true + createdBy: + type: string + nullable: true + updatedBy: + type: string + nullable: true + createdAt: + type: string + format: date-time + nullable: true + updatedAt: + type: string + format: date-time + nullable: true + Collection: + type: object + properties: + id: + type: string + ticker: + type: string + nullable: true + slug: + type: string + nullable: true + title: + type: string + nullable: true + subtitle: + type: string + nullable: true + collectionType: + type: string + nullable: true + description: + type: string + nullable: true + tags: + type: string + nullable: true + image: + type: string + nullable: true + icon: + type: string + nullable: true + headerImage: + type: string + nullable: true + layout: + type: string + nullable: true + active: + type: boolean + nullable: true + closed: + type: boolean + nullable: true + archived: + type: boolean + nullable: true + new: + type: boolean + nullable: true + featured: + type: boolean + nullable: true + restricted: + type: boolean + nullable: true + isTemplate: + type: boolean + nullable: true + templateVariables: + type: string + nullable: true + publishedAt: + type: string + nullable: true + createdBy: + type: string + nullable: true + updatedBy: + type: string + nullable: true + createdAt: + type: string + format: date-time + nullable: true + updatedAt: + type: string + format: date-time + nullable: true + commentsEnabled: + type: boolean + nullable: true + imageOptimized: + $ref: '#/components/schemas/ImageOptimization' + iconOptimized: + $ref: '#/components/schemas/ImageOptimization' + headerImageOptimized: + $ref: '#/components/schemas/ImageOptimization' + Tag: + type: object + properties: + id: + type: string + label: + type: string + nullable: true + slug: + type: string + nullable: true + forceShow: + type: boolean + nullable: true + publishedAt: + type: string + nullable: true + createdBy: + type: integer + nullable: true + updatedBy: + type: integer + nullable: true + createdAt: + type: string + format: date-time + nullable: true + updatedAt: + type: string + format: date-time + nullable: true + forceHide: + type: boolean + nullable: true + isCarousel: + type: boolean + nullable: true + EventCreator: + type: object + properties: + id: + type: string + creatorName: + type: string + nullable: true + creatorHandle: + type: string + nullable: true + creatorUrl: + type: string + nullable: true + creatorImage: + type: string + nullable: true + createdAt: + type: string + format: date-time + nullable: true + updatedAt: + type: string + format: date-time + nullable: true + Chat: + type: object + properties: + id: + type: string + channelId: + type: string + nullable: true + channelName: + type: string + nullable: true + channelImage: + type: string + nullable: true + live: + type: boolean + nullable: true + startTime: + type: string + format: date-time + nullable: true + endTime: + type: string + format: date-time + nullable: true + Template: + type: object + properties: + id: + type: string + eventTitle: + type: string + nullable: true + eventSlug: + type: string + nullable: true + eventImage: + type: string + nullable: true + marketTitle: + type: string + nullable: true + description: + type: string + nullable: true + resolutionSource: + type: string + nullable: true + negRisk: + type: boolean + nullable: true + sortBy: + type: string + nullable: true + showMarketImages: + type: boolean + nullable: true + seriesSlug: + type: string + nullable: true + outcomes: + type: string + nullable: true + FeeSchedule: + type: object + properties: + exponent: + type: number + nullable: true + rate: + type: number + nullable: true + takerOnly: + type: boolean + nullable: true + rebateRate: + type: number + nullable: true + +```` \ No newline at end of file diff --git a/PolymarketDocumentation-main/docs/api-reference/geoblock.md b/PolymarketDocumentation-main/docs/api-reference/geoblock.md new file mode 100644 index 00000000..f94e30f0 --- /dev/null +++ b/PolymarketDocumentation-main/docs/api-reference/geoblock.md @@ -0,0 +1,233 @@ +> ## Documentation Index +> Fetch the complete documentation index at: https://docs.polymarket.com/llms.txt +> Use this file to discover all available pages before exploring further. + +# Geographic Restrictions + +> Check geographic restrictions before placing orders on the Polymarket API + +Polymarket restricts order placement from certain geographic locations due to regulatory requirements and compliance with international sanctions. Before placing orders, builders should verify the location. + + + Orders submitted from blocked regions will be rejected. Implement geoblock + checks in your application to provide users with appropriate feedback before + they attempt to trade. + + +*** + +## Geoblock Endpoint + +Check the geographic eligibility of the requesting IP address: + +```bash theme={null} +GET https://polymarket.com/api/geoblock +``` + +This endpoint is on `polymarket.com`, not the API servers. + +### Response + +```json theme={null} +{ + "blocked": true, + "ip": "203.0.113.42", + "country": "US", + "region": "NY" +} +``` + +| Field | Type | Description | +| --------- | ------- | ----------------------------------------------- | +| `blocked` | boolean | Whether the user is blocked from placing orders | +| `ip` | string | Detected IP address | +| `country` | string | ISO 3166-1 alpha-2 country code | +| `region` | string | Region/state code | + +*** + +## Restricted Jurisdictions + +Restrictions fall into three groups. **Block completely** means no new orders and no closing of existing positions. **Close-only** means users can close existing positions but cannot open new ones. Each group notes whether it applies on the frontend, the API, or both. Codes are ISO 3166-1 alpha-2 for countries and ISO 3166-2 for sub-national regions. + +### OFAC-Sanctioned Jurisdictions (Block Completely) + +Blocked on both the frontend and the API. No new orders, and existing positions cannot be closed. + +| Jurisdiction | Code | +| ----------------- | ----- | +| Iran | IR | +| Syria | SY | +| Cuba | CU | +| North Korea | KP | +| Ukraine — Crimea | UA-43 | +| Ukraine — Donetsk | UA-14 | +| Ukraine — Luhansk | UA-09 | + +### Regulatory-Restricted Jurisdictions (Close-Only on Frontend and API) + +Users can close existing positions but cannot open new ones, on both the frontend and the API. + +| Jurisdiction | Code | +| ------------------------------------ | ----- | +| Australia | AU | +| Belarus | BY | +| Belgium | BE | +| Burundi | BI | +| Brazil | BR | +| Canada — British Columbia | CA-BC | +| Canada — Ontario | CA-ON | +| Canada — Alberta | CA-AB | +| Canada — Quebec | CA-QC | +| Central African Republic | CF | +| Congo (Kinshasa) | CD | +| Ethiopia | ET | +| France | FR | +| Germany | DE | +| Iraq | IQ | +| Italy | IT | +| Lebanon | LB | +| Libya | LY | +| Myanmar | MM | +| Nicaragua | NI | +| North Korea | KP | +| Poland | PL | +| Russia | RU | +| Singapore | SG | +| Somalia | SO | +| Slovakia | SK | +| South Sudan | SS | +| Sudan | SD | +| Taiwan | TW | +| Thailand | TH | +| United Kingdom | GB | +| United States | US | +| United States Minor Outlying Islands | UM | +| Venezuela | VE | +| Yemen | YE | +| Zimbabwe | ZW | + +### Regulatory-Restricted Jurisdictions (Close-Only on Frontend) + +Close-only on the Polymarket frontend; the API itself is not restricted. + +| Jurisdiction | Code | +| ------------------- | ---- | +| Japan | JP | +| Netherlands | NL | +| Malta (Sports Only) | MT | + +*** + +## Blocking Logic + +The geoblocking system includes: + +1. **OFAC-Sanctioned Countries**: Countries sanctioned by the U.S. Office of Foreign Assets Control (OFAC) +2. **Additional Regulatory Restrictions**: Countries added for specific regulatory compliance reasons + +*** + +## Server Infrastructure + +* **Primary Servers**: eu-west-2 +* **Closest Non-Georestricted Region**: eu-west-1 + + + **Direct co-location available.** Users who complete the [KYC/KYB + form](https://docs.google.com/forms/d/e/1FAIpQLSfY-3Dl3yxq8HKFjFad8YzKZmm0k3Gdg29HD6gL-K-AmI6KXw/viewform) can get access to co-locate + directly in `eu-west-2` for the lowest possible latency to Polymarket's + primary servers. + + +*** + +## Usage Examples + + + + ```typescript theme={null} + interface GeoblockResponse { + blocked: boolean; + ip: string; + country: string; + region: string; + } + + async function checkGeoblock(): Promise { + const response = await fetch("https://polymarket.com/api/geoblock"); + return response.json(); + } + + // Usage + const geo = await checkGeoblock(); + + if (geo.blocked) { + console.log(`Trading not available in ${geo.country}`); + } else { + console.log("Trading available"); + } + ``` + + + + ```python theme={null} + import requests + + def check_geoblock() -> dict: + response = requests.get("https://polymarket.com/api/geoblock") + return response.json() + + # Usage + geo = check_geoblock() + + if geo["blocked"]: + print(f"Trading not available in {geo['country']}") + else: + print("Trading available") + ``` + + + + ```rust theme={null} + use polymarket_client_sdk_v2::clob::{Client, Config}; + + let client = Client::new("https://clob.polymarket.com", Config::default())?; + let geo = client.check_geoblock().await?; + + if geo.blocked { + println!("Trading not available in {}", geo.country); + } else { + println!("Trading available"); + } + ``` + + + +*** + +## Why These Restrictions + +Geographic restrictions are implemented to ensure compliance with: + +* International sanctions and embargoes +* Local financial regulations +* Gambling and prediction market laws +* Anti-money laundering (AML) requirements +* Know Your Customer (KYC) regulations + +If you believe you are incorrectly restricted or have questions about geographic availability, please contact [Polymarket Support](https://polymarket.com/support). + +*** + +## Next Steps + + + + Learn how to authenticate trading requests. + + + + Start placing orders (from eligible regions). + + diff --git a/PolymarketDocumentation-main/docs/api-reference/get-account-limits.md b/PolymarketDocumentation-main/docs/api-reference/get-account-limits.md new file mode 100644 index 00000000..f48086c1 --- /dev/null +++ b/PolymarketDocumentation-main/docs/api-reference/get-account-limits.md @@ -0,0 +1,242 @@ +> ## Documentation Index +> Fetch the complete documentation index at: https://docs.polymarket.com/llms.txt +> Use this file to discover all available pages before exploring further. + +# Get Account Limits + +> Get the authenticated account's effective rate-limit allowances for its current +volume-based tier: order-action rate, open-order cap, and the display-only +messages-per-minute figure. `open_orders` reflects the account's current live +open-order count; the rate-usage counters (`actions_per_minute`, +`actions_burst`, and `reset`) are not tracked here and are reported as 0. + + +Request Weight: **2** + + +## OpenAPI + +````yaml /api-spec/perps-openapi.json get /v1/account/limits +openapi: 3.0.3 +info: + title: Polymarket Perps HTTP API + version: 1.0.0 + description: HTTP API for Polymarket perpetual trading system. + license: + name: Apache 2.0 + url: https://www.apache.org/licenses/LICENSE-2.0.html +servers: + - url: https://api.perpetuals.polymarket.com + description: Production Perps HTTP API +security: [] +paths: + /v1/account/limits: + get: + summary: Get Account Limits + description: > + Get the authenticated account's effective rate-limit allowances for its + current + + volume-based tier: order-action rate, open-order cap, and the + display-only + + messages-per-minute figure. `open_orders` reflects the account's current + live + + open-order count; the rate-usage counters (`actions_per_minute`, + + `actions_burst`, and `reset`) are not tracked here and are reported as + 0. + operationId: getAccountLimits + responses: + '200': + description: Account limits response. + content: + application/json: + schema: + $ref: '#/components/schemas/AccountLimits' + '401': + $ref: '#/components/responses/Error401Response' + '429': + $ref: '#/components/responses/Error429Response' + '500': + $ref: '#/components/responses/Error500Response' + security: + - polymarket_proxy: [] + polymarket_secret: [] +components: + schemas: + AccountLimits: + type: object + required: + - actions_per_minute + - actions_per_minute_limit + - actions_burst + - actions_burst_limit + - open_orders + - open_orders_limit + - reset + - messages_per_minute + properties: + actions_per_minute: + $ref: '#/components/schemas/actions_per_minute' + actions_per_minute_limit: + $ref: '#/components/schemas/actions_per_minute_limit' + actions_burst: + $ref: '#/components/schemas/actions_burst' + actions_burst_limit: + $ref: '#/components/schemas/actions_burst_limit' + open_orders: + $ref: '#/components/schemas/open_orders' + open_orders_limit: + $ref: '#/components/schemas/open_orders_limit' + reset: + $ref: '#/components/schemas/rate_reset' + messages_per_minute: + $ref: '#/components/schemas/messages_per_minute' + actions_per_minute: + type: integer + description: Order action tokens used by the account in the current minute + example: 23 + actions_per_minute_limit: + type: integer + description: Maximum order action tokens per account per minute + example: 300 + actions_burst: + type: integer + description: Additional account action allowance remaining + actions_burst_limit: + type: integer + description: Additional account action allowance limit + open_orders: + type: integer + description: Current number of open orders + example: 42 + open_orders_limit: + type: integer + description: Maximum number of open orders per account + example: 1000 + rate_reset: + type: integer + description: Timestamp in milliseconds when the current interval resets + example: 1767225660000 + messages_per_minute: + type: integer + description: >- + Display-only per-minute action/message allowance, equal to + actions_per_minute_limit. Not separately configured or enforced. + example: 300 + Error401: + title: Error401 + type: object + required: + - status + - error + properties: + status: + type: string + enum: + - err + error: + $ref: '#/components/schemas/error' + Error429: + title: Error429 + type: object + required: + - status + - error + properties: + status: + type: string + enum: + - err + error: + $ref: '#/components/schemas/error' + Error500: + title: Error500 + type: object + required: + - status + - error + properties: + status: + type: string + enum: + - err + error: + $ref: '#/components/schemas/error' + error: + type: string + description: >- + Error identifier. For domain rejections and transport errors + (`401`/`404`/`429`/`500`) this is a stable, machine-readable snake_case + identifier that is part of the API contract and safe to branch on, e.g. + `insufficient_margin`, `insufficient_balance`, `order_not_found`, + `reduce_only_invalid`, `unauthorized`, `not_found`. For `400` it is a + human-readable validation detail whose wording may change. See the Error + handling guide for the domain identifiers. (Post-only / Fill-or-Kill + outcomes are order statuses such as `post_only_rejected`, not + rejections.) + example: insufficient_margin + responses: + Error401Response: + description: > + Unauthorized — missing or invalid `POLYMARKET-PROXY` / + `POLYMARKET-SECRET` + + credentials. `error` is `unauthorized`. + content: + application/json: + schema: + $ref: '#/components/schemas/Error401' + Error429Response: + description: > + Too Many Requests. `error` distinguishes the limit that was hit: + + `ip_rate_limited` (per-IP token bucket), `action_rate_limited` + (per-account + + action rate), or `open_orders_limit` (resting open-order cap). + headers: + Retry-After: + description: > + Whole seconds to wait before retrying. Present only on token-bucket + + rate-limit rejections (`ip_rate_limited` and `action_rate_limited`); + a + + conservative estimate of when enough capacity will have refilled to + + admit the request. Absent on `open_orders_limit`, which is a + capacity + + limit, not a rate limit — waiting does not free order slots; cancel + + resting orders or wait for fills instead. + schema: + type: integer + example: 2 + content: + application/json: + schema: + $ref: '#/components/schemas/Error429' + Error500Response: + description: | + Internal server error. `error` is `internal_error`. + content: + application/json: + schema: + $ref: '#/components/schemas/Error500' + securitySchemes: + polymarket_proxy: + type: apiKey + name: POLYMARKET-PROXY + in: header + description: Proxy address + polymarket_secret: + type: apiKey + name: POLYMARKET-SECRET + in: header + description: Correponding proxy secret + +```` \ No newline at end of file diff --git a/PolymarketDocumentation-main/docs/api-reference/get-account-referral.md b/PolymarketDocumentation-main/docs/api-reference/get-account-referral.md new file mode 100644 index 00000000..f4bf7458 --- /dev/null +++ b/PolymarketDocumentation-main/docs/api-reference/get-account-referral.md @@ -0,0 +1,207 @@ +> ## Documentation Index +> Fetch the complete documentation index at: https://docs.polymarket.com/llms.txt +> Use this file to discover all available pages before exploring further. + +# Get Account Referral + +> Get the authenticated account's invite code, parent referral code, direct +referral count, and fee share rate. + + +Request Weight: **1** + + +## OpenAPI + +````yaml /api-spec/perps-openapi.json get /v1/account/referral +openapi: 3.0.3 +info: + title: Polymarket Perps HTTP API + version: 1.0.0 + description: HTTP API for Polymarket perpetual trading system. + license: + name: Apache 2.0 + url: https://www.apache.org/licenses/LICENSE-2.0.html +servers: + - url: https://api.perpetuals.polymarket.com + description: Production Perps HTTP API +security: [] +paths: + /v1/account/referral: + get: + summary: Get Account Referral + description: > + Get the authenticated account's invite code, parent referral code, + direct + + referral count, and fee share rate. + operationId: getAccountReferral + responses: + '200': + description: Account referral response. + content: + application/json: + schema: + $ref: '#/components/schemas/AccountReferral' + '401': + $ref: '#/components/responses/Error401Response' + '429': + $ref: '#/components/responses/Error429Response' + '500': + $ref: '#/components/responses/Error500Response' + security: + - polymarket_proxy: [] + polymarket_secret: [] +components: + schemas: + AccountReferral: + type: object + required: + - code + - children_count + - referrals_left + - fee_share_rate + properties: + code: + $ref: '#/components/schemas/code' + parent: + $ref: '#/components/schemas/code' + description: >- + Parent referral code, omitted when the account has no parent + referral. + children_count: + $ref: '#/components/schemas/children_count' + referrals_left: + $ref: '#/components/schemas/referrals_left' + fee_share_rate: + $ref: '#/components/schemas/fee_share_rate' + code: + type: string + description: Referral or invite code + example: ABC123 + children_count: + type: integer + description: Number of directly referred child accounts + example: 12 + referrals_left: + type: integer + description: Number of additional referrals remaining for this account's invite code + example: 11 + fee_share_rate: + type: string + description: Referral fee share rate. Defaults to 0.2. + example: '0.2' + Error401: + title: Error401 + type: object + required: + - status + - error + properties: + status: + type: string + enum: + - err + error: + $ref: '#/components/schemas/error' + Error429: + title: Error429 + type: object + required: + - status + - error + properties: + status: + type: string + enum: + - err + error: + $ref: '#/components/schemas/error' + Error500: + title: Error500 + type: object + required: + - status + - error + properties: + status: + type: string + enum: + - err + error: + $ref: '#/components/schemas/error' + error: + type: string + description: >- + Error identifier. For domain rejections and transport errors + (`401`/`404`/`429`/`500`) this is a stable, machine-readable snake_case + identifier that is part of the API contract and safe to branch on, e.g. + `insufficient_margin`, `insufficient_balance`, `order_not_found`, + `reduce_only_invalid`, `unauthorized`, `not_found`. For `400` it is a + human-readable validation detail whose wording may change. See the Error + handling guide for the domain identifiers. (Post-only / Fill-or-Kill + outcomes are order statuses such as `post_only_rejected`, not + rejections.) + example: insufficient_margin + responses: + Error401Response: + description: > + Unauthorized — missing or invalid `POLYMARKET-PROXY` / + `POLYMARKET-SECRET` + + credentials. `error` is `unauthorized`. + content: + application/json: + schema: + $ref: '#/components/schemas/Error401' + Error429Response: + description: > + Too Many Requests. `error` distinguishes the limit that was hit: + + `ip_rate_limited` (per-IP token bucket), `action_rate_limited` + (per-account + + action rate), or `open_orders_limit` (resting open-order cap). + headers: + Retry-After: + description: > + Whole seconds to wait before retrying. Present only on token-bucket + + rate-limit rejections (`ip_rate_limited` and `action_rate_limited`); + a + + conservative estimate of when enough capacity will have refilled to + + admit the request. Absent on `open_orders_limit`, which is a + capacity + + limit, not a rate limit — waiting does not free order slots; cancel + + resting orders or wait for fills instead. + schema: + type: integer + example: 2 + content: + application/json: + schema: + $ref: '#/components/schemas/Error429' + Error500Response: + description: | + Internal server error. `error` is `internal_error`. + content: + application/json: + schema: + $ref: '#/components/schemas/Error500' + securitySchemes: + polymarket_proxy: + type: apiKey + name: POLYMARKET-PROXY + in: header + description: Proxy address + polymarket_secret: + type: apiKey + name: POLYMARKET-SECRET + in: header + description: Correponding proxy secret + +```` \ No newline at end of file diff --git a/PolymarketDocumentation-main/docs/api-reference/get-account-rewards.md b/PolymarketDocumentation-main/docs/api-reference/get-account-rewards.md new file mode 100644 index 00000000..2327cc02 --- /dev/null +++ b/PolymarketDocumentation-main/docs/api-reference/get-account-rewards.md @@ -0,0 +1,333 @@ +> ## Documentation Index +> Fetch the complete documentation index at: https://docs.polymarket.com/llms.txt +> Use this file to discover all available pages before exploring further. + +# Get Account Rewards + +> Get per-instrument daily liquidity reward shares for the authenticated account. +Reward periods run from 12:00 UTC to 12:00 UTC and are labeled by their UTC end date. +OI rewards pay 6% APR on the account's full daily average gross OI across all +instruments when the combined daily average gross OI of its rewards entity is +at least $1M. Accounts without an entity mapping qualify independently. +The first reward period starts at 2026-05-08 12:00 UTC. If no date range is provided, +the latest computed reward period is returned. + + +Request Weight: **2** + + +## OpenAPI + +````yaml /api-spec/perps-openapi.json get /v1/account/rewards +openapi: 3.0.3 +info: + title: Polymarket Perps HTTP API + version: 1.0.0 + description: HTTP API for Polymarket perpetual trading system. + license: + name: Apache 2.0 + url: https://www.apache.org/licenses/LICENSE-2.0.html +servers: + - url: https://api.perpetuals.polymarket.com + description: Production Perps HTTP API +security: [] +paths: + /v1/account/rewards: + get: + summary: Get Account Rewards + description: > + Get per-instrument daily liquidity reward shares for the authenticated + account. + + Reward periods run from 12:00 UTC to 12:00 UTC and are labeled by their + UTC end date. + + OI rewards pay 6% APR on the account's full daily average gross OI + across all + + instruments when the combined daily average gross OI of its rewards + entity is + + at least $1M. Accounts without an entity mapping qualify independently. + + The first reward period starts at 2026-05-08 12:00 UTC. If no date range + is provided, + + the latest computed reward period is returned. + operationId: getAccountRewards + parameters: + - name: date + in: query + required: false + schema: + $ref: '#/components/schemas/date' + - name: start_date + in: query + required: false + schema: + $ref: '#/components/schemas/start_date' + - name: end_date + in: query + required: false + schema: + $ref: '#/components/schemas/end_date' + - name: limit + in: query + required: false + schema: + $ref: '#/components/schemas/limit' + responses: + '200': + description: Account rewards response. + content: + application/json: + schema: + $ref: '#/components/schemas/AccountRewards' + '400': + $ref: '#/components/responses/Error400Response' + '401': + $ref: '#/components/responses/Error401Response' + '429': + $ref: '#/components/responses/Error429Response' + '500': + $ref: '#/components/responses/Error500Response' + security: + - polymarket_proxy: [] + polymarket_secret: [] +components: + schemas: + date: + type: string + description: UTC reward period end date in YYYY-MM-DD format + example: '2026-05-10' + start_date: + type: string + description: Inclusive UTC start date in YYYY-MM-DD format + example: '2026-05-01' + end_date: + type: string + description: Inclusive UTC end date in YYYY-MM-DD format + example: '2026-05-10' + limit: + type: integer + description: Maximum number of entries to return + example: 100 + AccountRewards: + type: object + required: + - data + - more + properties: + data: + type: array + items: + $ref: '#/components/schemas/AccountReward' + more: + $ref: '#/components/schemas/more' + AccountReward: + type: object + required: + - date + - maker_share_7d + - reward_distributed + - breakdown + properties: + date: + $ref: '#/components/schemas/date' + maker_share_7d: + $ref: '#/components/schemas/maker_share_7d' + reward_distributed: + $ref: '#/components/schemas/reward_distributed' + breakdown: + type: array + items: + $ref: '#/components/schemas/AccountRewardInstrument' + oi_rewards: + $ref: '#/components/schemas/AccountRewardOi' + more: + type: boolean + description: More data available + Error400: + title: Error400 + type: object + required: + - status + - error + properties: + status: + type: string + enum: + - err + error: + $ref: '#/components/schemas/error' + Error401: + title: Error401 + type: object + required: + - status + - error + properties: + status: + type: string + enum: + - err + error: + $ref: '#/components/schemas/error' + Error429: + title: Error429 + type: object + required: + - status + - error + properties: + status: + type: string + enum: + - err + error: + $ref: '#/components/schemas/error' + Error500: + title: Error500 + type: object + required: + - status + - error + properties: + status: + type: string + enum: + - err + error: + $ref: '#/components/schemas/error' + maker_share_7d: + type: string + description: Rolling 7-day account maker volume divided by total exchange volume + example: '0.35' + reward_distributed: + type: boolean + description: Whether rewards for this period have been marked as distributed + example: true + AccountRewardInstrument: + type: object + required: + - instrument_id + - reward_pool + - reward_amount + properties: + instrument_id: + $ref: '#/components/schemas/instrument_id' + reward_pool: + $ref: '#/components/schemas/reward_pool' + reward_amount: + $ref: '#/components/schemas/reward_amount' + AccountRewardOi: + type: object + required: + - account_oi + - reward_amount + properties: + account_oi: + $ref: '#/components/schemas/account_oi' + reward_amount: + $ref: '#/components/schemas/reward_amount' + error: + type: string + description: >- + Error identifier. For domain rejections and transport errors + (`401`/`404`/`429`/`500`) this is a stable, machine-readable snake_case + identifier that is part of the API contract and safe to branch on, e.g. + `insufficient_margin`, `insufficient_balance`, `order_not_found`, + `reduce_only_invalid`, `unauthorized`, `not_found`. For `400` it is a + human-readable validation detail whose wording may change. See the Error + handling guide for the domain identifiers. (Post-only / Fill-or-Kill + outcomes are order statuses such as `post_only_rejected`, not + rejections.) + example: insufficient_margin + instrument_id: + type: integer + description: Instrument ID + reward_pool: + type: string + description: Configured reward pool for the instrument + example: '1000' + reward_amount: + type: string + description: Reward amount attributed to this reward row + example: '127.50344' + account_oi: + type: string + description: >- + Daily average gross open-interest notional for this account across all + instruments + example: '3200000' + responses: + Error400Response: + description: | + Bad request — the request was malformed or failed validation (bad query + parameters, unparseable body, invalid signature, or a domain pre-check). + The `error` field is a human-readable validation detail. + content: + application/json: + schema: + $ref: '#/components/schemas/Error400' + Error401Response: + description: > + Unauthorized — missing or invalid `POLYMARKET-PROXY` / + `POLYMARKET-SECRET` + + credentials. `error` is `unauthorized`. + content: + application/json: + schema: + $ref: '#/components/schemas/Error401' + Error429Response: + description: > + Too Many Requests. `error` distinguishes the limit that was hit: + + `ip_rate_limited` (per-IP token bucket), `action_rate_limited` + (per-account + + action rate), or `open_orders_limit` (resting open-order cap). + headers: + Retry-After: + description: > + Whole seconds to wait before retrying. Present only on token-bucket + + rate-limit rejections (`ip_rate_limited` and `action_rate_limited`); + a + + conservative estimate of when enough capacity will have refilled to + + admit the request. Absent on `open_orders_limit`, which is a + capacity + + limit, not a rate limit — waiting does not free order slots; cancel + + resting orders or wait for fills instead. + schema: + type: integer + example: 2 + content: + application/json: + schema: + $ref: '#/components/schemas/Error429' + Error500Response: + description: | + Internal server error. `error` is `internal_error`. + content: + application/json: + schema: + $ref: '#/components/schemas/Error500' + securitySchemes: + polymarket_proxy: + type: apiKey + name: POLYMARKET-PROXY + in: header + description: Proxy address + polymarket_secret: + type: apiKey + name: POLYMARKET-SECRET + in: header + description: Correponding proxy secret + +```` \ No newline at end of file diff --git a/PolymarketDocumentation-main/docs/api-reference/get-account-stats.md b/PolymarketDocumentation-main/docs/api-reference/get-account-stats.md new file mode 100644 index 00000000..5c840e56 --- /dev/null +++ b/PolymarketDocumentation-main/docs/api-reference/get-account-stats.md @@ -0,0 +1,223 @@ +> ## Documentation Index +> Fetch the complete documentation index at: https://docs.polymarket.com/llms.txt +> Use this file to discover all available pages before exploring further. + +# Get Account Stats + +> Get the authenticated account's 7-day trading stats (taker volume, maker volume, +account maker share, and entity maker share when applicable). +Stats are cached by UTC day and may be stale by up to 24 hours. + + +Request Weight: **2** + + +## OpenAPI + +````yaml /api-spec/perps-openapi.json get /v1/account/stats +openapi: 3.0.3 +info: + title: Polymarket Perps HTTP API + version: 1.0.0 + description: HTTP API for Polymarket perpetual trading system. + license: + name: Apache 2.0 + url: https://www.apache.org/licenses/LICENSE-2.0.html +servers: + - url: https://api.perpetuals.polymarket.com + description: Production Perps HTTP API +security: [] +paths: + /v1/account/stats: + get: + summary: Get Account Stats + description: > + Get the authenticated account's 7-day trading stats (taker volume, maker + volume, + + account maker share, and entity maker share when applicable). + + Stats are cached by UTC day and may be stale by up to 24 hours. + operationId: getAccountStats + responses: + '200': + description: Account stats response. + content: + application/json: + schema: + $ref: '#/components/schemas/AccountStats' + '401': + $ref: '#/components/responses/Error401Response' + '429': + $ref: '#/components/responses/Error429Response' + '500': + $ref: '#/components/responses/Error500Response' + security: + - polymarket_proxy: [] + polymarket_secret: [] +components: + schemas: + AccountStats: + type: object + required: + - volume_7d + - taker_volume_7d + - maker_volume_7d + - account_maker_share_7d + properties: + volume_7d: + $ref: '#/components/schemas/volume_7d' + taker_volume_7d: + $ref: '#/components/schemas/taker_volume_7d' + maker_volume_7d: + $ref: '#/components/schemas/maker_volume_7d' + account_maker_share_7d: + $ref: '#/components/schemas/account_maker_share_7d' + entity_maker_share_7d: + $ref: '#/components/schemas/entity_maker_share_7d' + entity_id: + $ref: '#/components/schemas/entity_id' + entity_name: + $ref: '#/components/schemas/entity_name' + volume_7d: + type: string + description: Rolling 7-day perpetual trading volume in USD + example: '5000000' + taker_volume_7d: + type: string + description: Rolling 7-day perpetual taker volume in USD + example: '3500000' + maker_volume_7d: + type: string + description: Rolling 7-day perpetual maker volume in USD + example: '1500000' + account_maker_share_7d: + type: string + description: Rolling 7-day account maker volume divided by total exchange volume + example: '0.35' + entity_maker_share_7d: + type: string + description: Rolling 7-day entity maker volume divided by total exchange volume + example: '0.35' + entity_id: + type: integer + description: Liquidity rewards entity ID + example: 42 + entity_name: + type: string + description: Liquidity rewards entity name + example: desk + Error401: + title: Error401 + type: object + required: + - status + - error + properties: + status: + type: string + enum: + - err + error: + $ref: '#/components/schemas/error' + Error429: + title: Error429 + type: object + required: + - status + - error + properties: + status: + type: string + enum: + - err + error: + $ref: '#/components/schemas/error' + Error500: + title: Error500 + type: object + required: + - status + - error + properties: + status: + type: string + enum: + - err + error: + $ref: '#/components/schemas/error' + error: + type: string + description: >- + Error identifier. For domain rejections and transport errors + (`401`/`404`/`429`/`500`) this is a stable, machine-readable snake_case + identifier that is part of the API contract and safe to branch on, e.g. + `insufficient_margin`, `insufficient_balance`, `order_not_found`, + `reduce_only_invalid`, `unauthorized`, `not_found`. For `400` it is a + human-readable validation detail whose wording may change. See the Error + handling guide for the domain identifiers. (Post-only / Fill-or-Kill + outcomes are order statuses such as `post_only_rejected`, not + rejections.) + example: insufficient_margin + responses: + Error401Response: + description: > + Unauthorized — missing or invalid `POLYMARKET-PROXY` / + `POLYMARKET-SECRET` + + credentials. `error` is `unauthorized`. + content: + application/json: + schema: + $ref: '#/components/schemas/Error401' + Error429Response: + description: > + Too Many Requests. `error` distinguishes the limit that was hit: + + `ip_rate_limited` (per-IP token bucket), `action_rate_limited` + (per-account + + action rate), or `open_orders_limit` (resting open-order cap). + headers: + Retry-After: + description: > + Whole seconds to wait before retrying. Present only on token-bucket + + rate-limit rejections (`ip_rate_limited` and `action_rate_limited`); + a + + conservative estimate of when enough capacity will have refilled to + + admit the request. Absent on `open_orders_limit`, which is a + capacity + + limit, not a rate limit — waiting does not free order slots; cancel + + resting orders or wait for fills instead. + schema: + type: integer + example: 2 + content: + application/json: + schema: + $ref: '#/components/schemas/Error429' + Error500Response: + description: | + Internal server error. `error` is `internal_error`. + content: + application/json: + schema: + $ref: '#/components/schemas/Error500' + securitySchemes: + polymarket_proxy: + type: apiKey + name: POLYMARKET-PROXY + in: header + description: Proxy address + polymarket_secret: + type: apiKey + name: POLYMARKET-SECRET + in: header + description: Correponding proxy secret + +```` \ No newline at end of file diff --git a/PolymarketDocumentation-main/docs/api-reference/get-auto-cancel-status.md b/PolymarketDocumentation-main/docs/api-reference/get-auto-cancel-status.md new file mode 100644 index 00000000..4c196017 --- /dev/null +++ b/PolymarketDocumentation-main/docs/api-reference/get-auto-cancel-status.md @@ -0,0 +1,210 @@ +> ## Documentation Index +> Fetch the complete documentation index at: https://docs.polymarket.com/llms.txt +> Use this file to discover all available pages before exploring further. + +# Get Auto-Cancel Status + +> Get the current auto-cancel dead-man-switch status for the authenticated +account, including the armed deadline, today's trigger count, and when +the daily counter resets. + + +Request Weight: **1** + + +## OpenAPI + +````yaml /api-spec/perps-openapi.json get /v1/account/auto-cancel +openapi: 3.0.3 +info: + title: Polymarket Perps HTTP API + version: 1.0.0 + description: HTTP API for Polymarket perpetual trading system. + license: + name: Apache 2.0 + url: https://www.apache.org/licenses/LICENSE-2.0.html +servers: + - url: https://api.perpetuals.polymarket.com + description: Production Perps HTTP API +security: [] +paths: + /v1/account/auto-cancel: + get: + summary: Get Auto-Cancel Status + description: | + Get the current auto-cancel dead-man-switch status for the authenticated + account, including the armed deadline, today's trigger count, and when + the daily counter resets. + operationId: getAutoCancel + responses: + '200': + description: Auto-cancel status response. + content: + application/json: + schema: + $ref: '#/components/schemas/AutoCancelStatus' + '401': + $ref: '#/components/responses/Error401Response' + '429': + $ref: '#/components/responses/Error429Response' + '500': + $ref: '#/components/responses/Error500Response' + security: + - polymarket_proxy: [] + polymarket_secret: [] +components: + schemas: + AutoCancelStatus: + type: object + required: + - deadline + - triggered + - daily_limit + - next_reset + properties: + deadline: + $ref: '#/components/schemas/auto_cancel_deadline' + triggered: + $ref: '#/components/schemas/auto_cancel_triggered' + daily_limit: + $ref: '#/components/schemas/auto_cancel_daily_limit' + next_reset: + $ref: '#/components/schemas/auto_cancel_next_reset' + auto_cancel_deadline: + type: integer + description: | + Unix-ms deadline for the per-account auto-cancel dead-man-switch. + Zero means no schedule is armed. When the deadline elapses, every + open order on the account is cancelled and the schedule clears. + example: 1767000045000 + auto_cancel_triggered: + type: integer + description: | + Number of times auto-cancel has fired for this account during the + current UTC day. Resets to zero at 00:00 UTC. + example: 0 + auto_cancel_daily_limit: + type: integer + description: | + Maximum number of auto-cancel triggers allowed per UTC day. + example: 10 + auto_cancel_next_reset: + type: integer + description: | + Unix-ms timestamp of the next UTC midnight when the daily trigger + count resets to zero. + example: 1767052800000 + Error401: + title: Error401 + type: object + required: + - status + - error + properties: + status: + type: string + enum: + - err + error: + $ref: '#/components/schemas/error' + Error429: + title: Error429 + type: object + required: + - status + - error + properties: + status: + type: string + enum: + - err + error: + $ref: '#/components/schemas/error' + Error500: + title: Error500 + type: object + required: + - status + - error + properties: + status: + type: string + enum: + - err + error: + $ref: '#/components/schemas/error' + error: + type: string + description: >- + Error identifier. For domain rejections and transport errors + (`401`/`404`/`429`/`500`) this is a stable, machine-readable snake_case + identifier that is part of the API contract and safe to branch on, e.g. + `insufficient_margin`, `insufficient_balance`, `order_not_found`, + `reduce_only_invalid`, `unauthorized`, `not_found`. For `400` it is a + human-readable validation detail whose wording may change. See the Error + handling guide for the domain identifiers. (Post-only / Fill-or-Kill + outcomes are order statuses such as `post_only_rejected`, not + rejections.) + example: insufficient_margin + responses: + Error401Response: + description: > + Unauthorized — missing or invalid `POLYMARKET-PROXY` / + `POLYMARKET-SECRET` + + credentials. `error` is `unauthorized`. + content: + application/json: + schema: + $ref: '#/components/schemas/Error401' + Error429Response: + description: > + Too Many Requests. `error` distinguishes the limit that was hit: + + `ip_rate_limited` (per-IP token bucket), `action_rate_limited` + (per-account + + action rate), or `open_orders_limit` (resting open-order cap). + headers: + Retry-After: + description: > + Whole seconds to wait before retrying. Present only on token-bucket + + rate-limit rejections (`ip_rate_limited` and `action_rate_limited`); + a + + conservative estimate of when enough capacity will have refilled to + + admit the request. Absent on `open_orders_limit`, which is a + capacity + + limit, not a rate limit — waiting does not free order slots; cancel + + resting orders or wait for fills instead. + schema: + type: integer + example: 2 + content: + application/json: + schema: + $ref: '#/components/schemas/Error429' + Error500Response: + description: | + Internal server error. `error` is `internal_error`. + content: + application/json: + schema: + $ref: '#/components/schemas/Error500' + securitySchemes: + polymarket_proxy: + type: apiKey + name: POLYMARKET-PROXY + in: header + description: Proxy address + polymarket_secret: + type: apiKey + name: POLYMARKET-SECRET + in: header + description: Correponding proxy secret + +```` \ No newline at end of file diff --git a/PolymarketDocumentation-main/docs/api-reference/get-balances.md b/PolymarketDocumentation-main/docs/api-reference/get-balances.md new file mode 100644 index 00000000..3c7730a5 --- /dev/null +++ b/PolymarketDocumentation-main/docs/api-reference/get-balances.md @@ -0,0 +1,191 @@ +> ## Documentation Index +> Fetch the complete documentation index at: https://docs.polymarket.com/llms.txt +> Use this file to discover all available pages before exploring further. + +# Get Balances + +> Get asset balances for the authenticated account. + +Request Weight: **2** + + +## OpenAPI + +````yaml /api-spec/perps-openapi.json get /v1/account/balances +openapi: 3.0.3 +info: + title: Polymarket Perps HTTP API + version: 1.0.0 + description: HTTP API for Polymarket perpetual trading system. + license: + name: Apache 2.0 + url: https://www.apache.org/licenses/LICENSE-2.0.html +servers: + - url: https://api.perpetuals.polymarket.com + description: Production Perps HTTP API +security: [] +paths: + /v1/account/balances: + get: + summary: Get Balances + description: Get asset balances for the authenticated account. + operationId: getBalances + responses: + '200': + description: Balances response. + content: + application/json: + schema: + type: array + items: + $ref: '#/components/schemas/Balance' + '401': + $ref: '#/components/responses/Error401Response' + '429': + $ref: '#/components/responses/Error429Response' + '500': + $ref: '#/components/responses/Error500Response' + security: + - polymarket_proxy: [] + polymarket_secret: [] +components: + schemas: + Balance: + type: object + required: + - asset + - balance + - value + properties: + asset: + $ref: '#/components/schemas/asset' + balance: + $ref: '#/components/schemas/balance' + value: + $ref: '#/components/schemas/value' + asset: + type: string + description: Asset name + example: USDC + balance: + type: string + description: Total balance + example: '10000.00' + value: + type: string + description: USD value + example: '10000.00' + Error401: + title: Error401 + type: object + required: + - status + - error + properties: + status: + type: string + enum: + - err + error: + $ref: '#/components/schemas/error' + Error429: + title: Error429 + type: object + required: + - status + - error + properties: + status: + type: string + enum: + - err + error: + $ref: '#/components/schemas/error' + Error500: + title: Error500 + type: object + required: + - status + - error + properties: + status: + type: string + enum: + - err + error: + $ref: '#/components/schemas/error' + error: + type: string + description: >- + Error identifier. For domain rejections and transport errors + (`401`/`404`/`429`/`500`) this is a stable, machine-readable snake_case + identifier that is part of the API contract and safe to branch on, e.g. + `insufficient_margin`, `insufficient_balance`, `order_not_found`, + `reduce_only_invalid`, `unauthorized`, `not_found`. For `400` it is a + human-readable validation detail whose wording may change. See the Error + handling guide for the domain identifiers. (Post-only / Fill-or-Kill + outcomes are order statuses such as `post_only_rejected`, not + rejections.) + example: insufficient_margin + responses: + Error401Response: + description: > + Unauthorized — missing or invalid `POLYMARKET-PROXY` / + `POLYMARKET-SECRET` + + credentials. `error` is `unauthorized`. + content: + application/json: + schema: + $ref: '#/components/schemas/Error401' + Error429Response: + description: > + Too Many Requests. `error` distinguishes the limit that was hit: + + `ip_rate_limited` (per-IP token bucket), `action_rate_limited` + (per-account + + action rate), or `open_orders_limit` (resting open-order cap). + headers: + Retry-After: + description: > + Whole seconds to wait before retrying. Present only on token-bucket + + rate-limit rejections (`ip_rate_limited` and `action_rate_limited`); + a + + conservative estimate of when enough capacity will have refilled to + + admit the request. Absent on `open_orders_limit`, which is a + capacity + + limit, not a rate limit — waiting does not free order slots; cancel + + resting orders or wait for fills instead. + schema: + type: integer + example: 2 + content: + application/json: + schema: + $ref: '#/components/schemas/Error429' + Error500Response: + description: | + Internal server error. `error` is `internal_error`. + content: + application/json: + schema: + $ref: '#/components/schemas/Error500' + securitySchemes: + polymarket_proxy: + type: apiKey + name: POLYMARKET-PROXY + in: header + description: Proxy address + polymarket_secret: + type: apiKey + name: POLYMARKET-SECRET + in: header + description: Correponding proxy secret + +```` \ No newline at end of file diff --git a/PolymarketDocumentation-main/docs/api-reference/get-bbo.md b/PolymarketDocumentation-main/docs/api-reference/get-bbo.md new file mode 100644 index 00000000..59bbf954 --- /dev/null +++ b/PolymarketDocumentation-main/docs/api-reference/get-bbo.md @@ -0,0 +1,211 @@ +> ## Documentation Index +> Fetch the complete documentation index at: https://docs.polymarket.com/llms.txt +> Use this file to discover all available pages before exploring further. + +# Get BBO + +> Get best bid and offer for all instruments. + +Request Weight: **2** + + +## OpenAPI + +````yaml /api-spec/perps-openapi.json get /v1/info/bbo +openapi: 3.0.3 +info: + title: Polymarket Perps HTTP API + version: 1.0.0 + description: HTTP API for Polymarket perpetual trading system. + license: + name: Apache 2.0 + url: https://www.apache.org/licenses/LICENSE-2.0.html +servers: + - url: https://api.perpetuals.polymarket.com + description: Production Perps HTTP API +security: [] +paths: + /v1/info/bbo: + get: + summary: Get BBO + description: Get best bid and offer for all instruments. + operationId: getBBO + parameters: + - name: instrument_id + in: query + required: false + schema: + $ref: '#/components/schemas/instrument_id' + responses: + '200': + description: BBO response. + content: + application/json: + schema: + type: array + items: + $ref: '#/components/schemas/BBO' + '400': + $ref: '#/components/responses/Error400Response' + '429': + $ref: '#/components/responses/Error429Response' + '500': + $ref: '#/components/responses/Error500Response' + security: [] +components: + schemas: + instrument_id: + type: integer + description: Instrument ID + BBO: + title: BBO + type: object + required: + - instrument_id + - bid_price + - bid_quantity + - ask_price + - ask_quantity + - timestamp + properties: + instrument_id: + $ref: '#/components/schemas/iid' + bid_price: + $ref: '#/components/schemas/best_bid_price' + bid_quantity: + $ref: '#/components/schemas/best_bid_quantity' + ask_price: + $ref: '#/components/schemas/best_ask_price' + ask_quantity: + $ref: '#/components/schemas/best_ask_quantity' + timestamp: + $ref: '#/components/schemas/ts' + iid: + type: integer + description: Instrument ID + example: 1 + best_bid_price: + type: string + description: Best bid price + example: '99.50' + best_bid_quantity: + type: string + description: Best bid quantity + example: '10.00' + best_ask_price: + type: string + description: Best ask price + example: '100.50' + best_ask_quantity: + type: string + description: Best ask quantity + example: '10.00' + ts: + type: integer + description: >- + Request timestamp. Unix milliseconds for most operations; Unix seconds + for withdrawals (must match the on-chain EIP-712 struct verified against + block.timestamp). + example: 1767225600000 + Error400: + title: Error400 + type: object + required: + - status + - error + properties: + status: + type: string + enum: + - err + error: + $ref: '#/components/schemas/error' + Error429: + title: Error429 + type: object + required: + - status + - error + properties: + status: + type: string + enum: + - err + error: + $ref: '#/components/schemas/error' + Error500: + title: Error500 + type: object + required: + - status + - error + properties: + status: + type: string + enum: + - err + error: + $ref: '#/components/schemas/error' + error: + type: string + description: >- + Error identifier. For domain rejections and transport errors + (`401`/`404`/`429`/`500`) this is a stable, machine-readable snake_case + identifier that is part of the API contract and safe to branch on, e.g. + `insufficient_margin`, `insufficient_balance`, `order_not_found`, + `reduce_only_invalid`, `unauthorized`, `not_found`. For `400` it is a + human-readable validation detail whose wording may change. See the Error + handling guide for the domain identifiers. (Post-only / Fill-or-Kill + outcomes are order statuses such as `post_only_rejected`, not + rejections.) + example: insufficient_margin + responses: + Error400Response: + description: | + Bad request — the request was malformed or failed validation (bad query + parameters, unparseable body, invalid signature, or a domain pre-check). + The `error` field is a human-readable validation detail. + content: + application/json: + schema: + $ref: '#/components/schemas/Error400' + Error429Response: + description: > + Too Many Requests. `error` distinguishes the limit that was hit: + + `ip_rate_limited` (per-IP token bucket), `action_rate_limited` + (per-account + + action rate), or `open_orders_limit` (resting open-order cap). + headers: + Retry-After: + description: > + Whole seconds to wait before retrying. Present only on token-bucket + + rate-limit rejections (`ip_rate_limited` and `action_rate_limited`); + a + + conservative estimate of when enough capacity will have refilled to + + admit the request. Absent on `open_orders_limit`, which is a + capacity + + limit, not a rate limit — waiting does not free order slots; cancel + + resting orders or wait for fills instead. + schema: + type: integer + example: 2 + content: + application/json: + schema: + $ref: '#/components/schemas/Error429' + Error500Response: + description: | + Internal server error. `error` is `internal_error`. + content: + application/json: + schema: + $ref: '#/components/schemas/Error500' + +```` \ No newline at end of file diff --git a/PolymarketDocumentation-main/docs/api-reference/get-book.md b/PolymarketDocumentation-main/docs/api-reference/get-book.md new file mode 100644 index 00000000..77349727 --- /dev/null +++ b/PolymarketDocumentation-main/docs/api-reference/get-book.md @@ -0,0 +1,233 @@ +> ## Documentation Index +> Fetch the complete documentation index at: https://docs.polymarket.com/llms.txt +> Use this file to discover all available pages before exploring further. + +# Get Book + +> Get book for an instrument. + +Request Weight: + +
+ +Depth 10: **2** + +
+ +Depth 100: **5** + +
+ +Depth 500: **10** + +
+ +Depth 1000: **20** + + +## OpenAPI + +````yaml /api-spec/perps-openapi.json get /v1/info/book +openapi: 3.0.3 +info: + title: Polymarket Perps HTTP API + version: 1.0.0 + description: HTTP API for Polymarket perpetual trading system. + license: + name: Apache 2.0 + url: https://www.apache.org/licenses/LICENSE-2.0.html +servers: + - url: https://api.perpetuals.polymarket.com + description: Production Perps HTTP API +security: [] +paths: + /v1/info/book: + get: + summary: Get Book + description: Get book for an instrument. + operationId: getBook + parameters: + - name: instrument_id + in: query + required: true + schema: + $ref: '#/components/schemas/instrument_id' + - name: depth + in: query + required: false + schema: + $ref: '#/components/schemas/depth' + responses: + '200': + description: Book response. + content: + application/json: + schema: + $ref: '#/components/schemas/Book' + '400': + $ref: '#/components/responses/Error400Response' + '429': + $ref: '#/components/responses/Error429Response' + '500': + $ref: '#/components/responses/Error500Response' + security: [] +components: + schemas: + instrument_id: + type: integer + description: Instrument ID + depth: + type: integer + description: Number of book levels to return + enum: + - 10 + - 100 + - 500 + - 1000 + default: 100 + Book: + type: object + required: + - instrument_id + - bids + - asks + - timestamp + - sequence + properties: + instrument_id: + $ref: '#/components/schemas/instrument_id' + bids: + type: array + items: + $ref: '#/components/schemas/level' + description: Bid levels + asks: + type: array + items: + $ref: '#/components/schemas/level' + description: Ask levels + timestamp: + $ref: '#/components/schemas/timestamp' + sequence: + $ref: '#/components/schemas/sequence' + level: + type: array + items: + type: string + maxItems: 2 + description: | + - `"100.00"` - Price + - `"10.00"` - Quantity + example: + - '100.00' + - '10.00' + timestamp: + type: integer + description: Timestamp in milliseconds + example: 1767225600000 + sequence: + type: integer + description: Sequence number + example: 1234567890 + Error400: + title: Error400 + type: object + required: + - status + - error + properties: + status: + type: string + enum: + - err + error: + $ref: '#/components/schemas/error' + Error429: + title: Error429 + type: object + required: + - status + - error + properties: + status: + type: string + enum: + - err + error: + $ref: '#/components/schemas/error' + Error500: + title: Error500 + type: object + required: + - status + - error + properties: + status: + type: string + enum: + - err + error: + $ref: '#/components/schemas/error' + error: + type: string + description: >- + Error identifier. For domain rejections and transport errors + (`401`/`404`/`429`/`500`) this is a stable, machine-readable snake_case + identifier that is part of the API contract and safe to branch on, e.g. + `insufficient_margin`, `insufficient_balance`, `order_not_found`, + `reduce_only_invalid`, `unauthorized`, `not_found`. For `400` it is a + human-readable validation detail whose wording may change. See the Error + handling guide for the domain identifiers. (Post-only / Fill-or-Kill + outcomes are order statuses such as `post_only_rejected`, not + rejections.) + example: insufficient_margin + responses: + Error400Response: + description: | + Bad request — the request was malformed or failed validation (bad query + parameters, unparseable body, invalid signature, or a domain pre-check). + The `error` field is a human-readable validation detail. + content: + application/json: + schema: + $ref: '#/components/schemas/Error400' + Error429Response: + description: > + Too Many Requests. `error` distinguishes the limit that was hit: + + `ip_rate_limited` (per-IP token bucket), `action_rate_limited` + (per-account + + action rate), or `open_orders_limit` (resting open-order cap). + headers: + Retry-After: + description: > + Whole seconds to wait before retrying. Present only on token-bucket + + rate-limit rejections (`ip_rate_limited` and `action_rate_limited`); + a + + conservative estimate of when enough capacity will have refilled to + + admit the request. Absent on `open_orders_limit`, which is a + capacity + + limit, not a rate limit — waiting does not free order slots; cancel + + resting orders or wait for fills instead. + schema: + type: integer + example: 2 + content: + application/json: + schema: + $ref: '#/components/schemas/Error429' + Error500Response: + description: | + Internal server error. `error` is `internal_error`. + content: + application/json: + schema: + $ref: '#/components/schemas/Error500' + +```` \ No newline at end of file diff --git a/PolymarketDocumentation-main/docs/api-reference/get-collateral-assets.md b/PolymarketDocumentation-main/docs/api-reference/get-collateral-assets.md new file mode 100644 index 00000000..6afb9aba --- /dev/null +++ b/PolymarketDocumentation-main/docs/api-reference/get-collateral-assets.md @@ -0,0 +1,169 @@ +> ## Documentation Index +> Fetch the complete documentation index at: https://docs.polymarket.com/llms.txt +> Use this file to discover all available pages before exploring further. + +# Get Collateral Assets + +> Get a list of collateral assets. + + +Request Weight: **2** + + +## OpenAPI + +````yaml /api-spec/perps-openapi.json get /v1/info/assets +openapi: 3.0.3 +info: + title: Polymarket Perps HTTP API + version: 1.0.0 + description: HTTP API for Polymarket perpetual trading system. + license: + name: Apache 2.0 + url: https://www.apache.org/licenses/LICENSE-2.0.html +servers: + - url: https://api.perpetuals.polymarket.com + description: Production Perps HTTP API +security: [] +paths: + /v1/info/assets: + get: + summary: Get Collateral Assets + description: | + Get a list of collateral assets. + operationId: getAssets + responses: + '200': + description: Assets response. + content: + application/json: + schema: + type: array + items: + $ref: '#/components/schemas/Asset' + '429': + $ref: '#/components/responses/Error429Response' + '500': + $ref: '#/components/responses/Error500Response' + security: [] +components: + schemas: + Asset: + type: object + required: + - asset + - address + - decimals + - collateral_ratio + - withdrawal_fee + properties: + asset: + $ref: '#/components/schemas/asset' + address: + $ref: '#/components/schemas/address' + decimals: + $ref: '#/components/schemas/decimals' + collateral_ratio: + $ref: '#/components/schemas/collateral_ratio' + withdrawal_fee: + $ref: '#/components/schemas/withdrawal_fee' + asset: + type: string + description: Asset name + example: USDC + address: + type: string + description: Address + example: '0x1234567890abcdef1234567890abcdef12345678' + decimals: + type: integer + description: Asset decimals + example: 6 + collateral_ratio: + type: string + description: Collateral ratio + example: '1.00' + withdrawal_fee: + type: string + description: Withdrawal transaction fee in decimalized asset units + example: '5.00' + Error429: + title: Error429 + type: object + required: + - status + - error + properties: + status: + type: string + enum: + - err + error: + $ref: '#/components/schemas/error' + Error500: + title: Error500 + type: object + required: + - status + - error + properties: + status: + type: string + enum: + - err + error: + $ref: '#/components/schemas/error' + error: + type: string + description: >- + Error identifier. For domain rejections and transport errors + (`401`/`404`/`429`/`500`) this is a stable, machine-readable snake_case + identifier that is part of the API contract and safe to branch on, e.g. + `insufficient_margin`, `insufficient_balance`, `order_not_found`, + `reduce_only_invalid`, `unauthorized`, `not_found`. For `400` it is a + human-readable validation detail whose wording may change. See the Error + handling guide for the domain identifiers. (Post-only / Fill-or-Kill + outcomes are order statuses such as `post_only_rejected`, not + rejections.) + example: insufficient_margin + responses: + Error429Response: + description: > + Too Many Requests. `error` distinguishes the limit that was hit: + + `ip_rate_limited` (per-IP token bucket), `action_rate_limited` + (per-account + + action rate), or `open_orders_limit` (resting open-order cap). + headers: + Retry-After: + description: > + Whole seconds to wait before retrying. Present only on token-bucket + + rate-limit rejections (`ip_rate_limited` and `action_rate_limited`); + a + + conservative estimate of when enough capacity will have refilled to + + admit the request. Absent on `open_orders_limit`, which is a + capacity + + limit, not a rate limit — waiting does not free order slots; cancel + + resting orders or wait for fills instead. + schema: + type: integer + example: 2 + content: + application/json: + schema: + $ref: '#/components/schemas/Error429' + Error500Response: + description: | + Internal server error. `error` is `internal_error`. + content: + application/json: + schema: + $ref: '#/components/schemas/Error500' + +```` \ No newline at end of file diff --git a/PolymarketDocumentation-main/docs/api-reference/get-credentials.md b/PolymarketDocumentation-main/docs/api-reference/get-credentials.md new file mode 100644 index 00000000..5c30ec5d --- /dev/null +++ b/PolymarketDocumentation-main/docs/api-reference/get-credentials.md @@ -0,0 +1,230 @@ +> ## Documentation Index +> Fetch the complete documentation index at: https://docs.polymarket.com/llms.txt +> Use this file to discover all available pages before exploring further. + +# Get Credentials + +> Get the account ID, address, and proxy keys for the authenticated account. + +Request Weight: **2** + + +## OpenAPI + +````yaml /api-spec/perps-openapi.json get /v1/account/credentials +openapi: 3.0.3 +info: + title: Polymarket Perps HTTP API + version: 1.0.0 + description: HTTP API for Polymarket perpetual trading system. + license: + name: Apache 2.0 + url: https://www.apache.org/licenses/LICENSE-2.0.html +servers: + - url: https://api.perpetuals.polymarket.com + description: Production Perps HTTP API +security: [] +paths: + /v1/account/credentials: + get: + summary: Get Credentials + description: >- + Get the account ID, address, and proxy keys for the authenticated + account. + operationId: getCredentials + responses: + '200': + description: Credentials response. + content: + application/json: + schema: + $ref: '#/components/schemas/Credentials' + '400': + $ref: '#/components/responses/Error400Response' + '401': + $ref: '#/components/responses/Error401Response' + '429': + $ref: '#/components/responses/Error429Response' + '500': + $ref: '#/components/responses/Error500Response' + security: + - polymarket_proxy: [] + polymarket_secret: [] +components: + schemas: + Credentials: + type: object + required: + - address + - keys + properties: + address: + $ref: '#/components/schemas/address' + keys: + type: array + items: + $ref: '#/components/schemas/Key' + address: + type: string + description: Address + example: '0x1234567890abcdef1234567890abcdef12345678' + Key: + type: object + required: + - proxy + - expiry + properties: + proxy: + $ref: '#/components/schemas/proxy' + label: + $ref: '#/components/schemas/label' + expiry: + $ref: '#/components/schemas/expiry' + Error400: + title: Error400 + type: object + required: + - status + - error + properties: + status: + type: string + enum: + - err + error: + $ref: '#/components/schemas/error' + Error401: + title: Error401 + type: object + required: + - status + - error + properties: + status: + type: string + enum: + - err + error: + $ref: '#/components/schemas/error' + Error429: + title: Error429 + type: object + required: + - status + - error + properties: + status: + type: string + enum: + - err + error: + $ref: '#/components/schemas/error' + Error500: + title: Error500 + type: object + required: + - status + - error + properties: + status: + type: string + enum: + - err + error: + $ref: '#/components/schemas/error' + proxy: + type: string + description: Proxy address in hex format + example: '0x70997970C51812dc3A010C7d01b50e0d17dc79C8' + label: + type: string + description: Human-readable label for a proxy key or internal transfer + example: trading-bot + expiry: + type: integer + description: Expiry timestamp in milliseconds + example: 1767225600000 + error: + type: string + description: >- + Error identifier. For domain rejections and transport errors + (`401`/`404`/`429`/`500`) this is a stable, machine-readable snake_case + identifier that is part of the API contract and safe to branch on, e.g. + `insufficient_margin`, `insufficient_balance`, `order_not_found`, + `reduce_only_invalid`, `unauthorized`, `not_found`. For `400` it is a + human-readable validation detail whose wording may change. See the Error + handling guide for the domain identifiers. (Post-only / Fill-or-Kill + outcomes are order statuses such as `post_only_rejected`, not + rejections.) + example: insufficient_margin + responses: + Error400Response: + description: | + Bad request — the request was malformed or failed validation (bad query + parameters, unparseable body, invalid signature, or a domain pre-check). + The `error` field is a human-readable validation detail. + content: + application/json: + schema: + $ref: '#/components/schemas/Error400' + Error401Response: + description: > + Unauthorized — missing or invalid `POLYMARKET-PROXY` / + `POLYMARKET-SECRET` + + credentials. `error` is `unauthorized`. + content: + application/json: + schema: + $ref: '#/components/schemas/Error401' + Error429Response: + description: > + Too Many Requests. `error` distinguishes the limit that was hit: + + `ip_rate_limited` (per-IP token bucket), `action_rate_limited` + (per-account + + action rate), or `open_orders_limit` (resting open-order cap). + headers: + Retry-After: + description: > + Whole seconds to wait before retrying. Present only on token-bucket + + rate-limit rejections (`ip_rate_limited` and `action_rate_limited`); + a + + conservative estimate of when enough capacity will have refilled to + + admit the request. Absent on `open_orders_limit`, which is a + capacity + + limit, not a rate limit — waiting does not free order slots; cancel + + resting orders or wait for fills instead. + schema: + type: integer + example: 2 + content: + application/json: + schema: + $ref: '#/components/schemas/Error429' + Error500Response: + description: | + Internal server error. `error` is `internal_error`. + content: + application/json: + schema: + $ref: '#/components/schemas/Error500' + securitySchemes: + polymarket_proxy: + type: apiKey + name: POLYMARKET-PROXY + in: header + description: Proxy address + polymarket_secret: + type: apiKey + name: POLYMARKET-SECRET + in: header + description: Correponding proxy secret + +```` \ No newline at end of file diff --git a/PolymarketDocumentation-main/docs/api-reference/get-deposits.md b/PolymarketDocumentation-main/docs/api-reference/get-deposits.md new file mode 100644 index 00000000..4a700bf6 --- /dev/null +++ b/PolymarketDocumentation-main/docs/api-reference/get-deposits.md @@ -0,0 +1,318 @@ +> ## Documentation Index +> Fetch the complete documentation index at: https://docs.polymarket.com/llms.txt +> Use this file to discover all available pages before exploring further. + +# Get Deposits + +> Get deposit history for the authenticated account. +If no end time is provided, the current time will be used. +Maximum of 100 entries returned per request. + + +Request Weight: **10** + + +## OpenAPI + +````yaml /api-spec/perps-openapi.json get /v1/account/deposits +openapi: 3.0.3 +info: + title: Polymarket Perps HTTP API + version: 1.0.0 + description: HTTP API for Polymarket perpetual trading system. + license: + name: Apache 2.0 + url: https://www.apache.org/licenses/LICENSE-2.0.html +servers: + - url: https://api.perpetuals.polymarket.com + description: Production Perps HTTP API +security: [] +paths: + /v1/account/deposits: + get: + summary: Get Deposits + description: | + Get deposit history for the authenticated account. + If no end time is provided, the current time will be used. + Maximum of 100 entries returned per request. + operationId: getDeposits + parameters: + - name: deposit_status + in: query + required: false + schema: + $ref: '#/components/schemas/deposit_status' + - name: hash + in: query + required: false + schema: + $ref: '#/components/schemas/hash' + - name: start_timestamp + in: query + required: false + schema: + $ref: '#/components/schemas/start_timestamp' + - name: end_timestamp + in: query + required: false + schema: + $ref: '#/components/schemas/end_timestamp' + responses: + '200': + description: Deposit history response. + content: + application/json: + schema: + $ref: '#/components/schemas/Deposits' + '400': + $ref: '#/components/responses/Error400Response' + '401': + $ref: '#/components/responses/Error401Response' + '429': + $ref: '#/components/responses/Error429Response' + '500': + $ref: '#/components/responses/Error500Response' + security: + - polymarket_proxy: [] + polymarket_secret: [] +components: + schemas: + deposit_status: + type: string + description: Deposit status + enum: + - pending + - confirmed + - removed + hash: + type: string + description: On-chain transaction hash, "0x" if not yet mined + default: 0x + example: '0x1234567890abcdef1234567890abcdef1234567890abcdef1234567890abcdef' + start_timestamp: + type: integer + description: Start timestamp in milliseconds + example: 1767225600000 + end_timestamp: + type: integer + description: End timestamp in milliseconds + example: 1767229200000 + Deposits: + type: object + required: + - data + - more + properties: + data: + type: array + items: + $ref: '#/components/schemas/Deposit' + more: + $ref: '#/components/schemas/more' + Deposit: + type: object + required: + - hash + - asset + - amount + - status + - from + - to + - confirmations + - required_confirmations + - created_timestamp + properties: + hash: + $ref: '#/components/schemas/hash' + asset: + $ref: '#/components/schemas/asset' + amount: + $ref: '#/components/schemas/amount' + from: + $ref: '#/components/schemas/from' + to: + $ref: '#/components/schemas/to' + status: + $ref: '#/components/schemas/deposit_status' + confirmations: + $ref: '#/components/schemas/confirmations' + required_confirmations: + $ref: '#/components/schemas/required_confirmations' + created_timestamp: + $ref: '#/components/schemas/created_timestamp' + confirmed_timestamp: + $ref: '#/components/schemas/confirmed_timestamp' + more: + type: boolean + description: More data available + Error400: + title: Error400 + type: object + required: + - status + - error + properties: + status: + type: string + enum: + - err + error: + $ref: '#/components/schemas/error' + Error401: + title: Error401 + type: object + required: + - status + - error + properties: + status: + type: string + enum: + - err + error: + $ref: '#/components/schemas/error' + Error429: + title: Error429 + type: object + required: + - status + - error + properties: + status: + type: string + enum: + - err + error: + $ref: '#/components/schemas/error' + Error500: + title: Error500 + type: object + required: + - status + - error + properties: + status: + type: string + enum: + - err + error: + $ref: '#/components/schemas/error' + asset: + type: string + description: Asset name + example: USDC + amount: + type: string + description: >- + Raw token amount including decimals. For withdrawals this matches the + uint256 amount in the EIP-712 signature (e.g. "100000000" for 100 USDC + with 6 decimals). + example: '100000000' + from: + type: string + description: Sender address in hex format + example: '0x1234567890abcdef1234567890abcdef12345678' + to: + type: string + description: Destination address in hex format + example: '0x1234567890abcdef1234567890abcdef12345678' + confirmations: + type: integer + description: Number of block confirmations + example: 12 + required_confirmations: + type: integer + description: Required number of block confirmations + example: 12 + created_timestamp: + type: integer + description: Creation timestamp in milliseconds + example: 1767225600000 + confirmed_timestamp: + type: integer + description: Confirmation timestamp in milliseconds + example: 1767225600000 + error: + type: string + description: >- + Error identifier. For domain rejections and transport errors + (`401`/`404`/`429`/`500`) this is a stable, machine-readable snake_case + identifier that is part of the API contract and safe to branch on, e.g. + `insufficient_margin`, `insufficient_balance`, `order_not_found`, + `reduce_only_invalid`, `unauthorized`, `not_found`. For `400` it is a + human-readable validation detail whose wording may change. See the Error + handling guide for the domain identifiers. (Post-only / Fill-or-Kill + outcomes are order statuses such as `post_only_rejected`, not + rejections.) + example: insufficient_margin + responses: + Error400Response: + description: | + Bad request — the request was malformed or failed validation (bad query + parameters, unparseable body, invalid signature, or a domain pre-check). + The `error` field is a human-readable validation detail. + content: + application/json: + schema: + $ref: '#/components/schemas/Error400' + Error401Response: + description: > + Unauthorized — missing or invalid `POLYMARKET-PROXY` / + `POLYMARKET-SECRET` + + credentials. `error` is `unauthorized`. + content: + application/json: + schema: + $ref: '#/components/schemas/Error401' + Error429Response: + description: > + Too Many Requests. `error` distinguishes the limit that was hit: + + `ip_rate_limited` (per-IP token bucket), `action_rate_limited` + (per-account + + action rate), or `open_orders_limit` (resting open-order cap). + headers: + Retry-After: + description: > + Whole seconds to wait before retrying. Present only on token-bucket + + rate-limit rejections (`ip_rate_limited` and `action_rate_limited`); + a + + conservative estimate of when enough capacity will have refilled to + + admit the request. Absent on `open_orders_limit`, which is a + capacity + + limit, not a rate limit — waiting does not free order slots; cancel + + resting orders or wait for fills instead. + schema: + type: integer + example: 2 + content: + application/json: + schema: + $ref: '#/components/schemas/Error429' + Error500Response: + description: | + Internal server error. `error` is `internal_error`. + content: + application/json: + schema: + $ref: '#/components/schemas/Error500' + securitySchemes: + polymarket_proxy: + type: apiKey + name: POLYMARKET-PROXY + in: header + description: Proxy address + polymarket_secret: + type: apiKey + name: POLYMARKET-SECRET + in: header + description: Correponding proxy secret + +```` \ No newline at end of file diff --git a/PolymarketDocumentation-main/docs/api-reference/get-equity.md b/PolymarketDocumentation-main/docs/api-reference/get-equity.md new file mode 100644 index 00000000..66e6fb34 --- /dev/null +++ b/PolymarketDocumentation-main/docs/api-reference/get-equity.md @@ -0,0 +1,255 @@ +> ## Documentation Index +> Fetch the complete documentation index at: https://docs.polymarket.com/llms.txt +> Use this file to discover all available pages before exploring further. + +# Get Equity + +> Get equity history for the authenticated account. +If no end time is provided, the current time will be used. +Maximum of 1000 entries returned per request. + + +Request Weight: **10** + + +## OpenAPI + +````yaml /api-spec/perps-openapi.json get /v1/account/equity +openapi: 3.0.3 +info: + title: Polymarket Perps HTTP API + version: 1.0.0 + description: HTTP API for Polymarket perpetual trading system. + license: + name: Apache 2.0 + url: https://www.apache.org/licenses/LICENSE-2.0.html +servers: + - url: https://api.perpetuals.polymarket.com + description: Production Perps HTTP API +security: [] +paths: + /v1/account/equity: + get: + summary: Get Equity + description: | + Get equity history for the authenticated account. + If no end time is provided, the current time will be used. + Maximum of 1000 entries returned per request. + operationId: getEquityHistory + parameters: + - name: interval + in: query + required: true + schema: + $ref: '#/components/schemas/interval' + - name: start_timestamp + in: query + required: true + schema: + $ref: '#/components/schemas/start_timestamp' + - name: end_timestamp + in: query + required: false + schema: + $ref: '#/components/schemas/end_timestamp' + responses: + '200': + description: Equity history response. + content: + application/json: + schema: + $ref: '#/components/schemas/EquityHistory' + '400': + $ref: '#/components/responses/Error400Response' + '401': + $ref: '#/components/responses/Error401Response' + '429': + $ref: '#/components/responses/Error429Response' + '500': + $ref: '#/components/responses/Error500Response' + security: + - polymarket_proxy: [] + polymarket_secret: [] +components: + schemas: + interval: + type: string + description: Kline interval + enum: + - 1s + - 1m + - 5m + - 15m + - 30m + - 1h + - 4h + - 6h + - 12h + - 1d + - 1w + start_timestamp: + type: integer + description: Start timestamp in milliseconds + example: 1767225600000 + end_timestamp: + type: integer + description: End timestamp in milliseconds + example: 1767229200000 + EquityHistory: + type: object + required: + - data + - more + properties: + data: + type: array + description: | + - `1767225600000` - Timestamp + - `"10000.00"` - Equity + items: + type: array + example: + - 1767225600000 + - '10000.00' + maxItems: 1000 + more: + $ref: '#/components/schemas/more' + more: + type: boolean + description: More data available + Error400: + title: Error400 + type: object + required: + - status + - error + properties: + status: + type: string + enum: + - err + error: + $ref: '#/components/schemas/error' + Error401: + title: Error401 + type: object + required: + - status + - error + properties: + status: + type: string + enum: + - err + error: + $ref: '#/components/schemas/error' + Error429: + title: Error429 + type: object + required: + - status + - error + properties: + status: + type: string + enum: + - err + error: + $ref: '#/components/schemas/error' + Error500: + title: Error500 + type: object + required: + - status + - error + properties: + status: + type: string + enum: + - err + error: + $ref: '#/components/schemas/error' + error: + type: string + description: >- + Error identifier. For domain rejections and transport errors + (`401`/`404`/`429`/`500`) this is a stable, machine-readable snake_case + identifier that is part of the API contract and safe to branch on, e.g. + `insufficient_margin`, `insufficient_balance`, `order_not_found`, + `reduce_only_invalid`, `unauthorized`, `not_found`. For `400` it is a + human-readable validation detail whose wording may change. See the Error + handling guide for the domain identifiers. (Post-only / Fill-or-Kill + outcomes are order statuses such as `post_only_rejected`, not + rejections.) + example: insufficient_margin + responses: + Error400Response: + description: | + Bad request — the request was malformed or failed validation (bad query + parameters, unparseable body, invalid signature, or a domain pre-check). + The `error` field is a human-readable validation detail. + content: + application/json: + schema: + $ref: '#/components/schemas/Error400' + Error401Response: + description: > + Unauthorized — missing or invalid `POLYMARKET-PROXY` / + `POLYMARKET-SECRET` + + credentials. `error` is `unauthorized`. + content: + application/json: + schema: + $ref: '#/components/schemas/Error401' + Error429Response: + description: > + Too Many Requests. `error` distinguishes the limit that was hit: + + `ip_rate_limited` (per-IP token bucket), `action_rate_limited` + (per-account + + action rate), or `open_orders_limit` (resting open-order cap). + headers: + Retry-After: + description: > + Whole seconds to wait before retrying. Present only on token-bucket + + rate-limit rejections (`ip_rate_limited` and `action_rate_limited`); + a + + conservative estimate of when enough capacity will have refilled to + + admit the request. Absent on `open_orders_limit`, which is a + capacity + + limit, not a rate limit — waiting does not free order slots; cancel + + resting orders or wait for fills instead. + schema: + type: integer + example: 2 + content: + application/json: + schema: + $ref: '#/components/schemas/Error429' + Error500Response: + description: | + Internal server error. `error` is `internal_error`. + content: + application/json: + schema: + $ref: '#/components/schemas/Error500' + securitySchemes: + polymarket_proxy: + type: apiKey + name: POLYMARKET-PROXY + in: header + description: Proxy address + polymarket_secret: + type: apiKey + name: POLYMARKET-SECRET + in: header + description: Correponding proxy secret + +```` \ No newline at end of file diff --git a/PolymarketDocumentation-main/docs/api-reference/get-exchange-info.md b/PolymarketDocumentation-main/docs/api-reference/get-exchange-info.md new file mode 100644 index 00000000..109d3dc9 --- /dev/null +++ b/PolymarketDocumentation-main/docs/api-reference/get-exchange-info.md @@ -0,0 +1,161 @@ +> ## Documentation Index +> Fetch the complete documentation index at: https://docs.polymarket.com/llms.txt +> Use this file to discover all available pages before exploring further. + +# Get Exchange Info + +> Get exchange information. + + +Request Weight: **2** + + +## OpenAPI + +````yaml /api-spec/perps-openapi.json get /v1/info/exchange +openapi: 3.0.3 +info: + title: Polymarket Perps HTTP API + version: 1.0.0 + description: HTTP API for Polymarket perpetual trading system. + license: + name: Apache 2.0 + url: https://www.apache.org/licenses/LICENSE-2.0.html +servers: + - url: https://api.perpetuals.polymarket.com + description: Production Perps HTTP API +security: [] +paths: + /v1/info/exchange: + get: + summary: Get Exchange Info + description: | + Get exchange information. + operationId: getExchange + responses: + '200': + description: Successful exchange information response. + content: + application/json: + schema: + $ref: '#/components/schemas/Exchange' + '429': + $ref: '#/components/responses/Error429Response' + '500': + $ref: '#/components/responses/Error500Response' + security: [] +components: + schemas: + Exchange: + type: object + required: + - name + - version + - chain_id + - contract + properties: + name: + $ref: '#/components/schemas/name' + version: + $ref: '#/components/schemas/version' + chain_id: + $ref: '#/components/schemas/chain_id' + contract: + $ref: '#/components/schemas/contract' + name: + type: string + description: Exchange name used in the EIP-712 domain. + example: Polymarket + version: + type: string + description: Exchange version used in the EIP-712 domain. + example: '1' + chain_id: + type: integer + format: uint32 + description: Chain ID of the network the exchange is deployed on. + example: 137 + contract: + type: string + description: Verifying contract address or the EIP-712 domain. + example: '0x1234567890abcdef1234567890abcdef12345678' + Error429: + title: Error429 + type: object + required: + - status + - error + properties: + status: + type: string + enum: + - err + error: + $ref: '#/components/schemas/error' + Error500: + title: Error500 + type: object + required: + - status + - error + properties: + status: + type: string + enum: + - err + error: + $ref: '#/components/schemas/error' + error: + type: string + description: >- + Error identifier. For domain rejections and transport errors + (`401`/`404`/`429`/`500`) this is a stable, machine-readable snake_case + identifier that is part of the API contract and safe to branch on, e.g. + `insufficient_margin`, `insufficient_balance`, `order_not_found`, + `reduce_only_invalid`, `unauthorized`, `not_found`. For `400` it is a + human-readable validation detail whose wording may change. See the Error + handling guide for the domain identifiers. (Post-only / Fill-or-Kill + outcomes are order statuses such as `post_only_rejected`, not + rejections.) + example: insufficient_margin + responses: + Error429Response: + description: > + Too Many Requests. `error` distinguishes the limit that was hit: + + `ip_rate_limited` (per-IP token bucket), `action_rate_limited` + (per-account + + action rate), or `open_orders_limit` (resting open-order cap). + headers: + Retry-After: + description: > + Whole seconds to wait before retrying. Present only on token-bucket + + rate-limit rejections (`ip_rate_limited` and `action_rate_limited`); + a + + conservative estimate of when enough capacity will have refilled to + + admit the request. Absent on `open_orders_limit`, which is a + capacity + + limit, not a rate limit — waiting does not free order slots; cancel + + resting orders or wait for fills instead. + schema: + type: integer + example: 2 + content: + application/json: + schema: + $ref: '#/components/schemas/Error429' + Error500Response: + description: | + Internal server error. `error` is `internal_error`. + content: + application/json: + schema: + $ref: '#/components/schemas/Error500' + +```` \ No newline at end of file diff --git a/PolymarketDocumentation-main/docs/api-reference/get-fees.md b/PolymarketDocumentation-main/docs/api-reference/get-fees.md new file mode 100644 index 00000000..b5e4e203 --- /dev/null +++ b/PolymarketDocumentation-main/docs/api-reference/get-fees.md @@ -0,0 +1,179 @@ +> ## Documentation Index +> Fetch the complete documentation index at: https://docs.polymarket.com/llms.txt +> Use this file to discover all available pages before exploring further. + +# Get Fees + +> Get the default fee schedule for each instrument type and category. Rates returned are the $0-tier defaults; the account's actual rate on each fill depends on its trailing 30-day volume tier. + +Request Weight: **2** + + +## OpenAPI + +````yaml /api-spec/perps-openapi.json get /v1/info/fees +openapi: 3.0.3 +info: + title: Polymarket Perps HTTP API + version: 1.0.0 + description: HTTP API for Polymarket perpetual trading system. + license: + name: Apache 2.0 + url: https://www.apache.org/licenses/LICENSE-2.0.html +servers: + - url: https://api.perpetuals.polymarket.com + description: Production Perps HTTP API +security: [] +paths: + /v1/info/fees: + get: + summary: Get Fees + description: >- + Get the default fee schedule for each instrument type and category. + Rates returned are the $0-tier defaults; the account's actual rate on + each fill depends on its trailing 30-day volume tier. + operationId: getInfoFees + responses: + '200': + description: Fee schedule response. + content: + application/json: + schema: + $ref: '#/components/schemas/FeesInfo' + '429': + $ref: '#/components/responses/Error429Response' + '500': + $ref: '#/components/responses/Error500Response' + security: [] +components: + schemas: + FeesInfo: + type: object + required: + - fee_schedule + properties: + fee_schedule: + type: array + items: + $ref: '#/components/schemas/FeeScheduleEntry' + FeeScheduleEntry: + type: object + required: + - instrument_type + - category + - taker_fee_rate + - maker_fee_rate + properties: + instrument_type: + $ref: '#/components/schemas/instrument_type' + category: + $ref: '#/components/schemas/category' + taker_fee_rate: + $ref: '#/components/schemas/taker_fee_rate' + maker_fee_rate: + $ref: '#/components/schemas/maker_fee_rate' + Error429: + title: Error429 + type: object + required: + - status + - error + properties: + status: + type: string + enum: + - err + error: + $ref: '#/components/schemas/error' + Error500: + title: Error500 + type: object + required: + - status + - error + properties: + status: + type: string + enum: + - err + error: + $ref: '#/components/schemas/error' + instrument_type: + type: string + description: Instrument type + enum: + - perpetual + category: + type: string + description: Instrument category + enum: + - equity + - commodity + - index + - crypto + taker_fee_rate: + type: string + description: >- + Default taker fee rate for the $0 volume tier. Actual rate scales down + with the account's trailing 30-day volume tier. + example: '0.0004' + maker_fee_rate: + type: string + description: >- + Default maker fee rate for the $0 volume tier. Positive at lower tiers, + zero at the $500M tier, and a rebate (negative) at the top tier. + example: '0.000125' + error: + type: string + description: >- + Error identifier. For domain rejections and transport errors + (`401`/`404`/`429`/`500`) this is a stable, machine-readable snake_case + identifier that is part of the API contract and safe to branch on, e.g. + `insufficient_margin`, `insufficient_balance`, `order_not_found`, + `reduce_only_invalid`, `unauthorized`, `not_found`. For `400` it is a + human-readable validation detail whose wording may change. See the Error + handling guide for the domain identifiers. (Post-only / Fill-or-Kill + outcomes are order statuses such as `post_only_rejected`, not + rejections.) + example: insufficient_margin + responses: + Error429Response: + description: > + Too Many Requests. `error` distinguishes the limit that was hit: + + `ip_rate_limited` (per-IP token bucket), `action_rate_limited` + (per-account + + action rate), or `open_orders_limit` (resting open-order cap). + headers: + Retry-After: + description: > + Whole seconds to wait before retrying. Present only on token-bucket + + rate-limit rejections (`ip_rate_limited` and `action_rate_limited`); + a + + conservative estimate of when enough capacity will have refilled to + + admit the request. Absent on `open_orders_limit`, which is a + capacity + + limit, not a rate limit — waiting does not free order slots; cancel + + resting orders or wait for fills instead. + schema: + type: integer + example: 2 + content: + application/json: + schema: + $ref: '#/components/schemas/Error429' + Error500Response: + description: | + Internal server error. `error` is `internal_error`. + content: + application/json: + schema: + $ref: '#/components/schemas/Error500' + +```` \ No newline at end of file diff --git a/PolymarketDocumentation-main/docs/api-reference/get-fills.md b/PolymarketDocumentation-main/docs/api-reference/get-fills.md new file mode 100644 index 00000000..5f5fad95 --- /dev/null +++ b/PolymarketDocumentation-main/docs/api-reference/get-fills.md @@ -0,0 +1,342 @@ +> ## Documentation Index +> Fetch the complete documentation index at: https://docs.polymarket.com/llms.txt +> Use this file to discover all available pages before exploring further. + +# Get Fills + +> Get fill history for the authenticated account. +If no end time is provided, the current time will be used. +Maximum of 100 entries returned per request. + + +Request Weight: **10** + + +## OpenAPI + +````yaml /api-spec/perps-openapi.json get /v1/account/fills +openapi: 3.0.3 +info: + title: Polymarket Perps HTTP API + version: 1.0.0 + description: HTTP API for Polymarket perpetual trading system. + license: + name: Apache 2.0 + url: https://www.apache.org/licenses/LICENSE-2.0.html +servers: + - url: https://api.perpetuals.polymarket.com + description: Production Perps HTTP API +security: [] +paths: + /v1/account/fills: + get: + summary: Get Fills + description: | + Get fill history for the authenticated account. + If no end time is provided, the current time will be used. + Maximum of 100 entries returned per request. + operationId: getFills + parameters: + - name: start_timestamp + in: query + required: false + schema: + $ref: '#/components/schemas/start_timestamp' + - name: end_timestamp + in: query + required: false + schema: + $ref: '#/components/schemas/end_timestamp' + responses: + '200': + description: Fills response. + content: + application/json: + schema: + $ref: '#/components/schemas/AccountTrades' + '400': + $ref: '#/components/responses/Error400Response' + '401': + $ref: '#/components/responses/Error401Response' + '429': + $ref: '#/components/responses/Error429Response' + '500': + $ref: '#/components/responses/Error500Response' + security: + - polymarket_proxy: [] + polymarket_secret: [] +components: + schemas: + start_timestamp: + type: integer + description: Start timestamp in milliseconds + example: 1767225600000 + end_timestamp: + type: integer + description: End timestamp in milliseconds + example: 1767229200000 + AccountTrades: + type: object + required: + - data + - more + properties: + data: + type: array + items: + $ref: '#/components/schemas/AccountTradeData' + description: Account's trade history + more: + $ref: '#/components/schemas/more' + AccountTradeData: + type: object + required: + - trade_id + - order_id + - instrument_id + - side + - price + - quantity + - taker + - fee + - fee_asset + - previous_size + - previous_entry_price + - pnl + - timestamp + - liquidation + - hash + properties: + trade_id: + $ref: '#/components/schemas/tid' + order_id: + $ref: '#/components/schemas/oid' + instrument_id: + $ref: '#/components/schemas/iid' + side: + $ref: '#/components/schemas/side' + price: + $ref: '#/components/schemas/p' + quantity: + $ref: '#/components/schemas/qty' + taker: + $ref: '#/components/schemas/taker' + fee: + $ref: '#/components/schemas/fee' + fee_asset: + $ref: '#/components/schemas/fea' + previous_size: + $ref: '#/components/schemas/psz' + previous_entry_price: + $ref: '#/components/schemas/pep' + pnl: + $ref: '#/components/schemas/pnl' + liquidation: + $ref: '#/components/schemas/liq' + timestamp: + $ref: '#/components/schemas/ts' + hash: + $ref: '#/components/schemas/hash' + more: + type: boolean + description: More data available + Error400: + title: Error400 + type: object + required: + - status + - error + properties: + status: + type: string + enum: + - err + error: + $ref: '#/components/schemas/error' + Error401: + title: Error401 + type: object + required: + - status + - error + properties: + status: + type: string + enum: + - err + error: + $ref: '#/components/schemas/error' + Error429: + title: Error429 + type: object + required: + - status + - error + properties: + status: + type: string + enum: + - err + error: + $ref: '#/components/schemas/error' + Error500: + title: Error500 + type: object + required: + - status + - error + properties: + status: + type: string + enum: + - err + error: + $ref: '#/components/schemas/error' + tid: + type: integer + description: Trade ID + example: 1 + oid: + type: integer + description: Order ID + example: 1234567890 + iid: + type: integer + description: Instrument ID + example: 1 + side: + type: string + description: Side + enum: + - long + - short + p: + type: string + description: Price + example: '100.00' + qty: + type: string + description: Quantity in no. of contracts + example: '10.00' + taker: + type: boolean + description: Whether this side was the taker + fee: + type: string + description: Fee amount for this trade side + example: '1.25' + fea: + type: string + description: Fee asset name + example: USDC + psz: + type: string + description: Position size before the fill + example: '26.86' + pep: + type: string + description: Position entry price before the fill + example: '100.00' + pnl: + type: string + description: PnL in USD + example: '100.00' + liq: + type: boolean + description: Whether the fill was a liquidation + ts: + type: integer + description: >- + Request timestamp. Unix milliseconds for most operations; Unix seconds + for withdrawals (must match the on-chain EIP-712 struct verified against + block.timestamp). + example: 1767225600000 + hash: + type: string + description: On-chain transaction hash, "0x" if not yet mined + default: 0x + example: '0x1234567890abcdef1234567890abcdef1234567890abcdef1234567890abcdef' + error: + type: string + description: >- + Error identifier. For domain rejections and transport errors + (`401`/`404`/`429`/`500`) this is a stable, machine-readable snake_case + identifier that is part of the API contract and safe to branch on, e.g. + `insufficient_margin`, `insufficient_balance`, `order_not_found`, + `reduce_only_invalid`, `unauthorized`, `not_found`. For `400` it is a + human-readable validation detail whose wording may change. See the Error + handling guide for the domain identifiers. (Post-only / Fill-or-Kill + outcomes are order statuses such as `post_only_rejected`, not + rejections.) + example: insufficient_margin + responses: + Error400Response: + description: | + Bad request — the request was malformed or failed validation (bad query + parameters, unparseable body, invalid signature, or a domain pre-check). + The `error` field is a human-readable validation detail. + content: + application/json: + schema: + $ref: '#/components/schemas/Error400' + Error401Response: + description: > + Unauthorized — missing or invalid `POLYMARKET-PROXY` / + `POLYMARKET-SECRET` + + credentials. `error` is `unauthorized`. + content: + application/json: + schema: + $ref: '#/components/schemas/Error401' + Error429Response: + description: > + Too Many Requests. `error` distinguishes the limit that was hit: + + `ip_rate_limited` (per-IP token bucket), `action_rate_limited` + (per-account + + action rate), or `open_orders_limit` (resting open-order cap). + headers: + Retry-After: + description: > + Whole seconds to wait before retrying. Present only on token-bucket + + rate-limit rejections (`ip_rate_limited` and `action_rate_limited`); + a + + conservative estimate of when enough capacity will have refilled to + + admit the request. Absent on `open_orders_limit`, which is a + capacity + + limit, not a rate limit — waiting does not free order slots; cancel + + resting orders or wait for fills instead. + schema: + type: integer + example: 2 + content: + application/json: + schema: + $ref: '#/components/schemas/Error429' + Error500Response: + description: | + Internal server error. `error` is `internal_error`. + content: + application/json: + schema: + $ref: '#/components/schemas/Error500' + securitySchemes: + polymarket_proxy: + type: apiKey + name: POLYMARKET-PROXY + in: header + description: Proxy address + polymarket_secret: + type: apiKey + name: POLYMARKET-SECRET + in: header + description: Correponding proxy secret + +```` \ No newline at end of file diff --git a/PolymarketDocumentation-main/docs/api-reference/get-funding-charges.md b/PolymarketDocumentation-main/docs/api-reference/get-funding-charges.md new file mode 100644 index 00000000..566eeec3 --- /dev/null +++ b/PolymarketDocumentation-main/docs/api-reference/get-funding-charges.md @@ -0,0 +1,287 @@ +> ## Documentation Index +> Fetch the complete documentation index at: https://docs.polymarket.com/llms.txt +> Use this file to discover all available pages before exploring further. + +# Get Funding Charges + +> Get funding payment history for the authenticated account. +If no end time is provided, the current time will be used. +Maximum of 100 entries returned per request. + + +Request Weight: **10** + + +## OpenAPI + +````yaml /api-spec/perps-openapi.json get /v1/account/funding +openapi: 3.0.3 +info: + title: Polymarket Perps HTTP API + version: 1.0.0 + description: HTTP API for Polymarket perpetual trading system. + license: + name: Apache 2.0 + url: https://www.apache.org/licenses/LICENSE-2.0.html +servers: + - url: https://api.perpetuals.polymarket.com + description: Production Perps HTTP API +security: [] +paths: + /v1/account/funding: + get: + summary: Get Funding Charges + description: | + Get funding payment history for the authenticated account. + If no end time is provided, the current time will be used. + Maximum of 100 entries returned per request. + operationId: getAccountFunding + parameters: + - name: instrument_id + in: query + required: false + schema: + $ref: '#/components/schemas/instrument_id' + - name: start_timestamp + in: query + required: false + schema: + $ref: '#/components/schemas/start_timestamp' + - name: end_timestamp + in: query + required: false + schema: + $ref: '#/components/schemas/end_timestamp' + responses: + '200': + description: Account funding history response. + content: + application/json: + schema: + $ref: '#/components/schemas/AccountFundingHistory' + '400': + $ref: '#/components/responses/Error400Response' + '401': + $ref: '#/components/responses/Error401Response' + '429': + $ref: '#/components/responses/Error429Response' + '500': + $ref: '#/components/responses/Error500Response' + security: + - polymarket_proxy: [] + polymarket_secret: [] +components: + schemas: + instrument_id: + type: integer + description: Instrument ID + start_timestamp: + type: integer + description: Start timestamp in milliseconds + example: 1767225600000 + end_timestamp: + type: integer + description: End timestamp in milliseconds + example: 1767229200000 + AccountFundingHistory: + type: object + required: + - data + - more + properties: + data: + type: array + items: + $ref: '#/components/schemas/AccountFundingData' + more: + $ref: '#/components/schemas/more' + AccountFundingData: + type: object + required: + - instrument_id + - size + - funding_rate + - funding_asset + - funding + - timestamp + properties: + instrument_id: + $ref: '#/components/schemas/iid' + size: + $ref: '#/components/schemas/sz' + funding_rate: + $ref: '#/components/schemas/fr' + funding_asset: + $ref: '#/components/schemas/fua' + funding: + $ref: '#/components/schemas/fund' + timestamp: + $ref: '#/components/schemas/ts' + more: + type: boolean + description: More data available + Error400: + title: Error400 + type: object + required: + - status + - error + properties: + status: + type: string + enum: + - err + error: + $ref: '#/components/schemas/error' + Error401: + title: Error401 + type: object + required: + - status + - error + properties: + status: + type: string + enum: + - err + error: + $ref: '#/components/schemas/error' + Error429: + title: Error429 + type: object + required: + - status + - error + properties: + status: + type: string + enum: + - err + error: + $ref: '#/components/schemas/error' + Error500: + title: Error500 + type: object + required: + - status + - error + properties: + status: + type: string + enum: + - err + error: + $ref: '#/components/schemas/error' + iid: + type: integer + description: Instrument ID + example: 1 + sz: + type: string + description: >- + Signed position size in no. of contracts (positive = long, negative = + short) + example: '10.00' + fr: + type: string + description: Funding rate + example: '0.0001' + fua: + type: string + description: Funding asset name + example: USDC + fund: + type: string + description: Funding paid in USD + example: '1.00' + ts: + type: integer + description: >- + Request timestamp. Unix milliseconds for most operations; Unix seconds + for withdrawals (must match the on-chain EIP-712 struct verified against + block.timestamp). + example: 1767225600000 + error: + type: string + description: >- + Error identifier. For domain rejections and transport errors + (`401`/`404`/`429`/`500`) this is a stable, machine-readable snake_case + identifier that is part of the API contract and safe to branch on, e.g. + `insufficient_margin`, `insufficient_balance`, `order_not_found`, + `reduce_only_invalid`, `unauthorized`, `not_found`. For `400` it is a + human-readable validation detail whose wording may change. See the Error + handling guide for the domain identifiers. (Post-only / Fill-or-Kill + outcomes are order statuses such as `post_only_rejected`, not + rejections.) + example: insufficient_margin + responses: + Error400Response: + description: | + Bad request — the request was malformed or failed validation (bad query + parameters, unparseable body, invalid signature, or a domain pre-check). + The `error` field is a human-readable validation detail. + content: + application/json: + schema: + $ref: '#/components/schemas/Error400' + Error401Response: + description: > + Unauthorized — missing or invalid `POLYMARKET-PROXY` / + `POLYMARKET-SECRET` + + credentials. `error` is `unauthorized`. + content: + application/json: + schema: + $ref: '#/components/schemas/Error401' + Error429Response: + description: > + Too Many Requests. `error` distinguishes the limit that was hit: + + `ip_rate_limited` (per-IP token bucket), `action_rate_limited` + (per-account + + action rate), or `open_orders_limit` (resting open-order cap). + headers: + Retry-After: + description: > + Whole seconds to wait before retrying. Present only on token-bucket + + rate-limit rejections (`ip_rate_limited` and `action_rate_limited`); + a + + conservative estimate of when enough capacity will have refilled to + + admit the request. Absent on `open_orders_limit`, which is a + capacity + + limit, not a rate limit — waiting does not free order slots; cancel + + resting orders or wait for fills instead. + schema: + type: integer + example: 2 + content: + application/json: + schema: + $ref: '#/components/schemas/Error429' + Error500Response: + description: | + Internal server error. `error` is `internal_error`. + content: + application/json: + schema: + $ref: '#/components/schemas/Error500' + securitySchemes: + polymarket_proxy: + type: apiKey + name: POLYMARKET-PROXY + in: header + description: Proxy address + polymarket_secret: + type: apiKey + name: POLYMARKET-SECRET + in: header + description: Correponding proxy secret + +```` \ No newline at end of file diff --git a/PolymarketDocumentation-main/docs/api-reference/get-historical-funding.md b/PolymarketDocumentation-main/docs/api-reference/get-historical-funding.md new file mode 100644 index 00000000..a6ee0bcd --- /dev/null +++ b/PolymarketDocumentation-main/docs/api-reference/get-historical-funding.md @@ -0,0 +1,217 @@ +> ## Documentation Index +> Fetch the complete documentation index at: https://docs.polymarket.com/llms.txt +> Use this file to discover all available pages before exploring further. + +# Get Historical Funding + +> Get public funding rate history for an instrument. +Maximum of 100 entries returned per request. + + +Request Weight: **10** + + +## OpenAPI + +````yaml /api-spec/perps-openapi.json get /v1/info/funding +openapi: 3.0.3 +info: + title: Polymarket Perps HTTP API + version: 1.0.0 + description: HTTP API for Polymarket perpetual trading system. + license: + name: Apache 2.0 + url: https://www.apache.org/licenses/LICENSE-2.0.html +servers: + - url: https://api.perpetuals.polymarket.com + description: Production Perps HTTP API +security: [] +paths: + /v1/info/funding: + get: + summary: Get Historical Funding + description: | + Get public funding rate history for an instrument. + Maximum of 100 entries returned per request. + operationId: getFundingHistory + parameters: + - name: instrument_id + in: query + required: true + schema: + $ref: '#/components/schemas/instrument_id' + - name: start_timestamp + in: query + required: false + schema: + $ref: '#/components/schemas/start_timestamp' + - name: end_timestamp + in: query + required: false + schema: + $ref: '#/components/schemas/end_timestamp' + responses: + '200': + description: Funding rate history response. + content: + application/json: + schema: + $ref: '#/components/schemas/FundingHistory' + '400': + $ref: '#/components/responses/Error400Response' + '429': + $ref: '#/components/responses/Error429Response' + '500': + $ref: '#/components/responses/Error500Response' + security: [] +components: + schemas: + instrument_id: + type: integer + description: Instrument ID + start_timestamp: + type: integer + description: Start timestamp in milliseconds + example: 1767225600000 + end_timestamp: + type: integer + description: End timestamp in milliseconds + example: 1767229200000 + FundingHistory: + type: object + required: + - data + - more + properties: + data: + type: array + items: + $ref: '#/components/schemas/FundingRate' + more: + $ref: '#/components/schemas/more' + FundingRate: + type: object + required: + - funding_rate + - timestamp + properties: + funding_rate: + $ref: '#/components/schemas/fr' + timestamp: + $ref: '#/components/schemas/ts' + more: + type: boolean + description: More data available + Error400: + title: Error400 + type: object + required: + - status + - error + properties: + status: + type: string + enum: + - err + error: + $ref: '#/components/schemas/error' + Error429: + title: Error429 + type: object + required: + - status + - error + properties: + status: + type: string + enum: + - err + error: + $ref: '#/components/schemas/error' + Error500: + title: Error500 + type: object + required: + - status + - error + properties: + status: + type: string + enum: + - err + error: + $ref: '#/components/schemas/error' + fr: + type: string + description: Funding rate + example: '0.0001' + ts: + type: integer + description: >- + Request timestamp. Unix milliseconds for most operations; Unix seconds + for withdrawals (must match the on-chain EIP-712 struct verified against + block.timestamp). + example: 1767225600000 + error: + type: string + description: >- + Error identifier. For domain rejections and transport errors + (`401`/`404`/`429`/`500`) this is a stable, machine-readable snake_case + identifier that is part of the API contract and safe to branch on, e.g. + `insufficient_margin`, `insufficient_balance`, `order_not_found`, + `reduce_only_invalid`, `unauthorized`, `not_found`. For `400` it is a + human-readable validation detail whose wording may change. See the Error + handling guide for the domain identifiers. (Post-only / Fill-or-Kill + outcomes are order statuses such as `post_only_rejected`, not + rejections.) + example: insufficient_margin + responses: + Error400Response: + description: | + Bad request — the request was malformed or failed validation (bad query + parameters, unparseable body, invalid signature, or a domain pre-check). + The `error` field is a human-readable validation detail. + content: + application/json: + schema: + $ref: '#/components/schemas/Error400' + Error429Response: + description: > + Too Many Requests. `error` distinguishes the limit that was hit: + + `ip_rate_limited` (per-IP token bucket), `action_rate_limited` + (per-account + + action rate), or `open_orders_limit` (resting open-order cap). + headers: + Retry-After: + description: > + Whole seconds to wait before retrying. Present only on token-bucket + + rate-limit rejections (`ip_rate_limited` and `action_rate_limited`); + a + + conservative estimate of when enough capacity will have refilled to + + admit the request. Absent on `open_orders_limit`, which is a + capacity + + limit, not a rate limit — waiting does not free order slots; cancel + + resting orders or wait for fills instead. + schema: + type: integer + example: 2 + content: + application/json: + schema: + $ref: '#/components/schemas/Error429' + Error500Response: + description: | + Internal server error. `error` is `internal_error`. + content: + application/json: + schema: + $ref: '#/components/schemas/Error500' + +```` \ No newline at end of file diff --git a/PolymarketDocumentation-main/docs/api-reference/get-index.md b/PolymarketDocumentation-main/docs/api-reference/get-index.md new file mode 100644 index 00000000..fbea083f --- /dev/null +++ b/PolymarketDocumentation-main/docs/api-reference/get-index.md @@ -0,0 +1,233 @@ +> ## Documentation Index +> Fetch the complete documentation index at: https://docs.polymarket.com/llms.txt +> Use this file to discover all available pages before exploring further. + +# Get Index + +> Get index price and the list of constituents for an asset. + +Request Weight: **2** + + +## OpenAPI + +````yaml /api-spec/perps-openapi.json get /v1/info/index +openapi: 3.0.3 +info: + title: Polymarket Perps HTTP API + version: 1.0.0 + description: HTTP API for Polymarket perpetual trading system. + license: + name: Apache 2.0 + url: https://www.apache.org/licenses/LICENSE-2.0.html +servers: + - url: https://api.perpetuals.polymarket.com + description: Production Perps HTTP API +security: [] +paths: + /v1/info/index: + get: + summary: Get Index + description: Get index price and the list of constituents for an asset. + operationId: getIndex + parameters: + - name: asset + in: query + required: true + schema: + $ref: '#/components/schemas/asset' + responses: + '200': + description: Index constituents response. + content: + application/json: + schema: + $ref: '#/components/schemas/Index' + examples: + index: + summary: Index constituents + value: + asset: NVDA + index_price: '160.00' + constituents: + - source: chainlink + symbol: NVDA/USD + weight: '1.0' + price: '160.00' + ts: 1767225600000 + '400': + $ref: '#/components/responses/Error400Response' + '429': + $ref: '#/components/responses/Error429Response' + '500': + $ref: '#/components/responses/Error500Response' + security: [] +components: + schemas: + asset: + type: string + description: Asset name + example: USDC + Index: + type: object + required: + - asset + - index_price + - constituents + - ts + properties: + asset: + $ref: '#/components/schemas/asset' + index_price: + $ref: '#/components/schemas/index_price' + constituents: + type: array + items: + $ref: '#/components/schemas/IndexConstituent' + ts: + $ref: '#/components/schemas/ts' + index_price: + type: string + description: Index price + example: '100.00' + IndexConstituent: + type: object + required: + - source + - symbol + - weight + - price + properties: + source: + $ref: '#/components/schemas/source' + symbol: + $ref: '#/components/schemas/symbol' + weight: + $ref: '#/components/schemas/weight' + price: + $ref: '#/components/schemas/price' + ts: + type: integer + description: >- + Request timestamp. Unix milliseconds for most operations; Unix seconds + for withdrawals (must match the on-chain EIP-712 struct verified against + block.timestamp). + example: 1767225600000 + Error400: + title: Error400 + type: object + required: + - status + - error + properties: + status: + type: string + enum: + - err + error: + $ref: '#/components/schemas/error' + Error429: + title: Error429 + type: object + required: + - status + - error + properties: + status: + type: string + enum: + - err + error: + $ref: '#/components/schemas/error' + Error500: + title: Error500 + type: object + required: + - status + - error + properties: + status: + type: string + enum: + - err + error: + $ref: '#/components/schemas/error' + source: + type: string + description: Source name + example: chainlink + symbol: + type: string + description: Instrument symbol + example: NVDA-USDC + weight: + type: string + description: Index constituent weight + example: '0.25' + price: + type: string + description: Price + example: '100.00' + error: + type: string + description: >- + Error identifier. For domain rejections and transport errors + (`401`/`404`/`429`/`500`) this is a stable, machine-readable snake_case + identifier that is part of the API contract and safe to branch on, e.g. + `insufficient_margin`, `insufficient_balance`, `order_not_found`, + `reduce_only_invalid`, `unauthorized`, `not_found`. For `400` it is a + human-readable validation detail whose wording may change. See the Error + handling guide for the domain identifiers. (Post-only / Fill-or-Kill + outcomes are order statuses such as `post_only_rejected`, not + rejections.) + example: insufficient_margin + responses: + Error400Response: + description: | + Bad request — the request was malformed or failed validation (bad query + parameters, unparseable body, invalid signature, or a domain pre-check). + The `error` field is a human-readable validation detail. + content: + application/json: + schema: + $ref: '#/components/schemas/Error400' + Error429Response: + description: > + Too Many Requests. `error` distinguishes the limit that was hit: + + `ip_rate_limited` (per-IP token bucket), `action_rate_limited` + (per-account + + action rate), or `open_orders_limit` (resting open-order cap). + headers: + Retry-After: + description: > + Whole seconds to wait before retrying. Present only on token-bucket + + rate-limit rejections (`ip_rate_limited` and `action_rate_limited`); + a + + conservative estimate of when enough capacity will have refilled to + + admit the request. Absent on `open_orders_limit`, which is a + capacity + + limit, not a rate limit — waiting does not free order slots; cancel + + resting orders or wait for fills instead. + schema: + type: integer + example: 2 + content: + application/json: + schema: + $ref: '#/components/schemas/Error429' + Error500Response: + description: | + Internal server error. `error` is `internal_error`. + content: + application/json: + schema: + $ref: '#/components/schemas/Error500' + +```` \ No newline at end of file diff --git a/PolymarketDocumentation-main/docs/api-reference/get-instrument-config.md b/PolymarketDocumentation-main/docs/api-reference/get-instrument-config.md new file mode 100644 index 00000000..c6cac462 --- /dev/null +++ b/PolymarketDocumentation-main/docs/api-reference/get-instrument-config.md @@ -0,0 +1,226 @@ +> ## Documentation Index +> Fetch the complete documentation index at: https://docs.polymarket.com/llms.txt +> Use this file to discover all available pages before exploring further. + +# Get Instrument Config + +> Get per-instrument configuration (leverage and margin mode) for the authenticated account. + +Request Weight: **2** + + +## OpenAPI + +````yaml /api-spec/perps-openapi.json get /v1/account/config +openapi: 3.0.3 +info: + title: Polymarket Perps HTTP API + version: 1.0.0 + description: HTTP API for Polymarket perpetual trading system. + license: + name: Apache 2.0 + url: https://www.apache.org/licenses/LICENSE-2.0.html +servers: + - url: https://api.perpetuals.polymarket.com + description: Production Perps HTTP API +security: [] +paths: + /v1/account/config: + get: + summary: Get Instrument Config + description: >- + Get per-instrument configuration (leverage and margin mode) for the + authenticated account. + operationId: getConfig + parameters: + - name: instrument_id + in: query + required: false + schema: + $ref: '#/components/schemas/instrument_id' + responses: + '200': + description: Instrument config response. + content: + application/json: + schema: + type: array + items: + $ref: '#/components/schemas/AccountConfig' + '400': + $ref: '#/components/responses/Error400Response' + '401': + $ref: '#/components/responses/Error401Response' + '429': + $ref: '#/components/responses/Error429Response' + '500': + $ref: '#/components/responses/Error500Response' + security: + - polymarket_proxy: [] + polymarket_secret: [] +components: + schemas: + instrument_id: + type: integer + description: Instrument ID + AccountConfig: + description: Account configuration. + type: object + required: + - instrument_id + - leverage + - cross + properties: + instrument_id: + $ref: '#/components/schemas/iid' + leverage: + $ref: '#/components/schemas/lev' + cross: + $ref: '#/components/schemas/cross' + iid: + type: integer + description: Instrument ID + example: 1 + lev: + type: integer + description: Leverage + example: 10 + cross: + type: boolean + description: Whether to use cross margin mode + Error400: + title: Error400 + type: object + required: + - status + - error + properties: + status: + type: string + enum: + - err + error: + $ref: '#/components/schemas/error' + Error401: + title: Error401 + type: object + required: + - status + - error + properties: + status: + type: string + enum: + - err + error: + $ref: '#/components/schemas/error' + Error429: + title: Error429 + type: object + required: + - status + - error + properties: + status: + type: string + enum: + - err + error: + $ref: '#/components/schemas/error' + Error500: + title: Error500 + type: object + required: + - status + - error + properties: + status: + type: string + enum: + - err + error: + $ref: '#/components/schemas/error' + error: + type: string + description: >- + Error identifier. For domain rejections and transport errors + (`401`/`404`/`429`/`500`) this is a stable, machine-readable snake_case + identifier that is part of the API contract and safe to branch on, e.g. + `insufficient_margin`, `insufficient_balance`, `order_not_found`, + `reduce_only_invalid`, `unauthorized`, `not_found`. For `400` it is a + human-readable validation detail whose wording may change. See the Error + handling guide for the domain identifiers. (Post-only / Fill-or-Kill + outcomes are order statuses such as `post_only_rejected`, not + rejections.) + example: insufficient_margin + responses: + Error400Response: + description: | + Bad request — the request was malformed or failed validation (bad query + parameters, unparseable body, invalid signature, or a domain pre-check). + The `error` field is a human-readable validation detail. + content: + application/json: + schema: + $ref: '#/components/schemas/Error400' + Error401Response: + description: > + Unauthorized — missing or invalid `POLYMARKET-PROXY` / + `POLYMARKET-SECRET` + + credentials. `error` is `unauthorized`. + content: + application/json: + schema: + $ref: '#/components/schemas/Error401' + Error429Response: + description: > + Too Many Requests. `error` distinguishes the limit that was hit: + + `ip_rate_limited` (per-IP token bucket), `action_rate_limited` + (per-account + + action rate), or `open_orders_limit` (resting open-order cap). + headers: + Retry-After: + description: > + Whole seconds to wait before retrying. Present only on token-bucket + + rate-limit rejections (`ip_rate_limited` and `action_rate_limited`); + a + + conservative estimate of when enough capacity will have refilled to + + admit the request. Absent on `open_orders_limit`, which is a + capacity + + limit, not a rate limit — waiting does not free order slots; cancel + + resting orders or wait for fills instead. + schema: + type: integer + example: 2 + content: + application/json: + schema: + $ref: '#/components/schemas/Error429' + Error500Response: + description: | + Internal server error. `error` is `internal_error`. + content: + application/json: + schema: + $ref: '#/components/schemas/Error500' + securitySchemes: + polymarket_proxy: + type: apiKey + name: POLYMARKET-PROXY + in: header + description: Proxy address + polymarket_secret: + type: apiKey + name: POLYMARKET-SECRET + in: header + description: Correponding proxy secret + +```` \ No newline at end of file diff --git a/PolymarketDocumentation-main/docs/api-reference/get-instruments.md b/PolymarketDocumentation-main/docs/api-reference/get-instruments.md new file mode 100644 index 00000000..02662a9d --- /dev/null +++ b/PolymarketDocumentation-main/docs/api-reference/get-instruments.md @@ -0,0 +1,310 @@ +> ## Documentation Index +> Fetch the complete documentation index at: https://docs.polymarket.com/llms.txt +> Use this file to discover all available pages before exploring further. + +# Get Instruments + +> Get all instruments. + +Request Weight: **2** + + +## OpenAPI + +````yaml /api-spec/perps-openapi.json get /v1/info/instruments +openapi: 3.0.3 +info: + title: Polymarket Perps HTTP API + version: 1.0.0 + description: HTTP API for Polymarket perpetual trading system. + license: + name: Apache 2.0 + url: https://www.apache.org/licenses/LICENSE-2.0.html +servers: + - url: https://api.perpetuals.polymarket.com + description: Production Perps HTTP API +security: [] +paths: + /v1/info/instruments: + get: + summary: Get Instruments + description: Get all instruments. + operationId: getInstruments + parameters: + - name: instrument_id + in: query + required: false + schema: + $ref: '#/components/schemas/instrument_id' + - name: instrument_type + in: query + required: false + schema: + $ref: '#/components/schemas/instrument_type' + - name: category + in: query + required: false + schema: + $ref: '#/components/schemas/category' + responses: + '200': + description: Instruments response. + content: + application/json: + schema: + type: array + items: + $ref: '#/components/schemas/Instrument' + '400': + $ref: '#/components/responses/Error400Response' + '429': + $ref: '#/components/responses/Error429Response' + '500': + $ref: '#/components/responses/Error500Response' + security: [] +components: + schemas: + instrument_id: + type: integer + description: Instrument ID + instrument_type: + type: string + description: Instrument type + enum: + - perpetual + category: + type: string + description: Instrument category + enum: + - equity + - commodity + - index + - crypto + Instrument: + type: object + required: + - instrument_id + - instrument_type + - category + - symbol + - base_asset + - quote_asset + - funding_interval + - quantity_decimals + - price_decimals + - price_bounds + - liquidation_fee + - max_order_count + - min_notional + - max_market_notional + - max_limit_notional + - max_leverage + - risk_tiers + properties: + instrument_id: + $ref: '#/components/schemas/instrument_id' + instrument_type: + $ref: '#/components/schemas/instrument_type' + category: + $ref: '#/components/schemas/category' + symbol: + $ref: '#/components/schemas/symbol' + base_asset: + $ref: '#/components/schemas/base_asset' + quote_asset: + $ref: '#/components/schemas/quote_asset' + funding_interval: + $ref: '#/components/schemas/funding_interval' + quantity_decimals: + $ref: '#/components/schemas/quantity_decimals' + price_decimals: + $ref: '#/components/schemas/price_decimals' + price_bounds: + $ref: '#/components/schemas/price_bounds' + liquidation_fee: + $ref: '#/components/schemas/liquidation_fee' + max_order_count: + $ref: '#/components/schemas/max_order_count' + min_notional: + $ref: '#/components/schemas/min_notional' + max_market_notional: + $ref: '#/components/schemas/max_market_notional' + max_limit_notional: + $ref: '#/components/schemas/max_limit_notional' + max_leverage: + $ref: '#/components/schemas/max_leverage' + risk_tiers: + type: array + items: + $ref: '#/components/schemas/RiskTier' + symbol: + type: string + description: Instrument symbol + example: NVDA-USDC + base_asset: + type: string + description: Base asset name + example: NVDA + quote_asset: + type: string + description: Quote asset name + example: USDC + funding_interval: + type: string + description: Funding interval + example: 1h + quantity_decimals: + type: integer + description: Number of decimal places for quantity. + example: 2 + price_decimals: + type: integer + description: >- + Number of decimal places for price. Non-integer prices have a maximum of + 5 significant figures; integer prices are allowed regardless of + significant figures. + example: 2 + price_bounds: + type: string + description: Price bounds percentage + example: '0.05' + liquidation_fee: + type: string + description: Liquidation fee rate + example: '0.025' + max_order_count: + type: integer + description: Maximum open order count + example: 200 + min_notional: + type: string + description: Minimum notional value in USD + example: '1.00' + max_market_notional: + type: string + description: Maximum market order notional value in USD + example: '1000000.00' + max_limit_notional: + type: string + description: Maximum limit order notional value in USD + example: '10000000.00' + max_leverage: + type: integer + description: Maximum leverage + example: 20 + RiskTier: + type: object + required: + - lower_bound + - max_leverage + properties: + lower_bound: + $ref: '#/components/schemas/lower_bound' + max_leverage: + $ref: '#/components/schemas/max_leverage' + Error400: + title: Error400 + type: object + required: + - status + - error + properties: + status: + type: string + enum: + - err + error: + $ref: '#/components/schemas/error' + Error429: + title: Error429 + type: object + required: + - status + - error + properties: + status: + type: string + enum: + - err + error: + $ref: '#/components/schemas/error' + Error500: + title: Error500 + type: object + required: + - status + - error + properties: + status: + type: string + enum: + - err + error: + $ref: '#/components/schemas/error' + lower_bound: + type: string + description: Position size lower bound + example: '0' + error: + type: string + description: >- + Error identifier. For domain rejections and transport errors + (`401`/`404`/`429`/`500`) this is a stable, machine-readable snake_case + identifier that is part of the API contract and safe to branch on, e.g. + `insufficient_margin`, `insufficient_balance`, `order_not_found`, + `reduce_only_invalid`, `unauthorized`, `not_found`. For `400` it is a + human-readable validation detail whose wording may change. See the Error + handling guide for the domain identifiers. (Post-only / Fill-or-Kill + outcomes are order statuses such as `post_only_rejected`, not + rejections.) + example: insufficient_margin + responses: + Error400Response: + description: | + Bad request — the request was malformed or failed validation (bad query + parameters, unparseable body, invalid signature, or a domain pre-check). + The `error` field is a human-readable validation detail. + content: + application/json: + schema: + $ref: '#/components/schemas/Error400' + Error429Response: + description: > + Too Many Requests. `error` distinguishes the limit that was hit: + + `ip_rate_limited` (per-IP token bucket), `action_rate_limited` + (per-account + + action rate), or `open_orders_limit` (resting open-order cap). + headers: + Retry-After: + description: > + Whole seconds to wait before retrying. Present only on token-bucket + + rate-limit rejections (`ip_rate_limited` and `action_rate_limited`); + a + + conservative estimate of when enough capacity will have refilled to + + admit the request. Absent on `open_orders_limit`, which is a + capacity + + limit, not a rate limit — waiting does not free order slots; cancel + + resting orders or wait for fills instead. + schema: + type: integer + example: 2 + content: + application/json: + schema: + $ref: '#/components/schemas/Error429' + Error500Response: + description: | + Internal server error. `error` is `internal_error`. + content: + application/json: + schema: + $ref: '#/components/schemas/Error500' + +```` \ No newline at end of file diff --git a/PolymarketDocumentation-main/docs/api-reference/get-internal-transfers.md b/PolymarketDocumentation-main/docs/api-reference/get-internal-transfers.md new file mode 100644 index 00000000..2d967aeb --- /dev/null +++ b/PolymarketDocumentation-main/docs/api-reference/get-internal-transfers.md @@ -0,0 +1,282 @@ +> ## Documentation Index +> Fetch the complete documentation index at: https://docs.polymarket.com/llms.txt +> Use this file to discover all available pages before exploring further. + +# Get Internal Transfers + +> Get settled internal transfer history for the authenticated account. +Returns both inbound and outbound transfers. + + +Request Weight: **10** + + +## OpenAPI + +````yaml /api-spec/perps-openapi.json get /v1/account/internal-transfers +openapi: 3.0.3 +info: + title: Polymarket Perps HTTP API + version: 1.0.0 + description: HTTP API for Polymarket perpetual trading system. + license: + name: Apache 2.0 + url: https://www.apache.org/licenses/LICENSE-2.0.html +servers: + - url: https://api.perpetuals.polymarket.com + description: Production Perps HTTP API +security: [] +paths: + /v1/account/internal-transfers: + get: + summary: Get Internal Transfers + description: | + Get settled internal transfer history for the authenticated account. + Returns both inbound and outbound transfers. + operationId: getInternalTransfers + parameters: + - name: start_timestamp + in: query + required: false + schema: + $ref: '#/components/schemas/start_timestamp' + - name: end_timestamp + in: query + required: false + schema: + $ref: '#/components/schemas/end_timestamp' + responses: + '200': + description: Internal transfer history response. + content: + application/json: + schema: + $ref: '#/components/schemas/InternalTransfers' + '400': + $ref: '#/components/responses/Error400Response' + '401': + $ref: '#/components/responses/Error401Response' + '429': + $ref: '#/components/responses/Error429Response' + '500': + $ref: '#/components/responses/Error500Response' + security: + - polymarket_proxy: [] + polymarket_secret: [] +components: + schemas: + start_timestamp: + type: integer + description: Start timestamp in milliseconds + example: 1767225600000 + end_timestamp: + type: integer + description: End timestamp in milliseconds + example: 1767229200000 + InternalTransfers: + type: object + required: + - data + - more + properties: + data: + type: array + items: + $ref: '#/components/schemas/InternalTransfer' + more: + $ref: '#/components/schemas/more' + InternalTransfer: + type: object + required: + - transfer_id + - asset + - amount + - direction + - counterparty + - created_timestamp + properties: + transfer_id: + $ref: '#/components/schemas/transfer_id' + asset: + $ref: '#/components/schemas/asset' + amount: + $ref: '#/components/schemas/amount' + direction: + $ref: '#/components/schemas/direction' + counterparty: + $ref: '#/components/schemas/counterparty' + label: + $ref: '#/components/schemas/label' + created_timestamp: + $ref: '#/components/schemas/created_timestamp' + more: + type: boolean + description: More data available + Error400: + title: Error400 + type: object + required: + - status + - error + properties: + status: + type: string + enum: + - err + error: + $ref: '#/components/schemas/error' + Error401: + title: Error401 + type: object + required: + - status + - error + properties: + status: + type: string + enum: + - err + error: + $ref: '#/components/schemas/error' + Error429: + title: Error429 + type: object + required: + - status + - error + properties: + status: + type: string + enum: + - err + error: + $ref: '#/components/schemas/error' + Error500: + title: Error500 + type: object + required: + - status + - error + properties: + status: + type: string + enum: + - err + error: + $ref: '#/components/schemas/error' + transfer_id: + type: integer + description: Internal transfer ID + asset: + type: string + description: Asset name + example: USDC + amount: + type: string + description: >- + Raw token amount including decimals. For withdrawals this matches the + uint256 amount in the EIP-712 signature (e.g. "100000000" for 100 USDC + with 6 decimals). + example: '100000000' + direction: + type: string + description: Transfer direction relative to the authenticated account + enum: + - in + - out + counterparty: + type: string + description: Counterparty account address in hex format + example: '0x1234567890abcdef1234567890abcdef12345678' + label: + type: string + description: Human-readable label for a proxy key or internal transfer + example: trading-bot + created_timestamp: + type: integer + description: Creation timestamp in milliseconds + example: 1767225600000 + error: + type: string + description: >- + Error identifier. For domain rejections and transport errors + (`401`/`404`/`429`/`500`) this is a stable, machine-readable snake_case + identifier that is part of the API contract and safe to branch on, e.g. + `insufficient_margin`, `insufficient_balance`, `order_not_found`, + `reduce_only_invalid`, `unauthorized`, `not_found`. For `400` it is a + human-readable validation detail whose wording may change. See the Error + handling guide for the domain identifiers. (Post-only / Fill-or-Kill + outcomes are order statuses such as `post_only_rejected`, not + rejections.) + example: insufficient_margin + responses: + Error400Response: + description: | + Bad request — the request was malformed or failed validation (bad query + parameters, unparseable body, invalid signature, or a domain pre-check). + The `error` field is a human-readable validation detail. + content: + application/json: + schema: + $ref: '#/components/schemas/Error400' + Error401Response: + description: > + Unauthorized — missing or invalid `POLYMARKET-PROXY` / + `POLYMARKET-SECRET` + + credentials. `error` is `unauthorized`. + content: + application/json: + schema: + $ref: '#/components/schemas/Error401' + Error429Response: + description: > + Too Many Requests. `error` distinguishes the limit that was hit: + + `ip_rate_limited` (per-IP token bucket), `action_rate_limited` + (per-account + + action rate), or `open_orders_limit` (resting open-order cap). + headers: + Retry-After: + description: > + Whole seconds to wait before retrying. Present only on token-bucket + + rate-limit rejections (`ip_rate_limited` and `action_rate_limited`); + a + + conservative estimate of when enough capacity will have refilled to + + admit the request. Absent on `open_orders_limit`, which is a + capacity + + limit, not a rate limit — waiting does not free order slots; cancel + + resting orders or wait for fills instead. + schema: + type: integer + example: 2 + content: + application/json: + schema: + $ref: '#/components/schemas/Error429' + Error500Response: + description: | + Internal server error. `error` is `internal_error`. + content: + application/json: + schema: + $ref: '#/components/schemas/Error500' + securitySchemes: + polymarket_proxy: + type: apiKey + name: POLYMARKET-PROXY + in: header + description: Proxy address + polymarket_secret: + type: apiKey + name: POLYMARKET-SECRET + in: header + description: Correponding proxy secret + +```` \ No newline at end of file diff --git a/PolymarketDocumentation-main/docs/api-reference/get-klines.md b/PolymarketDocumentation-main/docs/api-reference/get-klines.md new file mode 100644 index 00000000..343a9b6f --- /dev/null +++ b/PolymarketDocumentation-main/docs/api-reference/get-klines.md @@ -0,0 +1,237 @@ +> ## Documentation Index +> Fetch the complete documentation index at: https://docs.polymarket.com/llms.txt +> Use this file to discover all available pages before exploring further. + +# Get Klines + +> Get klines for an instrument. +If no end time is provided, the current time will be used. +Maximum of 1000 entries returned per request. + + +Request Weight: **5** + + +## OpenAPI + +````yaml /api-spec/perps-openapi.json get /v1/info/klines +openapi: 3.0.3 +info: + title: Polymarket Perps HTTP API + version: 1.0.0 + description: HTTP API for Polymarket perpetual trading system. + license: + name: Apache 2.0 + url: https://www.apache.org/licenses/LICENSE-2.0.html +servers: + - url: https://api.perpetuals.polymarket.com + description: Production Perps HTTP API +security: [] +paths: + /v1/info/klines: + get: + summary: Get Klines + description: | + Get klines for an instrument. + If no end time is provided, the current time will be used. + Maximum of 1000 entries returned per request. + operationId: getKlines + parameters: + - name: instrument_id + in: query + required: true + schema: + $ref: '#/components/schemas/instrument_id' + - name: interval + in: query + required: true + schema: + $ref: '#/components/schemas/interval' + - name: start_timestamp + in: query + required: true + schema: + $ref: '#/components/schemas/start_timestamp' + - name: end_timestamp + in: query + required: false + schema: + $ref: '#/components/schemas/end_timestamp' + responses: + '200': + description: Klines response. + content: + application/json: + schema: + $ref: '#/components/schemas/KlinesResponse' + '400': + $ref: '#/components/responses/Error400Response' + '429': + $ref: '#/components/responses/Error429Response' + '500': + $ref: '#/components/responses/Error500Response' + security: [] +components: + schemas: + instrument_id: + type: integer + description: Instrument ID + interval: + type: string + description: Kline interval + enum: + - 1s + - 1m + - 5m + - 15m + - 30m + - 1h + - 4h + - 6h + - 12h + - 1d + - 1w + start_timestamp: + type: integer + description: Start timestamp in milliseconds + example: 1767225600000 + end_timestamp: + type: integer + description: End timestamp in milliseconds + example: 1767229200000 + KlinesResponse: + type: object + required: + - data + - more + properties: + data: + type: array + items: + $ref: '#/components/schemas/kline' + maxItems: 1000 + more: + $ref: '#/components/schemas/more' + kline: + type: array + description: | + - `1767225600000` - Open time + - `"100.00"` - Open price + - `"105.00"` - High price + - `"99.00"` - Low price + - `"102.00"` - Close price + - `"500.00"` - Volume (base unit) + - `42` - Number of trades + example: + - 1767225600000 + - '100.00' + - '105.00' + - '99.00' + - '102.00' + - '500.00' + - 42 + more: + type: boolean + description: More data available + Error400: + title: Error400 + type: object + required: + - status + - error + properties: + status: + type: string + enum: + - err + error: + $ref: '#/components/schemas/error' + Error429: + title: Error429 + type: object + required: + - status + - error + properties: + status: + type: string + enum: + - err + error: + $ref: '#/components/schemas/error' + Error500: + title: Error500 + type: object + required: + - status + - error + properties: + status: + type: string + enum: + - err + error: + $ref: '#/components/schemas/error' + error: + type: string + description: >- + Error identifier. For domain rejections and transport errors + (`401`/`404`/`429`/`500`) this is a stable, machine-readable snake_case + identifier that is part of the API contract and safe to branch on, e.g. + `insufficient_margin`, `insufficient_balance`, `order_not_found`, + `reduce_only_invalid`, `unauthorized`, `not_found`. For `400` it is a + human-readable validation detail whose wording may change. See the Error + handling guide for the domain identifiers. (Post-only / Fill-or-Kill + outcomes are order statuses such as `post_only_rejected`, not + rejections.) + example: insufficient_margin + responses: + Error400Response: + description: | + Bad request — the request was malformed or failed validation (bad query + parameters, unparseable body, invalid signature, or a domain pre-check). + The `error` field is a human-readable validation detail. + content: + application/json: + schema: + $ref: '#/components/schemas/Error400' + Error429Response: + description: > + Too Many Requests. `error` distinguishes the limit that was hit: + + `ip_rate_limited` (per-IP token bucket), `action_rate_limited` + (per-account + + action rate), or `open_orders_limit` (resting open-order cap). + headers: + Retry-After: + description: > + Whole seconds to wait before retrying. Present only on token-bucket + + rate-limit rejections (`ip_rate_limited` and `action_rate_limited`); + a + + conservative estimate of when enough capacity will have refilled to + + admit the request. Absent on `open_orders_limit`, which is a + capacity + + limit, not a rate limit — waiting does not free order slots; cancel + + resting orders or wait for fills instead. + schema: + type: integer + example: 2 + content: + application/json: + schema: + $ref: '#/components/schemas/Error429' + Error500Response: + description: | + Internal server error. `error` is `internal_error`. + content: + application/json: + schema: + $ref: '#/components/schemas/Error500' + +```` \ No newline at end of file diff --git a/PolymarketDocumentation-main/docs/api-reference/get-limit-tiers.md b/PolymarketDocumentation-main/docs/api-reference/get-limit-tiers.md new file mode 100644 index 00000000..a90655d3 --- /dev/null +++ b/PolymarketDocumentation-main/docs/api-reference/get-limit-tiers.md @@ -0,0 +1,188 @@ +> ## Documentation Index +> Fetch the complete documentation index at: https://docs.polymarket.com/llms.txt +> Use this file to discover all available pages before exploring further. + +# Get Limit Tiers + +> Get the list of account limit tiers. Action and open-order fields are enforced per account; legacy request-rate fields are not used for gateway request enforcement. + +Request Weight: **2** + + +## OpenAPI + +````yaml /api-spec/perps-openapi.json get /v1/info/limit-tiers +openapi: 3.0.3 +info: + title: Polymarket Perps HTTP API + version: 1.0.0 + description: HTTP API for Polymarket perpetual trading system. + license: + name: Apache 2.0 + url: https://www.apache.org/licenses/LICENSE-2.0.html +servers: + - url: https://api.perpetuals.polymarket.com + description: Production Perps HTTP API +security: [] +paths: + /v1/info/limit-tiers: + get: + summary: Get Limit Tiers + description: >- + Get the list of account limit tiers. Action and open-order fields are + enforced per account; legacy request-rate fields are not used for + gateway request enforcement. + operationId: getLimitTiers + responses: + '200': + description: Limit tiers response. + content: + application/json: + schema: + type: array + items: + $ref: '#/components/schemas/LimitTier' + '429': + $ref: '#/components/responses/Error429Response' + '500': + $ref: '#/components/responses/Error500Response' + security: [] +components: + schemas: + LimitTier: + type: object + required: + - min_volume_14d + - rate_per_minute_limit + - rate_burst_limit + - actions_per_minute_limit + - actions_burst_limit + - open_orders_limit + - messages_per_minute + properties: + min_volume_14d: + $ref: '#/components/schemas/min_volume' + rate_per_minute_limit: + $ref: '#/components/schemas/rate_per_minute_limit' + rate_burst_limit: + $ref: '#/components/schemas/rate_burst_limit' + actions_per_minute_limit: + $ref: '#/components/schemas/actions_per_minute_limit' + actions_burst_limit: + $ref: '#/components/schemas/actions_burst_limit' + open_orders_limit: + $ref: '#/components/schemas/open_orders_limit' + messages_per_minute: + $ref: '#/components/schemas/messages_per_minute' + min_volume: + type: string + description: Minimum volume threshold for this tier + example: '0' + rate_per_minute_limit: + type: integer + description: >- + Maximum IP request weight per minute. In limit tiers, this is a legacy + field and is not used for gateway enforcement. + example: 1200 + rate_burst_limit: + type: integer + description: >- + Legacy limit-tier request-rate field. It is not used for gateway + enforcement. + actions_per_minute_limit: + type: integer + description: Maximum order action tokens per account per minute + example: 300 + actions_burst_limit: + type: integer + description: Additional account action allowance limit + open_orders_limit: + type: integer + description: Maximum number of open orders per account + example: 1000 + messages_per_minute: + type: integer + description: >- + Display-only per-minute action/message allowance, equal to + actions_per_minute_limit. Not separately configured or enforced. + example: 300 + Error429: + title: Error429 + type: object + required: + - status + - error + properties: + status: + type: string + enum: + - err + error: + $ref: '#/components/schemas/error' + Error500: + title: Error500 + type: object + required: + - status + - error + properties: + status: + type: string + enum: + - err + error: + $ref: '#/components/schemas/error' + error: + type: string + description: >- + Error identifier. For domain rejections and transport errors + (`401`/`404`/`429`/`500`) this is a stable, machine-readable snake_case + identifier that is part of the API contract and safe to branch on, e.g. + `insufficient_margin`, `insufficient_balance`, `order_not_found`, + `reduce_only_invalid`, `unauthorized`, `not_found`. For `400` it is a + human-readable validation detail whose wording may change. See the Error + handling guide for the domain identifiers. (Post-only / Fill-or-Kill + outcomes are order statuses such as `post_only_rejected`, not + rejections.) + example: insufficient_margin + responses: + Error429Response: + description: > + Too Many Requests. `error` distinguishes the limit that was hit: + + `ip_rate_limited` (per-IP token bucket), `action_rate_limited` + (per-account + + action rate), or `open_orders_limit` (resting open-order cap). + headers: + Retry-After: + description: > + Whole seconds to wait before retrying. Present only on token-bucket + + rate-limit rejections (`ip_rate_limited` and `action_rate_limited`); + a + + conservative estimate of when enough capacity will have refilled to + + admit the request. Absent on `open_orders_limit`, which is a + capacity + + limit, not a rate limit — waiting does not free order slots; cancel + + resting orders or wait for fills instead. + schema: + type: integer + example: 2 + content: + application/json: + schema: + $ref: '#/components/schemas/Error429' + Error500Response: + description: | + Internal server error. `error` is `internal_error`. + content: + application/json: + schema: + $ref: '#/components/schemas/Error500' + +```` \ No newline at end of file diff --git a/PolymarketDocumentation-main/docs/api-reference/get-open-orders.md b/PolymarketDocumentation-main/docs/api-reference/get-open-orders.md new file mode 100644 index 00000000..31609277 --- /dev/null +++ b/PolymarketDocumentation-main/docs/api-reference/get-open-orders.md @@ -0,0 +1,382 @@ +> ## Documentation Index +> Fetch the complete documentation index at: https://docs.polymarket.com/llms.txt +> Use this file to discover all available pages before exploring further. + +# Get Open Orders + +> Get open orders for the authenticated account. + +Request Weight: + +
+ +With instrument ID: **1** + +
+ +Without instrument ID: **20** + + +## OpenAPI + +````yaml /api-spec/perps-openapi.json get /v1/account/open-orders +openapi: 3.0.3 +info: + title: Polymarket Perps HTTP API + version: 1.0.0 + description: HTTP API for Polymarket perpetual trading system. + license: + name: Apache 2.0 + url: https://www.apache.org/licenses/LICENSE-2.0.html +servers: + - url: https://api.perpetuals.polymarket.com + description: Production Perps HTTP API +security: [] +paths: + /v1/account/open-orders: + get: + summary: Get Open Orders + description: Get open orders for the authenticated account. + operationId: getOpenOrders + parameters: + - name: instrument_id + in: query + required: false + schema: + $ref: '#/components/schemas/iid' + responses: + '200': + description: Orders response. + content: + application/json: + schema: + type: array + items: + $ref: '#/components/schemas/OrderData' + '400': + $ref: '#/components/responses/Error400Response' + '401': + $ref: '#/components/responses/Error401Response' + '429': + $ref: '#/components/responses/Error429Response' + '500': + $ref: '#/components/responses/Error500Response' + security: + - polymarket_proxy: [] + polymarket_secret: [] +components: + schemas: + iid: + type: integer + description: Instrument ID + example: 1 + OrderData: + type: object + required: + - order_id + - instrument_id + - buy + - price + - quantity + - tif + - post_only + - ro + - status + - resting_quantity + - filled_quantity + - created_timestamp + - updated_timestamp + properties: + order_id: + $ref: '#/components/schemas/oid' + instrument_id: + $ref: '#/components/schemas/iid' + buy: + $ref: '#/components/schemas/buy' + price: + $ref: '#/components/schemas/p' + quantity: + $ref: '#/components/schemas/qty' + tif: + $ref: '#/components/schemas/tif' + post_only: + $ref: '#/components/schemas/po' + ro: + $ref: '#/components/schemas/ro' + resting_quantity: + $ref: '#/components/schemas/rest' + filled_quantity: + $ref: '#/components/schemas/fill' + status: + $ref: '#/components/schemas/st' + created_timestamp: + $ref: '#/components/schemas/cts' + updated_timestamp: + $ref: '#/components/schemas/uts' + client_order_id: + $ref: '#/components/schemas/coid' + tpsl: + $ref: '#/components/schemas/TpSlOrderFields' + description: >- + Conditional-order fields. Present only when the order is a TP/SL + conditional order — `null`/omitted for regular orders. + oid: + type: integer + description: Order ID + example: 1234567890 + buy: + type: boolean + description: Is buy + example: true + p: + type: string + description: Price + example: '100.00' + qty: + type: string + description: Quantity in no. of contracts + example: '10.00' + tif: + type: string + description: Time in force + enum: + - gtc + - ioc + - fok + po: + type: boolean + description: Post only + default: false + example: false + ro: + type: boolean + description: Reduce only + example: false + default: false + rest: + type: string + description: Resting quantity + example: '9.00' + fill: + type: string + description: Filled quantity + example: '1.00' + st: + type: string + description: Order status + example: open + cts: + type: integer + description: Create timestamp in milliseconds + example: 1767225600000 + uts: + type: integer + description: Update timestamp in milliseconds + example: 1767225600000 + coid: + type: string + description: Client order ID + minLength: 32 + maxLength: 32 + pattern: ^[0-9a-f]{32}$ + example: 550e8400e29b41d4a716446655440000 + TpSlOrderFields: + type: object + description: TP/SL-specific fields surfaced alongside the regular order shape. + required: + - kind + - scope + - trp + properties: + kind: + $ref: '#/components/schemas/kind' + scope: + $ref: '#/components/schemas/tr_scope' + trp: + $ref: '#/components/schemas/trp' + parent_oid: + $ref: '#/components/schemas/parent_oid' + armed_qty: + $ref: '#/components/schemas/qty' + description: >- + Quantity armed at attach time (OCO) or `"0"` for position-based + (sized at trigger time). + slip_bps: + $ref: '#/components/schemas/slip_bps' + Error400: + title: Error400 + type: object + required: + - status + - error + properties: + status: + type: string + enum: + - err + error: + $ref: '#/components/schemas/error' + Error401: + title: Error401 + type: object + required: + - status + - error + properties: + status: + type: string + enum: + - err + error: + $ref: '#/components/schemas/error' + Error429: + title: Error429 + type: object + required: + - status + - error + properties: + status: + type: string + enum: + - err + error: + $ref: '#/components/schemas/error' + Error500: + title: Error500 + type: object + required: + - status + - error + properties: + status: + type: string + enum: + - err + error: + $ref: '#/components/schemas/error' + kind: + type: string + description: Conditional order type (TakeProfit / StopLoss) + enum: + - tp + - sl + tr_scope: + type: string + description: > + How the conditional order sizes itself. + + - `order` - child of a parent entry (bracket / OCO ladder). Quantity is + required. + + - `position` - attached to an open position. v1 always closes the full + position (`qty` must be `"0"`). + enum: + - order + - position + trp: + type: string + description: Trigger price + example: '110.00' + parent_oid: + type: integer + description: >- + Parent entry order id. Optional — omit it (do not send `0`) when the + parent is created in the same request (inline `CreateOrder.tpsl` or + `CreateTpSlArgs.parent`); the gateway auto-wires the child to it. Set it + only to attach an order-scoped leg to an existing resting order. Inline + `CreateOrder.tpsl` rejects a non-zero value; position-scoped legs carry + no parent. + example: 1234567890 + slip_bps: + type: integer + minimum: 0 + maximum: 10000 + description: >- + Per-order market-trigger slippage cap in basis points. 0 = use the + per-instrument default. Clamped to the instrument cap. + example: 1000 + error: + type: string + description: >- + Error identifier. For domain rejections and transport errors + (`401`/`404`/`429`/`500`) this is a stable, machine-readable snake_case + identifier that is part of the API contract and safe to branch on, e.g. + `insufficient_margin`, `insufficient_balance`, `order_not_found`, + `reduce_only_invalid`, `unauthorized`, `not_found`. For `400` it is a + human-readable validation detail whose wording may change. See the Error + handling guide for the domain identifiers. (Post-only / Fill-or-Kill + outcomes are order statuses such as `post_only_rejected`, not + rejections.) + example: insufficient_margin + responses: + Error400Response: + description: | + Bad request — the request was malformed or failed validation (bad query + parameters, unparseable body, invalid signature, or a domain pre-check). + The `error` field is a human-readable validation detail. + content: + application/json: + schema: + $ref: '#/components/schemas/Error400' + Error401Response: + description: > + Unauthorized — missing or invalid `POLYMARKET-PROXY` / + `POLYMARKET-SECRET` + + credentials. `error` is `unauthorized`. + content: + application/json: + schema: + $ref: '#/components/schemas/Error401' + Error429Response: + description: > + Too Many Requests. `error` distinguishes the limit that was hit: + + `ip_rate_limited` (per-IP token bucket), `action_rate_limited` + (per-account + + action rate), or `open_orders_limit` (resting open-order cap). + headers: + Retry-After: + description: > + Whole seconds to wait before retrying. Present only on token-bucket + + rate-limit rejections (`ip_rate_limited` and `action_rate_limited`); + a + + conservative estimate of when enough capacity will have refilled to + + admit the request. Absent on `open_orders_limit`, which is a + capacity + + limit, not a rate limit — waiting does not free order slots; cancel + + resting orders or wait for fills instead. + schema: + type: integer + example: 2 + content: + application/json: + schema: + $ref: '#/components/schemas/Error429' + Error500Response: + description: | + Internal server error. `error` is `internal_error`. + content: + application/json: + schema: + $ref: '#/components/schemas/Error500' + securitySchemes: + polymarket_proxy: + type: apiKey + name: POLYMARKET-PROXY + in: header + description: Proxy address + polymarket_secret: + type: apiKey + name: POLYMARKET-SECRET + in: header + description: Correponding proxy secret + +```` \ No newline at end of file diff --git a/PolymarketDocumentation-main/docs/api-reference/get-orders.md b/PolymarketDocumentation-main/docs/api-reference/get-orders.md new file mode 100644 index 00000000..e02d4c0f --- /dev/null +++ b/PolymarketDocumentation-main/docs/api-reference/get-orders.md @@ -0,0 +1,427 @@ +> ## Documentation Index +> Fetch the complete documentation index at: https://docs.polymarket.com/llms.txt +> Use this file to discover all available pages before exploring further. + +# Get Orders + +> Get historical order snapshots for the authenticated account from the order history database. +Returns the latest known state for each matching order, including accepted, open, partial, +filled, and cancelled orders. For currently resting orders only, use Get Open Orders. +Maximum of 100 entries returned per request. + + +Request Weight: + +
+ +With order ID: **1** + +
+ +Without order ID: **10** + + +## OpenAPI + +````yaml /api-spec/perps-openapi.json get /v1/account/orders +openapi: 3.0.3 +info: + title: Polymarket Perps HTTP API + version: 1.0.0 + description: HTTP API for Polymarket perpetual trading system. + license: + name: Apache 2.0 + url: https://www.apache.org/licenses/LICENSE-2.0.html +servers: + - url: https://api.perpetuals.polymarket.com + description: Production Perps HTTP API +security: [] +paths: + /v1/account/orders: + get: + summary: Get Orders + description: > + Get historical order snapshots for the authenticated account from the + order history database. + + Returns the latest known state for each matching order, including + accepted, open, partial, + + filled, and cancelled orders. For currently resting orders only, use Get + Open Orders. + + Maximum of 100 entries returned per request. + operationId: getOrders + parameters: + - name: order_id + in: query + required: false + schema: + $ref: '#/components/schemas/order_id' + - name: client_order_id + in: query + required: false + schema: + $ref: '#/components/schemas/coid' + - name: instrument_id + in: query + required: false + schema: + $ref: '#/components/schemas/iid' + - name: start_timestamp + in: query + required: false + schema: + $ref: '#/components/schemas/start_timestamp' + - name: end_timestamp + in: query + required: false + schema: + $ref: '#/components/schemas/end_timestamp' + responses: + '200': + description: Orders response. + content: + application/json: + schema: + type: array + items: + $ref: '#/components/schemas/OrderData' + '400': + $ref: '#/components/responses/Error400Response' + '401': + $ref: '#/components/responses/Error401Response' + '429': + $ref: '#/components/responses/Error429Response' + '500': + $ref: '#/components/responses/Error500Response' + security: + - polymarket_proxy: [] + polymarket_secret: [] +components: + schemas: + order_id: + type: integer + description: Order ID + coid: + type: string + description: Client order ID + minLength: 32 + maxLength: 32 + pattern: ^[0-9a-f]{32}$ + example: 550e8400e29b41d4a716446655440000 + iid: + type: integer + description: Instrument ID + example: 1 + start_timestamp: + type: integer + description: Start timestamp in milliseconds + example: 1767225600000 + end_timestamp: + type: integer + description: End timestamp in milliseconds + example: 1767229200000 + OrderData: + type: object + required: + - order_id + - instrument_id + - buy + - price + - quantity + - tif + - post_only + - ro + - status + - resting_quantity + - filled_quantity + - created_timestamp + - updated_timestamp + properties: + order_id: + $ref: '#/components/schemas/oid' + instrument_id: + $ref: '#/components/schemas/iid' + buy: + $ref: '#/components/schemas/buy' + price: + $ref: '#/components/schemas/p' + quantity: + $ref: '#/components/schemas/qty' + tif: + $ref: '#/components/schemas/tif' + post_only: + $ref: '#/components/schemas/po' + ro: + $ref: '#/components/schemas/ro' + resting_quantity: + $ref: '#/components/schemas/rest' + filled_quantity: + $ref: '#/components/schemas/fill' + status: + $ref: '#/components/schemas/st' + created_timestamp: + $ref: '#/components/schemas/cts' + updated_timestamp: + $ref: '#/components/schemas/uts' + client_order_id: + $ref: '#/components/schemas/coid' + tpsl: + $ref: '#/components/schemas/TpSlOrderFields' + description: >- + Conditional-order fields. Present only when the order is a TP/SL + conditional order — `null`/omitted for regular orders. + oid: + type: integer + description: Order ID + example: 1234567890 + buy: + type: boolean + description: Is buy + example: true + p: + type: string + description: Price + example: '100.00' + qty: + type: string + description: Quantity in no. of contracts + example: '10.00' + tif: + type: string + description: Time in force + enum: + - gtc + - ioc + - fok + po: + type: boolean + description: Post only + default: false + example: false + ro: + type: boolean + description: Reduce only + example: false + default: false + rest: + type: string + description: Resting quantity + example: '9.00' + fill: + type: string + description: Filled quantity + example: '1.00' + st: + type: string + description: Order status + example: open + cts: + type: integer + description: Create timestamp in milliseconds + example: 1767225600000 + uts: + type: integer + description: Update timestamp in milliseconds + example: 1767225600000 + TpSlOrderFields: + type: object + description: TP/SL-specific fields surfaced alongside the regular order shape. + required: + - kind + - scope + - trp + properties: + kind: + $ref: '#/components/schemas/kind' + scope: + $ref: '#/components/schemas/tr_scope' + trp: + $ref: '#/components/schemas/trp' + parent_oid: + $ref: '#/components/schemas/parent_oid' + armed_qty: + $ref: '#/components/schemas/qty' + description: >- + Quantity armed at attach time (OCO) or `"0"` for position-based + (sized at trigger time). + slip_bps: + $ref: '#/components/schemas/slip_bps' + Error400: + title: Error400 + type: object + required: + - status + - error + properties: + status: + type: string + enum: + - err + error: + $ref: '#/components/schemas/error' + Error401: + title: Error401 + type: object + required: + - status + - error + properties: + status: + type: string + enum: + - err + error: + $ref: '#/components/schemas/error' + Error429: + title: Error429 + type: object + required: + - status + - error + properties: + status: + type: string + enum: + - err + error: + $ref: '#/components/schemas/error' + Error500: + title: Error500 + type: object + required: + - status + - error + properties: + status: + type: string + enum: + - err + error: + $ref: '#/components/schemas/error' + kind: + type: string + description: Conditional order type (TakeProfit / StopLoss) + enum: + - tp + - sl + tr_scope: + type: string + description: > + How the conditional order sizes itself. + + - `order` - child of a parent entry (bracket / OCO ladder). Quantity is + required. + + - `position` - attached to an open position. v1 always closes the full + position (`qty` must be `"0"`). + enum: + - order + - position + trp: + type: string + description: Trigger price + example: '110.00' + parent_oid: + type: integer + description: >- + Parent entry order id. Optional — omit it (do not send `0`) when the + parent is created in the same request (inline `CreateOrder.tpsl` or + `CreateTpSlArgs.parent`); the gateway auto-wires the child to it. Set it + only to attach an order-scoped leg to an existing resting order. Inline + `CreateOrder.tpsl` rejects a non-zero value; position-scoped legs carry + no parent. + example: 1234567890 + slip_bps: + type: integer + minimum: 0 + maximum: 10000 + description: >- + Per-order market-trigger slippage cap in basis points. 0 = use the + per-instrument default. Clamped to the instrument cap. + example: 1000 + error: + type: string + description: >- + Error identifier. For domain rejections and transport errors + (`401`/`404`/`429`/`500`) this is a stable, machine-readable snake_case + identifier that is part of the API contract and safe to branch on, e.g. + `insufficient_margin`, `insufficient_balance`, `order_not_found`, + `reduce_only_invalid`, `unauthorized`, `not_found`. For `400` it is a + human-readable validation detail whose wording may change. See the Error + handling guide for the domain identifiers. (Post-only / Fill-or-Kill + outcomes are order statuses such as `post_only_rejected`, not + rejections.) + example: insufficient_margin + responses: + Error400Response: + description: | + Bad request — the request was malformed or failed validation (bad query + parameters, unparseable body, invalid signature, or a domain pre-check). + The `error` field is a human-readable validation detail. + content: + application/json: + schema: + $ref: '#/components/schemas/Error400' + Error401Response: + description: > + Unauthorized — missing or invalid `POLYMARKET-PROXY` / + `POLYMARKET-SECRET` + + credentials. `error` is `unauthorized`. + content: + application/json: + schema: + $ref: '#/components/schemas/Error401' + Error429Response: + description: > + Too Many Requests. `error` distinguishes the limit that was hit: + + `ip_rate_limited` (per-IP token bucket), `action_rate_limited` + (per-account + + action rate), or `open_orders_limit` (resting open-order cap). + headers: + Retry-After: + description: > + Whole seconds to wait before retrying. Present only on token-bucket + + rate-limit rejections (`ip_rate_limited` and `action_rate_limited`); + a + + conservative estimate of when enough capacity will have refilled to + + admit the request. Absent on `open_orders_limit`, which is a + capacity + + limit, not a rate limit — waiting does not free order slots; cancel + + resting orders or wait for fills instead. + schema: + type: integer + example: 2 + content: + application/json: + schema: + $ref: '#/components/schemas/Error429' + Error500Response: + description: | + Internal server error. `error` is `internal_error`. + content: + application/json: + schema: + $ref: '#/components/schemas/Error500' + securitySchemes: + polymarket_proxy: + type: apiKey + name: POLYMARKET-PROXY + in: header + description: Proxy address + polymarket_secret: + type: apiKey + name: POLYMARKET-SECRET + in: header + description: Correponding proxy secret + +```` \ No newline at end of file diff --git a/PolymarketDocumentation-main/docs/api-reference/get-pnl.md b/PolymarketDocumentation-main/docs/api-reference/get-pnl.md new file mode 100644 index 00000000..0d2dab32 --- /dev/null +++ b/PolymarketDocumentation-main/docs/api-reference/get-pnl.md @@ -0,0 +1,248 @@ +> ## Documentation Index +> Fetch the complete documentation index at: https://docs.polymarket.com/llms.txt +> Use this file to discover all available pages before exploring further. + +# Get PnL + +> Get PnL history for the authenticated account. +If no end time is provided, the current time will be used. +Maximum of 1000 entries returned per request. + + +Request Weight: **10** + + +## OpenAPI + +````yaml /api-spec/perps-openapi.json get /v1/account/pnl +openapi: 3.0.3 +info: + title: Polymarket Perps HTTP API + version: 1.0.0 + description: HTTP API for Polymarket perpetual trading system. + license: + name: Apache 2.0 + url: https://www.apache.org/licenses/LICENSE-2.0.html +servers: + - url: https://api.perpetuals.polymarket.com + description: Production Perps HTTP API +security: [] +paths: + /v1/account/pnl: + get: + summary: Get PnL + description: | + Get PnL history for the authenticated account. + If no end time is provided, the current time will be used. + Maximum of 1000 entries returned per request. + operationId: getPnlHistory + parameters: + - name: interval + in: query + required: true + schema: + $ref: '#/components/schemas/pnl_interval' + - name: start_timestamp + in: query + required: true + schema: + $ref: '#/components/schemas/start_timestamp' + - name: end_timestamp + in: query + required: false + schema: + $ref: '#/components/schemas/end_timestamp' + responses: + '200': + description: PnL history response. + content: + application/json: + schema: + $ref: '#/components/schemas/PnlHistory' + '400': + $ref: '#/components/responses/Error400Response' + '401': + $ref: '#/components/responses/Error401Response' + '429': + $ref: '#/components/responses/Error429Response' + '500': + $ref: '#/components/responses/Error500Response' + security: + - polymarket_proxy: [] + polymarket_secret: [] +components: + schemas: + pnl_interval: + type: string + description: PnL interval + enum: + - 1h + - 4h + - 1d + - 1w + start_timestamp: + type: integer + description: Start timestamp in milliseconds + example: 1767225600000 + end_timestamp: + type: integer + description: End timestamp in milliseconds + example: 1767229200000 + PnlHistory: + type: object + required: + - data + - more + properties: + data: + type: array + description: | + - `1767225600000` - Timestamp + - `"100.50"` - PnL + items: + type: array + example: + - 1767225600000 + - '100.50' + maxItems: 1000 + more: + $ref: '#/components/schemas/more' + more: + type: boolean + description: More data available + Error400: + title: Error400 + type: object + required: + - status + - error + properties: + status: + type: string + enum: + - err + error: + $ref: '#/components/schemas/error' + Error401: + title: Error401 + type: object + required: + - status + - error + properties: + status: + type: string + enum: + - err + error: + $ref: '#/components/schemas/error' + Error429: + title: Error429 + type: object + required: + - status + - error + properties: + status: + type: string + enum: + - err + error: + $ref: '#/components/schemas/error' + Error500: + title: Error500 + type: object + required: + - status + - error + properties: + status: + type: string + enum: + - err + error: + $ref: '#/components/schemas/error' + error: + type: string + description: >- + Error identifier. For domain rejections and transport errors + (`401`/`404`/`429`/`500`) this is a stable, machine-readable snake_case + identifier that is part of the API contract and safe to branch on, e.g. + `insufficient_margin`, `insufficient_balance`, `order_not_found`, + `reduce_only_invalid`, `unauthorized`, `not_found`. For `400` it is a + human-readable validation detail whose wording may change. See the Error + handling guide for the domain identifiers. (Post-only / Fill-or-Kill + outcomes are order statuses such as `post_only_rejected`, not + rejections.) + example: insufficient_margin + responses: + Error400Response: + description: | + Bad request — the request was malformed or failed validation (bad query + parameters, unparseable body, invalid signature, or a domain pre-check). + The `error` field is a human-readable validation detail. + content: + application/json: + schema: + $ref: '#/components/schemas/Error400' + Error401Response: + description: > + Unauthorized — missing or invalid `POLYMARKET-PROXY` / + `POLYMARKET-SECRET` + + credentials. `error` is `unauthorized`. + content: + application/json: + schema: + $ref: '#/components/schemas/Error401' + Error429Response: + description: > + Too Many Requests. `error` distinguishes the limit that was hit: + + `ip_rate_limited` (per-IP token bucket), `action_rate_limited` + (per-account + + action rate), or `open_orders_limit` (resting open-order cap). + headers: + Retry-After: + description: > + Whole seconds to wait before retrying. Present only on token-bucket + + rate-limit rejections (`ip_rate_limited` and `action_rate_limited`); + a + + conservative estimate of when enough capacity will have refilled to + + admit the request. Absent on `open_orders_limit`, which is a + capacity + + limit, not a rate limit — waiting does not free order slots; cancel + + resting orders or wait for fills instead. + schema: + type: integer + example: 2 + content: + application/json: + schema: + $ref: '#/components/schemas/Error429' + Error500Response: + description: | + Internal server error. `error` is `internal_error`. + content: + application/json: + schema: + $ref: '#/components/schemas/Error500' + securitySchemes: + polymarket_proxy: + type: apiKey + name: POLYMARKET-PROXY + in: header + description: Proxy address + polymarket_secret: + type: apiKey + name: POLYMARKET-SECRET + in: header + description: Correponding proxy secret + +```` \ No newline at end of file diff --git a/PolymarketDocumentation-main/docs/api-reference/get-portfolio.md b/PolymarketDocumentation-main/docs/api-reference/get-portfolio.md new file mode 100644 index 00000000..1558fc9e --- /dev/null +++ b/PolymarketDocumentation-main/docs/api-reference/get-portfolio.md @@ -0,0 +1,350 @@ +> ## Documentation Index +> Fetch the complete documentation index at: https://docs.polymarket.com/llms.txt +> Use this file to discover all available pages before exploring further. + +# Get Portfolio + +> Get current portfolio snapshot including open positions, margin summary, and withdrawable balance. + + +Request Weight: **2** + + +## OpenAPI + +````yaml /api-spec/perps-openapi.json get /v1/account/portfolio +openapi: 3.0.3 +info: + title: Polymarket Perps HTTP API + version: 1.0.0 + description: HTTP API for Polymarket perpetual trading system. + license: + name: Apache 2.0 + url: https://www.apache.org/licenses/LICENSE-2.0.html +servers: + - url: https://api.perpetuals.polymarket.com + description: Production Perps HTTP API +security: [] +paths: + /v1/account/portfolio: + get: + summary: Get Portfolio + description: > + Get current portfolio snapshot including open positions, margin summary, + and withdrawable balance. + operationId: getPortfolio + responses: + '200': + description: Portfolio response. + content: + application/json: + schema: + $ref: '#/components/schemas/Portfolio' + '400': + $ref: '#/components/responses/Error400Response' + '401': + $ref: '#/components/responses/Error401Response' + '429': + $ref: '#/components/responses/Error429Response' + '500': + $ref: '#/components/responses/Error500Response' + security: + - polymarket_proxy: [] + polymarket_secret: [] +components: + schemas: + Portfolio: + type: object + required: + - positions + - margin + - withdrawable + - in_liquidation + - timestamp + properties: + positions: + type: array + items: + $ref: '#/components/schemas/PortfolioPosition' + margin: + $ref: '#/components/schemas/MarginSummary' + withdrawable: + $ref: '#/components/schemas/withdrawable' + in_liquidation: + $ref: '#/components/schemas/in_liquidation' + timestamp: + $ref: '#/components/schemas/update_timestamp' + PortfolioPosition: + type: object + required: + - instrument_id + - symbol + - size + - entry_price + - leverage + - cross + - initial_margin + - maintenance_margin + - position_value + - liquidation_price + - unrealized_pnl + - return_on_equity + - cumulative_funding + properties: + instrument_id: + $ref: '#/components/schemas/instrument_id' + symbol: + $ref: '#/components/schemas/symbol' + size: + $ref: '#/components/schemas/size' + entry_price: + $ref: '#/components/schemas/entry_price' + leverage: + $ref: '#/components/schemas/leverage' + cross: + $ref: '#/components/schemas/cross' + initial_margin: + $ref: '#/components/schemas/initial_margin' + maintenance_margin: + $ref: '#/components/schemas/maintenance_margin_amount' + position_value: + $ref: '#/components/schemas/position_value' + liquidation_price: + $ref: '#/components/schemas/liquidation_price' + unrealized_pnl: + $ref: '#/components/schemas/unrealized_pnl' + return_on_equity: + $ref: '#/components/schemas/return_on_equity' + cumulative_funding: + $ref: '#/components/schemas/cumulative_funding' + MarginSummary: + type: object + required: + - total_account_value + - total_initial_margin + - total_maintenance_margin + - total_position_value + properties: + total_account_value: + $ref: '#/components/schemas/total_account_value' + total_initial_margin: + $ref: '#/components/schemas/total_initial_margin' + total_maintenance_margin: + $ref: '#/components/schemas/total_maintenance_margin' + total_position_value: + $ref: '#/components/schemas/total_position_value' + withdrawable: + type: string + description: Withdrawable balance in USD + example: '13104.51' + in_liquidation: + type: boolean + description: Whether the account is currently under liquidation + update_timestamp: + type: integer + description: Update timestamp in milliseconds + example: 1767225600000 + Error400: + title: Error400 + type: object + required: + - status + - error + properties: + status: + type: string + enum: + - err + error: + $ref: '#/components/schemas/error' + Error401: + title: Error401 + type: object + required: + - status + - error + properties: + status: + type: string + enum: + - err + error: + $ref: '#/components/schemas/error' + Error429: + title: Error429 + type: object + required: + - status + - error + properties: + status: + type: string + enum: + - err + error: + $ref: '#/components/schemas/error' + Error500: + title: Error500 + type: object + required: + - status + - error + properties: + status: + type: string + enum: + - err + error: + $ref: '#/components/schemas/error' + instrument_id: + type: integer + description: Instrument ID + symbol: + type: string + description: Instrument symbol + example: NVDA-USDC + size: + type: string + description: >- + Signed position size in no. of contracts (positive = long, negative = + short) + example: '10.00' + entry_price: + type: string + description: Average entry price + example: '2986.30' + leverage: + type: integer + description: Leverage + example: 10 + cross: + type: boolean + description: Whether to use cross margin mode + initial_margin: + type: string + description: Initial margin in USD + example: '10.00' + maintenance_margin_amount: + type: string + description: Maintenance margin amount + example: '100.00' + position_value: + type: string + description: Notional position value in USD + example: '100.03' + liquidation_price: + type: string + description: Liquidation price + example: '2866.27' + unrealized_pnl: + type: string + description: Unrealized PnL in USD + example: '-0.01' + return_on_equity: + type: string + description: Return on equity as a decimal + example: '-0.0027' + cumulative_funding: + type: string + description: Cumulative funding paid/received in USD + example: '514.09' + total_account_value: + type: string + description: Total account value in USD (equity + unrealized PnL) + example: '13109.48' + total_initial_margin: + type: string + description: Total initial margin in use across all positions + example: '4.97' + total_maintenance_margin: + type: string + description: Total maintenance margin across all positions + example: '2.49' + total_position_value: + type: string + description: Total notional position value in USD + example: '100.03' + error: + type: string + description: >- + Error identifier. For domain rejections and transport errors + (`401`/`404`/`429`/`500`) this is a stable, machine-readable snake_case + identifier that is part of the API contract and safe to branch on, e.g. + `insufficient_margin`, `insufficient_balance`, `order_not_found`, + `reduce_only_invalid`, `unauthorized`, `not_found`. For `400` it is a + human-readable validation detail whose wording may change. See the Error + handling guide for the domain identifiers. (Post-only / Fill-or-Kill + outcomes are order statuses such as `post_only_rejected`, not + rejections.) + example: insufficient_margin + responses: + Error400Response: + description: | + Bad request — the request was malformed or failed validation (bad query + parameters, unparseable body, invalid signature, or a domain pre-check). + The `error` field is a human-readable validation detail. + content: + application/json: + schema: + $ref: '#/components/schemas/Error400' + Error401Response: + description: > + Unauthorized — missing or invalid `POLYMARKET-PROXY` / + `POLYMARKET-SECRET` + + credentials. `error` is `unauthorized`. + content: + application/json: + schema: + $ref: '#/components/schemas/Error401' + Error429Response: + description: > + Too Many Requests. `error` distinguishes the limit that was hit: + + `ip_rate_limited` (per-IP token bucket), `action_rate_limited` + (per-account + + action rate), or `open_orders_limit` (resting open-order cap). + headers: + Retry-After: + description: > + Whole seconds to wait before retrying. Present only on token-bucket + + rate-limit rejections (`ip_rate_limited` and `action_rate_limited`); + a + + conservative estimate of when enough capacity will have refilled to + + admit the request. Absent on `open_orders_limit`, which is a + capacity + + limit, not a rate limit — waiting does not free order slots; cancel + + resting orders or wait for fills instead. + schema: + type: integer + example: 2 + content: + application/json: + schema: + $ref: '#/components/schemas/Error429' + Error500Response: + description: | + Internal server error. `error` is `internal_error`. + content: + application/json: + schema: + $ref: '#/components/schemas/Error500' + securitySchemes: + polymarket_proxy: + type: apiKey + name: POLYMARKET-PROXY + in: header + description: Proxy address + polymarket_secret: + type: apiKey + name: POLYMARKET-SECRET + in: header + description: Correponding proxy secret + +```` \ No newline at end of file diff --git a/PolymarketDocumentation-main/docs/api-reference/get-public-portfolio.md b/PolymarketDocumentation-main/docs/api-reference/get-public-portfolio.md new file mode 100644 index 00000000..bed1da39 --- /dev/null +++ b/PolymarketDocumentation-main/docs/api-reference/get-public-portfolio.md @@ -0,0 +1,232 @@ +> ## Documentation Index +> Fetch the complete documentation index at: https://docs.polymarket.com/llms.txt +> Use this file to discover all available pages before exploring further. + +# Get Public Portfolio + +> Get public portfolio for an address including equity and open positions. + + +Request Weight: **5** + + +## OpenAPI + +````yaml /api-spec/perps-openapi.json get /v1/info/portfolio +openapi: 3.0.3 +info: + title: Polymarket Perps HTTP API + version: 1.0.0 + description: HTTP API for Polymarket perpetual trading system. + license: + name: Apache 2.0 + url: https://www.apache.org/licenses/LICENSE-2.0.html +servers: + - url: https://api.perpetuals.polymarket.com + description: Production Perps HTTP API +security: [] +paths: + /v1/info/portfolio: + get: + summary: Get Public Portfolio + description: | + Get public portfolio for an address including equity and open positions. + operationId: getPublicPortfolio + parameters: + - name: address + in: query + required: true + schema: + $ref: '#/components/schemas/address' + responses: + '200': + description: Public portfolio response. + content: + application/json: + schema: + $ref: '#/components/schemas/PublicPortfolio' + '400': + $ref: '#/components/responses/Error400Response' + '429': + $ref: '#/components/responses/Error429Response' + '500': + $ref: '#/components/responses/Error500Response' + security: [] +components: + schemas: + address: + type: string + description: Address + example: '0x1234567890abcdef1234567890abcdef12345678' + PublicPortfolio: + type: object + required: + - positions + - equity + - timestamp + properties: + positions: + type: array + items: + $ref: '#/components/schemas/PublicPortfolioPosition' + equity: + $ref: '#/components/schemas/equity' + timestamp: + $ref: '#/components/schemas/update_timestamp' + PublicPortfolioPosition: + type: object + required: + - instrument_id + - symbol + - size + - entry_price + - unrealized_pnl + - return_on_equity + properties: + instrument_id: + $ref: '#/components/schemas/instrument_id' + symbol: + $ref: '#/components/schemas/symbol' + size: + $ref: '#/components/schemas/size' + entry_price: + $ref: '#/components/schemas/entry_price' + unrealized_pnl: + $ref: '#/components/schemas/unrealized_pnl' + return_on_equity: + $ref: '#/components/schemas/return_on_equity' + equity: + type: string + description: Equity in USD + example: '10000.00' + update_timestamp: + type: integer + description: Update timestamp in milliseconds + example: 1767225600000 + Error400: + title: Error400 + type: object + required: + - status + - error + properties: + status: + type: string + enum: + - err + error: + $ref: '#/components/schemas/error' + Error429: + title: Error429 + type: object + required: + - status + - error + properties: + status: + type: string + enum: + - err + error: + $ref: '#/components/schemas/error' + Error500: + title: Error500 + type: object + required: + - status + - error + properties: + status: + type: string + enum: + - err + error: + $ref: '#/components/schemas/error' + instrument_id: + type: integer + description: Instrument ID + symbol: + type: string + description: Instrument symbol + example: NVDA-USDC + size: + type: string + description: >- + Signed position size in no. of contracts (positive = long, negative = + short) + example: '10.00' + entry_price: + type: string + description: Average entry price + example: '2986.30' + unrealized_pnl: + type: string + description: Unrealized PnL in USD + example: '-0.01' + return_on_equity: + type: string + description: Return on equity as a decimal + example: '-0.0027' + error: + type: string + description: >- + Error identifier. For domain rejections and transport errors + (`401`/`404`/`429`/`500`) this is a stable, machine-readable snake_case + identifier that is part of the API contract and safe to branch on, e.g. + `insufficient_margin`, `insufficient_balance`, `order_not_found`, + `reduce_only_invalid`, `unauthorized`, `not_found`. For `400` it is a + human-readable validation detail whose wording may change. See the Error + handling guide for the domain identifiers. (Post-only / Fill-or-Kill + outcomes are order statuses such as `post_only_rejected`, not + rejections.) + example: insufficient_margin + responses: + Error400Response: + description: | + Bad request — the request was malformed or failed validation (bad query + parameters, unparseable body, invalid signature, or a domain pre-check). + The `error` field is a human-readable validation detail. + content: + application/json: + schema: + $ref: '#/components/schemas/Error400' + Error429Response: + description: > + Too Many Requests. `error` distinguishes the limit that was hit: + + `ip_rate_limited` (per-IP token bucket), `action_rate_limited` + (per-account + + action rate), or `open_orders_limit` (resting open-order cap). + headers: + Retry-After: + description: > + Whole seconds to wait before retrying. Present only on token-bucket + + rate-limit rejections (`ip_rate_limited` and `action_rate_limited`); + a + + conservative estimate of when enough capacity will have refilled to + + admit the request. Absent on `open_orders_limit`, which is a + capacity + + limit, not a rate limit — waiting does not free order slots; cancel + + resting orders or wait for fills instead. + schema: + type: integer + example: 2 + content: + application/json: + schema: + $ref: '#/components/schemas/Error429' + Error500Response: + description: | + Internal server error. `error` is `internal_error`. + content: + application/json: + schema: + $ref: '#/components/schemas/Error500' + +```` \ No newline at end of file diff --git a/PolymarketDocumentation-main/docs/api-reference/get-recent-trades.md b/PolymarketDocumentation-main/docs/api-reference/get-recent-trades.md new file mode 100644 index 00000000..737a2ea6 --- /dev/null +++ b/PolymarketDocumentation-main/docs/api-reference/get-recent-trades.md @@ -0,0 +1,256 @@ +> ## Documentation Index +> Fetch the complete documentation index at: https://docs.polymarket.com/llms.txt +> Use this file to discover all available pages before exploring further. + +# Get Recent Trades + +> Get public trades for an instrument. +Maximum of 100 entries returned per request. + + +Request Weight: **10** + + +## OpenAPI + +````yaml /api-spec/perps-openapi.json get /v1/info/trades +openapi: 3.0.3 +info: + title: Polymarket Perps HTTP API + version: 1.0.0 + description: HTTP API for Polymarket perpetual trading system. + license: + name: Apache 2.0 + url: https://www.apache.org/licenses/LICENSE-2.0.html +servers: + - url: https://api.perpetuals.polymarket.com + description: Production Perps HTTP API +security: [] +paths: + /v1/info/trades: + get: + summary: Get Recent Trades + description: | + Get public trades for an instrument. + Maximum of 100 entries returned per request. + operationId: getTrades + parameters: + - name: instrument_id + in: query + required: true + schema: + $ref: '#/components/schemas/instrument_id' + - name: start_timestamp + in: query + required: false + schema: + $ref: '#/components/schemas/start_timestamp' + - name: end_timestamp + in: query + required: false + schema: + $ref: '#/components/schemas/end_timestamp' + responses: + '200': + description: Trades response. + content: + application/json: + schema: + $ref: '#/components/schemas/Trades' + '400': + $ref: '#/components/responses/Error400Response' + '429': + $ref: '#/components/responses/Error429Response' + '500': + $ref: '#/components/responses/Error500Response' + security: [] +components: + schemas: + instrument_id: + type: integer + description: Instrument ID + start_timestamp: + type: integer + description: Start timestamp in milliseconds + example: 1767225600000 + end_timestamp: + type: integer + description: End timestamp in milliseconds + example: 1767229200000 + Trades: + type: object + required: + - data + - more + properties: + data: + type: array + items: + $ref: '#/components/schemas/TradeData' + description: Public trades for the instrument + more: + $ref: '#/components/schemas/more' + TradeData: + type: object + required: + - trade_id + - instrument_id + - side + - price + - quantity + - timestamp + - hash + properties: + trade_id: + $ref: '#/components/schemas/tid' + instrument_id: + $ref: '#/components/schemas/iid' + side: + $ref: '#/components/schemas/side' + price: + $ref: '#/components/schemas/p' + quantity: + $ref: '#/components/schemas/qty' + timestamp: + $ref: '#/components/schemas/ts' + hash: + $ref: '#/components/schemas/hash' + more: + type: boolean + description: More data available + Error400: + title: Error400 + type: object + required: + - status + - error + properties: + status: + type: string + enum: + - err + error: + $ref: '#/components/schemas/error' + Error429: + title: Error429 + type: object + required: + - status + - error + properties: + status: + type: string + enum: + - err + error: + $ref: '#/components/schemas/error' + Error500: + title: Error500 + type: object + required: + - status + - error + properties: + status: + type: string + enum: + - err + error: + $ref: '#/components/schemas/error' + tid: + type: integer + description: Trade ID + example: 1 + iid: + type: integer + description: Instrument ID + example: 1 + side: + type: string + description: Side + enum: + - long + - short + p: + type: string + description: Price + example: '100.00' + qty: + type: string + description: Quantity in no. of contracts + example: '10.00' + ts: + type: integer + description: >- + Request timestamp. Unix milliseconds for most operations; Unix seconds + for withdrawals (must match the on-chain EIP-712 struct verified against + block.timestamp). + example: 1767225600000 + hash: + type: string + description: On-chain transaction hash, "0x" if not yet mined + default: 0x + example: '0x1234567890abcdef1234567890abcdef1234567890abcdef1234567890abcdef' + error: + type: string + description: >- + Error identifier. For domain rejections and transport errors + (`401`/`404`/`429`/`500`) this is a stable, machine-readable snake_case + identifier that is part of the API contract and safe to branch on, e.g. + `insufficient_margin`, `insufficient_balance`, `order_not_found`, + `reduce_only_invalid`, `unauthorized`, `not_found`. For `400` it is a + human-readable validation detail whose wording may change. See the Error + handling guide for the domain identifiers. (Post-only / Fill-or-Kill + outcomes are order statuses such as `post_only_rejected`, not + rejections.) + example: insufficient_margin + responses: + Error400Response: + description: | + Bad request — the request was malformed or failed validation (bad query + parameters, unparseable body, invalid signature, or a domain pre-check). + The `error` field is a human-readable validation detail. + content: + application/json: + schema: + $ref: '#/components/schemas/Error400' + Error429Response: + description: > + Too Many Requests. `error` distinguishes the limit that was hit: + + `ip_rate_limited` (per-IP token bucket), `action_rate_limited` + (per-account + + action rate), or `open_orders_limit` (resting open-order cap). + headers: + Retry-After: + description: > + Whole seconds to wait before retrying. Present only on token-bucket + + rate-limit rejections (`ip_rate_limited` and `action_rate_limited`); + a + + conservative estimate of when enough capacity will have refilled to + + admit the request. Absent on `open_orders_limit`, which is a + capacity + + limit, not a rate limit — waiting does not free order slots; cancel + + resting orders or wait for fills instead. + schema: + type: integer + example: 2 + content: + application/json: + schema: + $ref: '#/components/schemas/Error429' + Error500Response: + description: | + Internal server error. `error` is `internal_error`. + content: + application/json: + schema: + $ref: '#/components/schemas/Error500' + +```` \ No newline at end of file diff --git a/PolymarketDocumentation-main/docs/api-reference/get-server-time.md b/PolymarketDocumentation-main/docs/api-reference/get-server-time.md new file mode 100644 index 00000000..9bd604b9 --- /dev/null +++ b/PolymarketDocumentation-main/docs/api-reference/get-server-time.md @@ -0,0 +1,139 @@ +> ## Documentation Index +> Fetch the complete documentation index at: https://docs.polymarket.com/llms.txt +> Use this file to discover all available pages before exploring further. + +# Get Server Time + +> Get server time. + + +Request Weight: **1** + + +## OpenAPI + +````yaml /api-spec/perps-openapi.json get /v1/info/time +openapi: 3.0.3 +info: + title: Polymarket Perps HTTP API + version: 1.0.0 + description: HTTP API for Polymarket perpetual trading system. + license: + name: Apache 2.0 + url: https://www.apache.org/licenses/LICENSE-2.0.html +servers: + - url: https://api.perpetuals.polymarket.com + description: Production Perps HTTP API +security: [] +paths: + /v1/info/time: + get: + summary: Get Server Time + description: | + Get server time. + operationId: getTime + responses: + '200': + description: Successful time response. + content: + application/json: + schema: + $ref: '#/components/schemas/Time' + '429': + $ref: '#/components/responses/Error429Response' + '500': + $ref: '#/components/responses/Error500Response' + security: [] +components: + schemas: + Time: + type: object + required: + - time + properties: + time: + $ref: '#/components/schemas/time' + time: + type: integer + description: Timestamp in milliseconds + example: 1767225600000 + Error429: + title: Error429 + type: object + required: + - status + - error + properties: + status: + type: string + enum: + - err + error: + $ref: '#/components/schemas/error' + Error500: + title: Error500 + type: object + required: + - status + - error + properties: + status: + type: string + enum: + - err + error: + $ref: '#/components/schemas/error' + error: + type: string + description: >- + Error identifier. For domain rejections and transport errors + (`401`/`404`/`429`/`500`) this is a stable, machine-readable snake_case + identifier that is part of the API contract and safe to branch on, e.g. + `insufficient_margin`, `insufficient_balance`, `order_not_found`, + `reduce_only_invalid`, `unauthorized`, `not_found`. For `400` it is a + human-readable validation detail whose wording may change. See the Error + handling guide for the domain identifiers. (Post-only / Fill-or-Kill + outcomes are order statuses such as `post_only_rejected`, not + rejections.) + example: insufficient_margin + responses: + Error429Response: + description: > + Too Many Requests. `error` distinguishes the limit that was hit: + + `ip_rate_limited` (per-IP token bucket), `action_rate_limited` + (per-account + + action rate), or `open_orders_limit` (resting open-order cap). + headers: + Retry-After: + description: > + Whole seconds to wait before retrying. Present only on token-bucket + + rate-limit rejections (`ip_rate_limited` and `action_rate_limited`); + a + + conservative estimate of when enough capacity will have refilled to + + admit the request. Absent on `open_orders_limit`, which is a + capacity + + limit, not a rate limit — waiting does not free order slots; cancel + + resting orders or wait for fills instead. + schema: + type: integer + example: 2 + content: + application/json: + schema: + $ref: '#/components/schemas/Error429' + Error500Response: + description: | + Internal server error. `error` is `internal_error`. + content: + application/json: + schema: + $ref: '#/components/schemas/Error500' + +```` \ No newline at end of file diff --git a/PolymarketDocumentation-main/docs/api-reference/get-statistics.md b/PolymarketDocumentation-main/docs/api-reference/get-statistics.md new file mode 100644 index 00000000..03772845 --- /dev/null +++ b/PolymarketDocumentation-main/docs/api-reference/get-statistics.md @@ -0,0 +1,195 @@ +> ## Documentation Index +> Fetch the complete documentation index at: https://docs.polymarket.com/llms.txt +> Use this file to discover all available pages before exploring further. + +# Get Statistics + +> Get last 24-hour statistics for all instruments. + +Request Weight: **2** + + +## OpenAPI + +````yaml /api-spec/perps-openapi.json get /v1/info/statistics +openapi: 3.0.3 +info: + title: Polymarket Perps HTTP API + version: 1.0.0 + description: HTTP API for Polymarket perpetual trading system. + license: + name: Apache 2.0 + url: https://www.apache.org/licenses/LICENSE-2.0.html +servers: + - url: https://api.perpetuals.polymarket.com + description: Production Perps HTTP API +security: [] +paths: + /v1/info/statistics: + get: + summary: Get Statistics + description: Get last 24-hour statistics for all instruments. + operationId: getStatistics + parameters: + - name: instrument_id + in: query + required: false + schema: + $ref: '#/components/schemas/instrument_id' + responses: + '200': + description: Statistics response. + content: + application/json: + schema: + type: array + items: + $ref: '#/components/schemas/Statistic' + '429': + $ref: '#/components/responses/Error429Response' + '500': + $ref: '#/components/responses/Error500Response' + security: [] +components: + schemas: + instrument_id: + type: integer + description: Instrument ID + Statistic: + type: object + required: + - instrument_id + - symbol + - volume + - open_price + - klines + properties: + instrument_id: + $ref: '#/components/schemas/iid' + symbol: + $ref: '#/components/schemas/symbol' + volume: + $ref: '#/components/schemas/volume' + open_price: + $ref: '#/components/schemas/open_price' + klines: + $ref: '#/components/schemas/klines' + iid: + type: integer + description: Instrument ID + example: 1 + symbol: + type: string + description: Instrument symbol + example: NVDA-USDC + volume: + type: string + description: 24-hour trading volume in contracts + example: '1000.00' + open_price: + type: string + description: Opening price from 24 hours ago + example: '100.50' + klines: + type: array + items: + $ref: '#/components/schemas/kline' + description: Last 24-hour kline data + Error429: + title: Error429 + type: object + required: + - status + - error + properties: + status: + type: string + enum: + - err + error: + $ref: '#/components/schemas/error' + Error500: + title: Error500 + type: object + required: + - status + - error + properties: + status: + type: string + enum: + - err + error: + $ref: '#/components/schemas/error' + kline: + type: array + description: | + - `1767225600000` - Open time + - `"100.00"` - Open price + - `"105.00"` - High price + - `"99.00"` - Low price + - `"102.00"` - Close price + - `"500.00"` - Volume (base unit) + - `42` - Number of trades + example: + - 1767225600000 + - '100.00' + - '105.00' + - '99.00' + - '102.00' + - '500.00' + - 42 + error: + type: string + description: >- + Error identifier. For domain rejections and transport errors + (`401`/`404`/`429`/`500`) this is a stable, machine-readable snake_case + identifier that is part of the API contract and safe to branch on, e.g. + `insufficient_margin`, `insufficient_balance`, `order_not_found`, + `reduce_only_invalid`, `unauthorized`, `not_found`. For `400` it is a + human-readable validation detail whose wording may change. See the Error + handling guide for the domain identifiers. (Post-only / Fill-or-Kill + outcomes are order statuses such as `post_only_rejected`, not + rejections.) + example: insufficient_margin + responses: + Error429Response: + description: > + Too Many Requests. `error` distinguishes the limit that was hit: + + `ip_rate_limited` (per-IP token bucket), `action_rate_limited` + (per-account + + action rate), or `open_orders_limit` (resting open-order cap). + headers: + Retry-After: + description: > + Whole seconds to wait before retrying. Present only on token-bucket + + rate-limit rejections (`ip_rate_limited` and `action_rate_limited`); + a + + conservative estimate of when enough capacity will have refilled to + + admit the request. Absent on `open_orders_limit`, which is a + capacity + + limit, not a rate limit — waiting does not free order slots; cancel + + resting orders or wait for fills instead. + schema: + type: integer + example: 2 + content: + application/json: + schema: + $ref: '#/components/schemas/Error429' + Error500Response: + description: | + Internal server error. `error` is `internal_error`. + content: + application/json: + schema: + $ref: '#/components/schemas/Error500' + +```` \ No newline at end of file diff --git a/PolymarketDocumentation-main/docs/api-reference/get-tickers.md b/PolymarketDocumentation-main/docs/api-reference/get-tickers.md new file mode 100644 index 00000000..56213db3 --- /dev/null +++ b/PolymarketDocumentation-main/docs/api-reference/get-tickers.md @@ -0,0 +1,213 @@ +> ## Documentation Index +> Fetch the complete documentation index at: https://docs.polymarket.com/llms.txt +> Use this file to discover all available pages before exploring further. + +# Get Tickers + +> Get all instrument tickers with live market data. + +Request Weight: **2** + + +## OpenAPI + +````yaml /api-spec/perps-openapi.json get /v1/info/tickers +openapi: 3.0.3 +info: + title: Polymarket Perps HTTP API + version: 1.0.0 + description: HTTP API for Polymarket perpetual trading system. + license: + name: Apache 2.0 + url: https://www.apache.org/licenses/LICENSE-2.0.html +servers: + - url: https://api.perpetuals.polymarket.com + description: Production Perps HTTP API +security: [] +paths: + /v1/info/tickers: + get: + summary: Get Tickers + description: Get all instrument tickers with live market data. + operationId: getTickers + parameters: + - name: instrument_id + in: query + required: false + schema: + $ref: '#/components/schemas/instrument_id' + responses: + '200': + description: Tickers response. + content: + application/json: + schema: + type: array + items: + $ref: '#/components/schemas/Ticker' + '429': + $ref: '#/components/responses/Error429Response' + '500': + $ref: '#/components/responses/Error500Response' + security: [] +components: + schemas: + instrument_id: + type: integer + description: Instrument ID + Ticker: + allOf: + - $ref: '#/components/schemas/TickerData' + - type: object + required: + - timestamp + properties: + timestamp: + $ref: '#/components/schemas/timestamp' + TickerData: + type: object + required: + - instrument_id + - symbol + - index_price + - mark_price + - last_price + - mid_price + - open_interest + - funding_rate + - next_funding + properties: + instrument_id: + $ref: '#/components/schemas/instrument_id' + symbol: + $ref: '#/components/schemas/symbol' + index_price: + $ref: '#/components/schemas/index_price' + mark_price: + $ref: '#/components/schemas/mark_price' + last_price: + $ref: '#/components/schemas/last_price' + mid_price: + $ref: '#/components/schemas/mid_price' + open_interest: + $ref: '#/components/schemas/open_interest' + funding_rate: + $ref: '#/components/schemas/funding_rate' + next_funding: + $ref: '#/components/schemas/next_funding' + timestamp: + type: integer + description: Timestamp in milliseconds + example: 1767225600000 + Error429: + title: Error429 + type: object + required: + - status + - error + properties: + status: + type: string + enum: + - err + error: + $ref: '#/components/schemas/error' + Error500: + title: Error500 + type: object + required: + - status + - error + properties: + status: + type: string + enum: + - err + error: + $ref: '#/components/schemas/error' + symbol: + type: string + description: Instrument symbol + example: NVDA-USDC + index_price: + type: string + description: Index price + example: '100.00' + mark_price: + type: string + description: Mark price + example: '100.00' + last_price: + type: string + description: Last traded price + example: '100.00' + mid_price: + type: string + description: Mid price + example: '100.00' + open_interest: + type: string + description: Open interest in number of contracts + example: '10.00' + funding_rate: + type: string + description: Funding rate + example: '0.0001' + next_funding: + type: integer + description: Next funding timestamp in milliseconds + example: 1767225600000 + error: + type: string + description: >- + Error identifier. For domain rejections and transport errors + (`401`/`404`/`429`/`500`) this is a stable, machine-readable snake_case + identifier that is part of the API contract and safe to branch on, e.g. + `insufficient_margin`, `insufficient_balance`, `order_not_found`, + `reduce_only_invalid`, `unauthorized`, `not_found`. For `400` it is a + human-readable validation detail whose wording may change. See the Error + handling guide for the domain identifiers. (Post-only / Fill-or-Kill + outcomes are order statuses such as `post_only_rejected`, not + rejections.) + example: insufficient_margin + responses: + Error429Response: + description: > + Too Many Requests. `error` distinguishes the limit that was hit: + + `ip_rate_limited` (per-IP token bucket), `action_rate_limited` + (per-account + + action rate), or `open_orders_limit` (resting open-order cap). + headers: + Retry-After: + description: > + Whole seconds to wait before retrying. Present only on token-bucket + + rate-limit rejections (`ip_rate_limited` and `action_rate_limited`); + a + + conservative estimate of when enough capacity will have refilled to + + admit the request. Absent on `open_orders_limit`, which is a + capacity + + limit, not a rate limit — waiting does not free order slots; cancel + + resting orders or wait for fills instead. + schema: + type: integer + example: 2 + content: + application/json: + schema: + $ref: '#/components/schemas/Error429' + Error500Response: + description: | + Internal server error. `error` is `internal_error`. + content: + application/json: + schema: + $ref: '#/components/schemas/Error500' + +```` \ No newline at end of file diff --git a/PolymarketDocumentation-main/docs/api-reference/get-withdrawals.md b/PolymarketDocumentation-main/docs/api-reference/get-withdrawals.md new file mode 100644 index 00000000..75d66573 --- /dev/null +++ b/PolymarketDocumentation-main/docs/api-reference/get-withdrawals.md @@ -0,0 +1,325 @@ +> ## Documentation Index +> Fetch the complete documentation index at: https://docs.polymarket.com/llms.txt +> Use this file to discover all available pages before exploring further. + +# Get Withdrawals + +> Get withdrawal history for the authenticated account. +If no end time is provided, the current time will be used. +Maximum of 100 entries returned per request. + + +Request Weight: **10** + + +## OpenAPI + +````yaml /api-spec/perps-openapi.json get /v1/account/withdrawals +openapi: 3.0.3 +info: + title: Polymarket Perps HTTP API + version: 1.0.0 + description: HTTP API for Polymarket perpetual trading system. + license: + name: Apache 2.0 + url: https://www.apache.org/licenses/LICENSE-2.0.html +servers: + - url: https://api.perpetuals.polymarket.com + description: Production Perps HTTP API +security: [] +paths: + /v1/account/withdrawals: + get: + summary: Get Withdrawals + description: | + Get withdrawal history for the authenticated account. + If no end time is provided, the current time will be used. + Maximum of 100 entries returned per request. + operationId: getWithdrawals + parameters: + - name: withdrawal_status + in: query + required: false + schema: + $ref: '#/components/schemas/withdrawal_status' + - name: hash + in: query + required: false + schema: + $ref: '#/components/schemas/hash' + - name: start_timestamp + in: query + required: false + schema: + $ref: '#/components/schemas/start_timestamp' + - name: end_timestamp + in: query + required: false + schema: + $ref: '#/components/schemas/end_timestamp' + responses: + '200': + description: Withdrawal history response. + content: + application/json: + schema: + $ref: '#/components/schemas/Withdrawals' + '400': + $ref: '#/components/responses/Error400Response' + '401': + $ref: '#/components/responses/Error401Response' + '429': + $ref: '#/components/responses/Error429Response' + '500': + $ref: '#/components/responses/Error500Response' + security: + - polymarket_proxy: [] + polymarket_secret: [] +components: + schemas: + withdrawal_status: + type: string + description: Withdrawal status + enum: + - pending + - confirmed + - removed + - failed + hash: + type: string + description: On-chain transaction hash, "0x" if not yet mined + default: 0x + example: '0x1234567890abcdef1234567890abcdef1234567890abcdef1234567890abcdef' + start_timestamp: + type: integer + description: Start timestamp in milliseconds + example: 1767225600000 + end_timestamp: + type: integer + description: End timestamp in milliseconds + example: 1767229200000 + Withdrawals: + type: object + required: + - data + - more + properties: + data: + type: array + items: + $ref: '#/components/schemas/Withdrawal' + more: + $ref: '#/components/schemas/more' + Withdrawal: + type: object + required: + - withdraw_id + - asset + - amount + - fee + - status + - to + - hash + - confirmations + - required_confirmations + - created_timestamp + properties: + withdraw_id: + $ref: '#/components/schemas/withdraw_id' + asset: + $ref: '#/components/schemas/asset' + amount: + $ref: '#/components/schemas/amount' + to: + $ref: '#/components/schemas/to' + fee: + $ref: '#/components/schemas/withdrawal_fee' + status: + $ref: '#/components/schemas/withdrawal_status' + hash: + $ref: '#/components/schemas/hash' + confirmations: + $ref: '#/components/schemas/confirmations' + required_confirmations: + $ref: '#/components/schemas/required_confirmations' + created_timestamp: + $ref: '#/components/schemas/created_timestamp' + confirmed_timestamp: + $ref: '#/components/schemas/confirmed_timestamp' + more: + type: boolean + description: More data available + Error400: + title: Error400 + type: object + required: + - status + - error + properties: + status: + type: string + enum: + - err + error: + $ref: '#/components/schemas/error' + Error401: + title: Error401 + type: object + required: + - status + - error + properties: + status: + type: string + enum: + - err + error: + $ref: '#/components/schemas/error' + Error429: + title: Error429 + type: object + required: + - status + - error + properties: + status: + type: string + enum: + - err + error: + $ref: '#/components/schemas/error' + Error500: + title: Error500 + type: object + required: + - status + - error + properties: + status: + type: string + enum: + - err + error: + $ref: '#/components/schemas/error' + withdraw_id: + type: integer + description: Withdraw ID + asset: + type: string + description: Asset name + example: USDC + amount: + type: string + description: >- + Raw token amount including decimals. For withdrawals this matches the + uint256 amount in the EIP-712 signature (e.g. "100000000" for 100 USDC + with 6 decimals). + example: '100000000' + to: + type: string + description: Destination address in hex format + example: '0x1234567890abcdef1234567890abcdef12345678' + withdrawal_fee: + type: string + description: Withdrawal transaction fee in decimalized asset units + example: '5.00' + confirmations: + type: integer + description: Number of block confirmations + example: 12 + required_confirmations: + type: integer + description: Required number of block confirmations + example: 12 + created_timestamp: + type: integer + description: Creation timestamp in milliseconds + example: 1767225600000 + confirmed_timestamp: + type: integer + description: Confirmation timestamp in milliseconds + example: 1767225600000 + error: + type: string + description: >- + Error identifier. For domain rejections and transport errors + (`401`/`404`/`429`/`500`) this is a stable, machine-readable snake_case + identifier that is part of the API contract and safe to branch on, e.g. + `insufficient_margin`, `insufficient_balance`, `order_not_found`, + `reduce_only_invalid`, `unauthorized`, `not_found`. For `400` it is a + human-readable validation detail whose wording may change. See the Error + handling guide for the domain identifiers. (Post-only / Fill-or-Kill + outcomes are order statuses such as `post_only_rejected`, not + rejections.) + example: insufficient_margin + responses: + Error400Response: + description: | + Bad request — the request was malformed or failed validation (bad query + parameters, unparseable body, invalid signature, or a domain pre-check). + The `error` field is a human-readable validation detail. + content: + application/json: + schema: + $ref: '#/components/schemas/Error400' + Error401Response: + description: > + Unauthorized — missing or invalid `POLYMARKET-PROXY` / + `POLYMARKET-SECRET` + + credentials. `error` is `unauthorized`. + content: + application/json: + schema: + $ref: '#/components/schemas/Error401' + Error429Response: + description: > + Too Many Requests. `error` distinguishes the limit that was hit: + + `ip_rate_limited` (per-IP token bucket), `action_rate_limited` + (per-account + + action rate), or `open_orders_limit` (resting open-order cap). + headers: + Retry-After: + description: > + Whole seconds to wait before retrying. Present only on token-bucket + + rate-limit rejections (`ip_rate_limited` and `action_rate_limited`); + a + + conservative estimate of when enough capacity will have refilled to + + admit the request. Absent on `open_orders_limit`, which is a + capacity + + limit, not a rate limit — waiting does not free order slots; cancel + + resting orders or wait for fills instead. + schema: + type: integer + example: 2 + content: + application/json: + schema: + $ref: '#/components/schemas/Error429' + Error500Response: + description: | + Internal server error. `error` is `internal_error`. + content: + application/json: + schema: + $ref: '#/components/schemas/Error500' + securitySchemes: + polymarket_proxy: + type: apiKey + name: POLYMARKET-PROXY + in: header + description: Proxy address + polymarket_secret: + type: apiKey + name: POLYMARKET-SECRET + in: header + description: Correponding proxy secret + +```` \ No newline at end of file diff --git a/PolymarketDocumentation-main/docs/api-reference/internal-transfer.md b/PolymarketDocumentation-main/docs/api-reference/internal-transfer.md new file mode 100644 index 00000000..4b0580b4 --- /dev/null +++ b/PolymarketDocumentation-main/docs/api-reference/internal-transfer.md @@ -0,0 +1,304 @@ +> ## Documentation Index +> Fetch the complete documentation index at: https://docs.polymarket.com/llms.txt +> Use this file to discover all available pages before exploring further. + +# Internal Transfer + +> Submit a signed internal ledger transfer between two exchange accounts. +Requires proxy signature using the standard signed-op flow. + + +Request Weight: **1** + + +## OpenAPI + +````yaml /api-spec/perps-openapi.json post /v1/account/internal-transfer +openapi: 3.0.3 +info: + title: Polymarket Perps HTTP API + version: 1.0.0 + description: HTTP API for Polymarket perpetual trading system. + license: + name: Apache 2.0 + url: https://www.apache.org/licenses/LICENSE-2.0.html +servers: + - url: https://api.perpetuals.polymarket.com + description: Production Perps HTTP API +security: [] +paths: + /v1/account/internal-transfer: + post: + summary: Internal Transfer + description: | + Submit a signed internal ledger transfer between two exchange accounts. + Requires proxy signature using the standard signed-op flow. + operationId: internalTransfer + requestBody: + description: Internal transfer request. + content: + application/json: + schema: + $ref: '#/components/schemas/InternalTransferRequest' + examples: + transfer: + summary: Transfer USDC to another account + value: + op: + type: internalTransfer + args: + account: '0xf39Fd6e51aad88F6F4ce6aB8827279cffFb92266' + token: '0xaf88d065e77c8cc2239327c5edb3a432268e5831' + amount: '100.00' + to: '0x70997970C51812dc3A010C7d01b50e0d17dc79C8' + sig: >- + 0x5a6b7c8d9e0f1a2b3c4d5e6f7a8b9c0d1e2f3a4b5c6d7e8f9a0b1c2d3e4f5a6b7c8d9e0f1a2b3c4d5e6f7a8b9c0d1e2f3a4b5c6d7e8f9a0b1c2d3e4f5a1c + salt: 555555555 + ts: 1767000014000 + label: ops-rebalance + responses: + '200': + description: The accepted transfer, carrying its `transfer_id`. + content: + application/json: + schema: + $ref: '#/components/schemas/InternalTransferAccepted' + '400': + $ref: '#/components/responses/Error400Response' + '422': + description: | + The transfer was rejected on its merits (e.g. insufficient balance, + transfer to self). The body carries `transfer_id` and `error`. + content: + application/json: + schema: + $ref: '#/components/schemas/InternalTransferRejected' + '429': + $ref: '#/components/responses/Error429Response' + '500': + $ref: '#/components/responses/Error500Response' + security: [] +components: + schemas: + InternalTransferRequest: + allOf: + - type: object + required: + - op + properties: + op: + $ref: '#/components/schemas/OpInternalTransfer' + - $ref: '#/components/schemas/BaseOp' + - type: object + properties: + label: + $ref: '#/components/schemas/label' + InternalTransferAccepted: + type: object + required: + - status + - transfer_id + properties: + status: + type: string + enum: + - ok + transfer_id: + $ref: '#/components/schemas/transfer_id' + InternalTransferRejected: + type: object + required: + - status + - transfer_id + - error + properties: + status: + type: string + enum: + - err + transfer_id: + $ref: '#/components/schemas/transfer_id' + error: + $ref: '#/components/schemas/error' + OpInternalTransfer: + type: object + required: + - type + - args + properties: + type: + type: string + enum: + - internalTransfer + args: + type: object + required: + - account + - token + - amount + - to + properties: + account: + $ref: '#/components/schemas/account' + token: + $ref: '#/components/schemas/token' + amount: + $ref: '#/components/schemas/amount' + to: + $ref: '#/components/schemas/to' + BaseOp: + type: object + required: + - sig + - salt + - ts + properties: + sig: + $ref: '#/components/schemas/sig' + salt: + $ref: '#/components/schemas/salt' + ts: + $ref: '#/components/schemas/ts' + label: + type: string + description: Human-readable label for a proxy key or internal transfer + example: trading-bot + transfer_id: + type: integer + description: Internal transfer ID + Error400: + title: Error400 + type: object + required: + - status + - error + properties: + status: + type: string + enum: + - err + error: + $ref: '#/components/schemas/error' + error: + type: string + description: >- + Error identifier. For domain rejections and transport errors + (`401`/`404`/`429`/`500`) this is a stable, machine-readable snake_case + identifier that is part of the API contract and safe to branch on, e.g. + `insufficient_margin`, `insufficient_balance`, `order_not_found`, + `reduce_only_invalid`, `unauthorized`, `not_found`. For `400` it is a + human-readable validation detail whose wording may change. See the Error + handling guide for the domain identifiers. (Post-only / Fill-or-Kill + outcomes are order statuses such as `post_only_rejected`, not + rejections.) + example: insufficient_margin + Error429: + title: Error429 + type: object + required: + - status + - error + properties: + status: + type: string + enum: + - err + error: + $ref: '#/components/schemas/error' + Error500: + title: Error500 + type: object + required: + - status + - error + properties: + status: + type: string + enum: + - err + error: + $ref: '#/components/schemas/error' + account: + type: string + description: Account address in hex format + example: '0xf39Fd6e51aad88F6F4ce6aB8827279cffFb92266' + token: + type: string + description: Token contract address in hex format + example: '0xaf88d065e77c8cc2239327c5edb3a432268e5831' + amount: + type: string + description: >- + Raw token amount including decimals. For withdrawals this matches the + uint256 amount in the EIP-712 signature (e.g. "100000000" for 100 USDC + with 6 decimals). + example: '100000000' + to: + type: string + description: Destination address in hex format + example: '0x1234567890abcdef1234567890abcdef12345678' + sig: + type: string + description: Signature in hex format + example: 0x1234567890... + salt: + type: integer + description: Salt + example: 1234567890 + ts: + type: integer + description: >- + Request timestamp. Unix milliseconds for most operations; Unix seconds + for withdrawals (must match the on-chain EIP-712 struct verified against + block.timestamp). + example: 1767225600000 + responses: + Error400Response: + description: | + Bad request — the request was malformed or failed validation (bad query + parameters, unparseable body, invalid signature, or a domain pre-check). + The `error` field is a human-readable validation detail. + content: + application/json: + schema: + $ref: '#/components/schemas/Error400' + Error429Response: + description: > + Too Many Requests. `error` distinguishes the limit that was hit: + + `ip_rate_limited` (per-IP token bucket), `action_rate_limited` + (per-account + + action rate), or `open_orders_limit` (resting open-order cap). + headers: + Retry-After: + description: > + Whole seconds to wait before retrying. Present only on token-bucket + + rate-limit rejections (`ip_rate_limited` and `action_rate_limited`); + a + + conservative estimate of when enough capacity will have refilled to + + admit the request. Absent on `open_orders_limit`, which is a + capacity + + limit, not a rate limit — waiting does not free order slots; cancel + + resting orders or wait for fills instead. + schema: + type: integer + example: 2 + content: + application/json: + schema: + $ref: '#/components/schemas/Error429' + Error500Response: + description: | + Internal server error. `error` is `internal_error`. + content: + application/json: + schema: + $ref: '#/components/schemas/Error500' + +```` \ No newline at end of file diff --git a/PolymarketDocumentation-main/docs/api-reference/introduction.md b/PolymarketDocumentation-main/docs/api-reference/introduction.md new file mode 100644 index 00000000..003f8c4b --- /dev/null +++ b/PolymarketDocumentation-main/docs/api-reference/introduction.md @@ -0,0 +1,59 @@ +> ## Documentation Index +> Fetch the complete documentation index at: https://docs.polymarket.com/llms.txt +> Use this file to discover all available pages before exploring further. + +# Introduction + +> Overview of the Polymarket APIs + +The Polymarket API provides programmatic access to the world's largest prediction market. The platform is served by three separate APIs, each handling a different domain. + +*** + +## APIs + + + + **`https://gamma-api.polymarket.com`** + + Markets, events, tags, series, comments, sports, search, and public profiles. This is the primary API for discovering and browsing market data. + + + + **`https://data-api.polymarket.com`** + + User positions, trades, activity, holder data, open interest, leaderboards, and builder analytics. + + + + **`https://clob.polymarket.com`** + + Orderbook data, pricing, midpoints, spreads, and price history. Also handles order placement, cancellation, and other trading operations. Trading endpoints require [authentication](/api-reference/authentication). + + + + + A separate **Bridge API** (`https://bridge.polymarket.com`) handles deposits and withdrawals. Bridges are not handled by Polymarket, it is a proxy of fun.xyz service. + + +*** + +## Authentication + +The Gamma API and Data API are fully public — no authentication required. + +The CLOB API has both public endpoints (orderbook, prices) and authenticated endpoints (order management). See [Authentication](/api-reference/authentication) for details. + +*** + +## Next Steps + + + + Learn how to authenticate requests for trading endpoints. + + + + Official TypeScript, Python, and Rust libraries. + + diff --git a/PolymarketDocumentation-main/docs/api-reference/maker/cancel-a-quote.md b/PolymarketDocumentation-main/docs/api-reference/maker/cancel-a-quote.md new file mode 100644 index 00000000..9ecc49b5 --- /dev/null +++ b/PolymarketDocumentation-main/docs/api-reference/maker/cancel-a-quote.md @@ -0,0 +1,435 @@ +> ## Documentation Index +> Fetch the complete documentation index at: https://docs.polymarket.com/llms.txt +> Use this file to discover all available pages before exploring further. + +# Cancel a quote + +> Cancel an active maker quote before it is selected. Requires CLOB L2 +authentication for the maker role. `signer_address` and `maker_address` +must match the authenticated identity. + + + + +## OpenAPI + +````yaml /api-spec/combos-rfq-openapi.yaml post /v1/maker/quotes/cancel +openapi: 3.1.0 +info: + title: Polymarket Combinatorial RFQ API + description: > + REST API for the combinatorial RFQ (Request for Quote) system. + + + This spec covers the publicly documented endpoints used by quoters (market + + makers): the combo-market catalog and the authenticated maker commands for + + submitting, cancelling, and confirming quotes. + + + Conventions: + + - All `*_e6` fields are six-decimal fixed-point values encoded as + **strings** + to avoid number precision issues. + - All timestamps are **Unix milliseconds** (integer); zero/omitted means + unset. + + - Errors return an HTTP status code with a body of the form `{ "error": + "..." }`. + license: + name: MIT + identifier: MIT + version: 1.0.0 +servers: + - url: https://combos-rfq-api.polymarket.com + description: Production combinatorial RFQ API +security: [] +tags: + - name: Combo Markets + description: Public catalog of markets that can be used as combo legs + - name: Maker + description: Authenticated quoter (maker) commands +paths: + /v1/maker/quotes/cancel: + post: + tags: + - Maker + summary: Cancel a quote + description: | + Cancel an active maker quote before it is selected. Requires CLOB L2 + authentication for the maker role. `signer_address` and `maker_address` + must match the authenticated identity. + operationId: cancelMakerQuote + requestBody: + required: true + content: + application/json: + schema: + $ref: '#/components/schemas/CancelQuoteRequest' + example: + rfq_id: rfq_ + quote_id: quote_ + signer_address: 0xYourSigner + maker_address: 0xYourQuoterWallet + signature_type: 0 + responses: + '200': + description: Current RFQ snapshot after the cancellation was applied + content: + application/json: + schema: + $ref: '#/components/schemas/RFQSnapshot' + '400': + $ref: '#/components/responses/BadRequest' + '401': + $ref: '#/components/responses/Unauthorized' + '403': + $ref: '#/components/responses/Forbidden' + '404': + $ref: '#/components/responses/NotFound' + '409': + $ref: '#/components/responses/Conflict' + '429': + $ref: '#/components/responses/TooManyRequests' + '503': + $ref: '#/components/responses/ServiceUnavailable' + security: + - polyApiKey: [] + polyAddress: [] + polySignature: [] + polyPassphrase: [] + polyTimestamp: [] +components: + schemas: + CancelQuoteRequest: + type: object + properties: + rfq_id: + type: string + example: rfq_ + quote_id: + type: string + example: quote_ + signer_address: + type: string + description: Must match the authenticated `signer_address`. + example: 0xYourSigner + maker_address: + type: string + description: Must match the authenticated `maker_address`. + example: 0xYourQuoterWallet + signature_type: + $ref: '#/components/schemas/SignatureType' + required: + - rfq_id + - quote_id + - signer_address + - maker_address + - signature_type + RFQSnapshot: + type: object + description: Point-in-time view of an RFQ and its competition/confirmation windows. + properties: + request: + $ref: '#/components/schemas/RFQRequest' + status: + $ref: '#/components/schemas/RFQStatus' + competition_started_at: + type: integer + format: int64 + description: Unix milliseconds. + competition_ends_at: + type: integer + format: int64 + description: Unix milliseconds. + confirmation_started_at: + type: integer + format: int64 + description: Unix milliseconds. + confirmation_ends_at: + type: integer + format: int64 + description: Unix milliseconds. + quote_id: + type: string + bundle: + $ref: '#/components/schemas/FillBundle' + maker_confirmations: + type: array + items: + $ref: '#/components/schemas/MakerConfirmationSnapshot' + required: + - request + - status + SignatureType: + type: integer + description: | + CLOB signature type: + - `0` EOA + - `1` POLY_PROXY + - `2` GNOSIS_SAFE + - `3` POLY_1271 + enum: + - 0 + - 1 + - 2 + - 3 + example: 0 + RFQRequest: + type: object + description: The RFQ request as stored by the engine. + properties: + rfq_id: + type: string + auth_address: + type: string + signer_address: + type: string + maker_address: + type: string + signature_type: + $ref: '#/components/schemas/SignatureType' + requestor_public_id: + type: string + leg_position_ids: + type: array + items: + type: string + condition_id: + type: string + yes_position_id: + type: string + no_position_id: + type: string + direction: + $ref: '#/components/schemas/Direction' + side: + $ref: '#/components/schemas/Side' + requested_size: + $ref: '#/components/schemas/RequestedSize' + created_at: + type: integer + format: int64 + description: Creation time in Unix milliseconds. + required: + - rfq_id + - leg_position_ids + - direction + - side + RFQStatus: + type: string + description: Lifecycle status of the RFQ + enum: + - CREATED + - COLLECTING_QUOTES + - AWAITING_REQUESTER_ACCEPTANCE + - AWAITING_MAKER_CONFIRMATION + - EXECUTING + - FILLED + - FAILED + - EXPIRED + - CANCELED + - REJECTED + FillBundle: + type: object + description: The selected executable bundle of maker allocations. + properties: + requested_shares_e6: + type: string + description: Requested share size in six-decimal fixed-point units. + requested_notional_e6: + type: string + description: Requested notional in six-decimal fixed-point units (BUY RFQs only). + blended_price_e6: + type: string + description: Blended bundle price in six-decimal fixed-point units. + allocations: + type: array + items: + $ref: '#/components/schemas/FillAllocation' + required: + - requested_shares_e6 + - blended_price_e6 + - allocations + MakerConfirmationSnapshot: + type: object + properties: + quote_id: + type: string + signer_address: + type: string + maker_address: + type: string + decision: + type: string + enum: + - CONFIRM + - DECLINE + - TIMED_OUT + reason: + type: string + responded_at: + type: integer + format: int64 + description: Response time in Unix milliseconds. + required: + - quote_id + - signer_address + - maker_address + ErrorResponse: + type: object + properties: + error: + type: string + description: Human-readable error detail + required: + - error + Direction: + type: string + description: Requester trade direction + enum: + - BUY + - SELL + Side: + type: string + description: Combinatorial position side. Currently only `YES` is supported. + enum: + - 'YES' + - 'NO' + RequestedSize: + type: object + description: Requested RFQ size and unit + properties: + unit: + type: string + description: > + `notional` for requester BUY RFQs and `shares` for requester SELL + RFQs. + enum: + - notional + - shares + value_e6: + type: string + description: Six-decimal fixed-point value encoded as a string. + example: '1000000' + required: + - unit + - value_e6 + FillAllocation: + type: object + properties: + maker_quote_id: + type: string + signer_address: + type: string + maker_address: + type: string + size_e6: + type: string + description: >- + Accepted fill size for this maker quote, in six-decimal fixed-point + units. + price_e6: + type: string + description: Fill price in six-decimal fixed-point units. + received_at: + type: integer + format: int64 + description: Receipt time in Unix milliseconds. + required: + - maker_quote_id + - signer_address + - maker_address + - size_e6 + - price_e6 + responses: + BadRequest: + description: >- + Invalid request (malformed JSON, invalid parameters, or failed + validation) + content: + application/json: + schema: + $ref: '#/components/schemas/ErrorResponse' + example: + error: invalid quote + Unauthorized: + description: Missing or invalid CLOB L2 authentication + content: + application/json: + schema: + $ref: '#/components/schemas/ErrorResponse' + example: + error: unauthenticated + Forbidden: + description: >- + Authenticated identity does not match the request, or role is not + allowed + content: + application/json: + schema: + $ref: '#/components/schemas/ErrorResponse' + example: + error: auth address mismatch + NotFound: + description: The referenced RFQ is not active or no longer exists + content: + application/json: + schema: + $ref: '#/components/schemas/ErrorResponse' + example: + error: unknown rfq + Conflict: + description: The RFQ is not in a state that accepts this command + content: + application/json: + schema: + $ref: '#/components/schemas/ErrorResponse' + example: + error: competition window closed + TooManyRequests: + description: Rate limited + content: + application/json: + schema: + $ref: '#/components/schemas/ErrorResponse' + example: + error: rate limited + ServiceUnavailable: + description: An RFQ service dependency is temporarily unavailable + content: + application/json: + schema: + $ref: '#/components/schemas/ErrorResponse' + example: + error: service unavailable + securitySchemes: + polyApiKey: + type: apiKey + in: header + name: POLY_API_KEY + description: CLOB API key + polyAddress: + type: apiKey + in: header + name: POLY_ADDRESS + description: Wallet address associated with the API key + polySignature: + type: apiKey + in: header + name: POLY_SIGNATURE + description: HMAC-SHA256 signature of the request + polyPassphrase: + type: apiKey + in: header + name: POLY_PASSPHRASE + description: CLOB API key passphrase + polyTimestamp: + type: apiKey + in: header + name: POLY_TIMESTAMP + description: Unix timestamp of the request + +```` \ No newline at end of file diff --git a/PolymarketDocumentation-main/docs/api-reference/maker/confirm-or-decline-last-look.md b/PolymarketDocumentation-main/docs/api-reference/maker/confirm-or-decline-last-look.md new file mode 100644 index 00000000..613467c0 --- /dev/null +++ b/PolymarketDocumentation-main/docs/api-reference/maker/confirm-or-decline-last-look.md @@ -0,0 +1,669 @@ +> ## Documentation Index +> Fetch the complete documentation index at: https://docs.polymarket.com/llms.txt +> Use this file to discover all available pages before exploring further. + +# Confirm or decline last look + +> Respond to a last-look confirmation request for a selected quote. Requires +CLOB L2 authentication for the maker role. `decision` must be `CONFIRM` or +`DECLINE`. + + + + +## OpenAPI + +````yaml /api-spec/combos-rfq-openapi.yaml post /v1/maker/confirmations +openapi: 3.1.0 +info: + title: Polymarket Combinatorial RFQ API + description: > + REST API for the combinatorial RFQ (Request for Quote) system. + + + This spec covers the publicly documented endpoints used by quoters (market + + makers): the combo-market catalog and the authenticated maker commands for + + submitting, cancelling, and confirming quotes. + + + Conventions: + + - All `*_e6` fields are six-decimal fixed-point values encoded as + **strings** + to avoid number precision issues. + - All timestamps are **Unix milliseconds** (integer); zero/omitted means + unset. + + - Errors return an HTTP status code with a body of the form `{ "error": + "..." }`. + license: + name: MIT + identifier: MIT + version: 1.0.0 +servers: + - url: https://combos-rfq-api.polymarket.com + description: Production combinatorial RFQ API +security: [] +tags: + - name: Combo Markets + description: Public catalog of markets that can be used as combo legs + - name: Maker + description: Authenticated quoter (maker) commands +paths: + /v1/maker/confirmations: + post: + tags: + - Maker + summary: Confirm or decline last look + description: > + Respond to a last-look confirmation request for a selected quote. + Requires + + CLOB L2 authentication for the maker role. `decision` must be `CONFIRM` + or + + `DECLINE`. + operationId: submitMakerConfirmation + requestBody: + required: true + content: + application/json: + schema: + $ref: '#/components/schemas/MakerConfirmationRequest' + example: + rfq_id: rfq_ + quote_id: quote_ + signer_address: 0xYourSigner + maker_address: 0xYourQuoterWallet + signature_type: 0 + decision: CONFIRM + responses: + '200': + description: Result of the confirmation — a snapshot and/or an execution handoff + content: + application/json: + schema: + $ref: '#/components/schemas/MakerConfirmationResult' + '400': + $ref: '#/components/responses/BadRequest' + '401': + $ref: '#/components/responses/Unauthorized' + '403': + $ref: '#/components/responses/Forbidden' + '404': + $ref: '#/components/responses/NotFound' + '409': + $ref: '#/components/responses/Conflict' + '429': + $ref: '#/components/responses/TooManyRequests' + '503': + $ref: '#/components/responses/ServiceUnavailable' + security: + - polyApiKey: [] + polyAddress: [] + polySignature: [] + polyPassphrase: [] + polyTimestamp: [] +components: + schemas: + MakerConfirmationRequest: + type: object + description: Maker last-look confirmation response. + properties: + rfq_id: + type: string + example: rfq_ + quote_id: + type: string + example: quote_ + signer_address: + type: string + example: 0xYourSigner + maker_address: + type: string + example: 0xYourQuoterWallet + signature_type: + $ref: '#/components/schemas/SignatureType' + decision: + type: string + description: Confirmation decision. + enum: + - CONFIRM + - DECLINE + required: + - rfq_id + - quote_id + - signer_address + - maker_address + - signature_type + - decision + MakerConfirmationResult: + type: object + description: > + Result of a maker confirmation. Includes a snapshot, an execution + handoff, + + or both, depending on whether the confirmation completed the bundle. + properties: + snapshot: + $ref: '#/components/schemas/RFQSnapshot' + execution: + $ref: '#/components/schemas/ExecutionHandoff' + SignatureType: + type: integer + description: | + CLOB signature type: + - `0` EOA + - `1` POLY_PROXY + - `2` GNOSIS_SAFE + - `3` POLY_1271 + enum: + - 0 + - 1 + - 2 + - 3 + example: 0 + RFQSnapshot: + type: object + description: Point-in-time view of an RFQ and its competition/confirmation windows. + properties: + request: + $ref: '#/components/schemas/RFQRequest' + status: + $ref: '#/components/schemas/RFQStatus' + competition_started_at: + type: integer + format: int64 + description: Unix milliseconds. + competition_ends_at: + type: integer + format: int64 + description: Unix milliseconds. + confirmation_started_at: + type: integer + format: int64 + description: Unix milliseconds. + confirmation_ends_at: + type: integer + format: int64 + description: Unix milliseconds. + quote_id: + type: string + bundle: + $ref: '#/components/schemas/FillBundle' + maker_confirmations: + type: array + items: + $ref: '#/components/schemas/MakerConfirmationSnapshot' + required: + - request + - status + ExecutionHandoff: + type: object + description: Handoff produced when a confirmed RFQ is ready for onchain execution. + properties: + execution_id: + type: string + request: + $ref: '#/components/schemas/RFQRequest' + quote_id: + type: string + bundle: + $ref: '#/components/schemas/FillBundle' + requester_acceptance: + $ref: '#/components/schemas/RequesterAcceptance' + maker_quotes: + type: array + items: + $ref: '#/components/schemas/Quote' + reservations: + type: array + items: + $ref: '#/components/schemas/WalletReservation' + ready_at: + type: integer + format: int64 + description: Unix milliseconds. + required: + - execution_id + - request + - quote_id + - bundle + - requester_acceptance + - maker_quotes + ErrorResponse: + type: object + properties: + error: + type: string + description: Human-readable error detail + required: + - error + RFQRequest: + type: object + description: The RFQ request as stored by the engine. + properties: + rfq_id: + type: string + auth_address: + type: string + signer_address: + type: string + maker_address: + type: string + signature_type: + $ref: '#/components/schemas/SignatureType' + requestor_public_id: + type: string + leg_position_ids: + type: array + items: + type: string + condition_id: + type: string + yes_position_id: + type: string + no_position_id: + type: string + direction: + $ref: '#/components/schemas/Direction' + side: + $ref: '#/components/schemas/Side' + requested_size: + $ref: '#/components/schemas/RequestedSize' + created_at: + type: integer + format: int64 + description: Creation time in Unix milliseconds. + required: + - rfq_id + - leg_position_ids + - direction + - side + RFQStatus: + type: string + description: Lifecycle status of the RFQ + enum: + - CREATED + - COLLECTING_QUOTES + - AWAITING_REQUESTER_ACCEPTANCE + - AWAITING_MAKER_CONFIRMATION + - EXECUTING + - FILLED + - FAILED + - EXPIRED + - CANCELED + - REJECTED + FillBundle: + type: object + description: The selected executable bundle of maker allocations. + properties: + requested_shares_e6: + type: string + description: Requested share size in six-decimal fixed-point units. + requested_notional_e6: + type: string + description: Requested notional in six-decimal fixed-point units (BUY RFQs only). + blended_price_e6: + type: string + description: Blended bundle price in six-decimal fixed-point units. + allocations: + type: array + items: + $ref: '#/components/schemas/FillAllocation' + required: + - requested_shares_e6 + - blended_price_e6 + - allocations + MakerConfirmationSnapshot: + type: object + properties: + quote_id: + type: string + signer_address: + type: string + maker_address: + type: string + decision: + type: string + enum: + - CONFIRM + - DECLINE + - TIMED_OUT + reason: + type: string + responded_at: + type: integer + format: int64 + description: Response time in Unix milliseconds. + required: + - quote_id + - signer_address + - maker_address + RequesterAcceptance: + type: object + properties: + rfq_id: + type: string + quote_id: + type: string + auth_address: + type: string + signer_address: + type: string + maker_address: + type: string + signature_type: + $ref: '#/components/schemas/SignatureType' + signed_order: + $ref: '#/components/schemas/ExchangeV3Order' + accepted_at: + type: integer + format: int64 + description: Unix milliseconds. + required: + - rfq_id + - quote_id + - signed_order + Quote: + type: object + description: A signed maker quote. + properties: + quote_id: + type: string + description: Maker-generated quote ID (required for REST submissions). + example: quote_ + rfq_id: + type: string + description: RFQ ID from the `RFQ_REQUEST`. + example: rfq_ + auth_address: + type: string + description: Derived from the authenticated session; ignored if provided. + readOnly: true + signer_address: + type: string + example: 0xYourSigner + maker_address: + type: string + example: 0xYourQuoterWallet + signature_type: + $ref: '#/components/schemas/SignatureType' + price_e6: + type: string + description: Quote price in six-decimal fixed-point units (must be positive). + example: '450000' + size_e6: + type: string + description: > + Fillable share count in six-decimal fixed-point units (must be + positive). + + Note this differs from the request's size field, which may be + notional or shares. + example: '1000000' + valid_until: + type: integer + format: int64 + description: Optional quote expiry in Unix milliseconds. + signed_order: + $ref: '#/components/schemas/ExchangeV3Order' + received_at: + type: integer + format: int64 + description: Server-assigned receipt time in Unix milliseconds. + readOnly: true + required: + - quote_id + - rfq_id + - signer_address + - maker_address + - signature_type + - price_e6 + - size_e6 + - signed_order + WalletReservation: + type: object + properties: + action_id: + type: string + user: + type: string + wallet_nonce: + type: integer + format: int64 + deltas: + type: array + items: + $ref: '#/components/schemas/WalletAssetDelta' + required: + - action_id + - user + - wallet_nonce + - deltas + Direction: + type: string + description: Requester trade direction + enum: + - BUY + - SELL + Side: + type: string + description: Combinatorial position side. Currently only `YES` is supported. + enum: + - 'YES' + - 'NO' + RequestedSize: + type: object + description: Requested RFQ size and unit + properties: + unit: + type: string + description: > + `notional` for requester BUY RFQs and `shares` for requester SELL + RFQs. + enum: + - notional + - shares + value_e6: + type: string + description: Six-decimal fixed-point value encoded as a string. + example: '1000000' + required: + - unit + - value_e6 + FillAllocation: + type: object + properties: + maker_quote_id: + type: string + signer_address: + type: string + maker_address: + type: string + size_e6: + type: string + description: >- + Accepted fill size for this maker quote, in six-decimal fixed-point + units. + price_e6: + type: string + description: Fill price in six-decimal fixed-point units. + received_at: + type: integer + format: int64 + description: Receipt time in Unix milliseconds. + required: + - maker_quote_id + - signer_address + - maker_address + - size_e6 + - price_e6 + ExchangeV3Order: + type: object + description: >- + Signed Exchange v3 order. Combinatorial RFQ trades settle through + Exchange v3. + properties: + salt: + type: string + description: Order salt (uint256 as a decimal string) + maker: + type: string + description: Wallet that funds the order + example: 0xYourQuoterWallet + signer: + type: string + description: Address that signs the order + example: 0xYourSigner + tokenId: + type: string + description: YES or NO combo position ID (uint256 as a decimal string) + makerAmount: + type: string + description: >- + Amount the maker pays, in six-decimal base units (uint256 as a + string) + takerAmount: + type: string + description: >- + Amount the maker receives, in six-decimal base units (uint256 as a + string) + side: + type: integer + description: Order side — `0` BUY, `1` SELL + enum: + - 0 + - 1 + signatureType: + $ref: '#/components/schemas/SignatureType' + timestamp: + type: string + description: Order timestamp in Unix seconds (as a string) + metadata: + type: string + description: 32-byte hex field; defaults to the zero value + example: '0x0000000000000000000000000000000000000000000000000000000000000000' + builder: + type: string + description: 32-byte hex field; defaults to the zero value + example: '0x0000000000000000000000000000000000000000000000000000000000000000' + signature: + type: string + description: EIP-712 signature over the order + example: 0x... + required: + - salt + - maker + - signer + - tokenId + - makerAmount + - takerAmount + - side + - signatureType + - timestamp + - signature + WalletAssetDelta: + type: object + properties: + asset: + type: string + asset_id: + type: string + amount: + type: string + required: + - asset + - asset_id + - amount + responses: + BadRequest: + description: >- + Invalid request (malformed JSON, invalid parameters, or failed + validation) + content: + application/json: + schema: + $ref: '#/components/schemas/ErrorResponse' + example: + error: invalid quote + Unauthorized: + description: Missing or invalid CLOB L2 authentication + content: + application/json: + schema: + $ref: '#/components/schemas/ErrorResponse' + example: + error: unauthenticated + Forbidden: + description: >- + Authenticated identity does not match the request, or role is not + allowed + content: + application/json: + schema: + $ref: '#/components/schemas/ErrorResponse' + example: + error: auth address mismatch + NotFound: + description: The referenced RFQ is not active or no longer exists + content: + application/json: + schema: + $ref: '#/components/schemas/ErrorResponse' + example: + error: unknown rfq + Conflict: + description: The RFQ is not in a state that accepts this command + content: + application/json: + schema: + $ref: '#/components/schemas/ErrorResponse' + example: + error: competition window closed + TooManyRequests: + description: Rate limited + content: + application/json: + schema: + $ref: '#/components/schemas/ErrorResponse' + example: + error: rate limited + ServiceUnavailable: + description: An RFQ service dependency is temporarily unavailable + content: + application/json: + schema: + $ref: '#/components/schemas/ErrorResponse' + example: + error: service unavailable + securitySchemes: + polyApiKey: + type: apiKey + in: header + name: POLY_API_KEY + description: CLOB API key + polyAddress: + type: apiKey + in: header + name: POLY_ADDRESS + description: Wallet address associated with the API key + polySignature: + type: apiKey + in: header + name: POLY_SIGNATURE + description: HMAC-SHA256 signature of the request + polyPassphrase: + type: apiKey + in: header + name: POLY_PASSPHRASE + description: CLOB API key passphrase + polyTimestamp: + type: apiKey + in: header + name: POLY_TIMESTAMP + description: Unix timestamp of the request + +```` \ No newline at end of file diff --git a/PolymarketDocumentation-main/docs/api-reference/maker/submit-a-quote.md b/PolymarketDocumentation-main/docs/api-reference/maker/submit-a-quote.md new file mode 100644 index 00000000..1c54104b --- /dev/null +++ b/PolymarketDocumentation-main/docs/api-reference/maker/submit-a-quote.md @@ -0,0 +1,550 @@ +> ## Documentation Index +> Fetch the complete documentation index at: https://docs.polymarket.com/llms.txt +> Use this file to discover all available pages before exploring further. + +# Submit a quote + +> Submit a signed maker quote for an active RFQ. Requires CLOB L2 +authentication for the maker role. + +REST does not assign a quote ID — generate `quote_id` client-side. + + + + +## OpenAPI + +````yaml /api-spec/combos-rfq-openapi.yaml post /v1/maker/quotes +openapi: 3.1.0 +info: + title: Polymarket Combinatorial RFQ API + description: > + REST API for the combinatorial RFQ (Request for Quote) system. + + + This spec covers the publicly documented endpoints used by quoters (market + + makers): the combo-market catalog and the authenticated maker commands for + + submitting, cancelling, and confirming quotes. + + + Conventions: + + - All `*_e6` fields are six-decimal fixed-point values encoded as + **strings** + to avoid number precision issues. + - All timestamps are **Unix milliseconds** (integer); zero/omitted means + unset. + + - Errors return an HTTP status code with a body of the form `{ "error": + "..." }`. + license: + name: MIT + identifier: MIT + version: 1.0.0 +servers: + - url: https://combos-rfq-api.polymarket.com + description: Production combinatorial RFQ API +security: [] +tags: + - name: Combo Markets + description: Public catalog of markets that can be used as combo legs + - name: Maker + description: Authenticated quoter (maker) commands +paths: + /v1/maker/quotes: + post: + tags: + - Maker + summary: Submit a quote + description: | + Submit a signed maker quote for an active RFQ. Requires CLOB L2 + authentication for the maker role. + + REST does not assign a quote ID — generate `quote_id` client-side. + operationId: submitMakerQuote + requestBody: + required: true + content: + application/json: + schema: + $ref: '#/components/schemas/Quote' + example: + quote_id: quote_ + rfq_id: rfq_ + signer_address: 0xYourSigner + maker_address: 0xYourQuoterWallet + signature_type: 0 + price_e6: '450000' + size_e6: '1000000' + signed_order: + salt: + maker: 0xYourQuoterWallet + signer: 0xYourSigner + tokenId: + makerAmount: + takerAmount: + side: 0 + signatureType: 0 + timestamp: + metadata: >- + 0x0000000000000000000000000000000000000000000000000000000000000000 + builder: >- + 0x0000000000000000000000000000000000000000000000000000000000000000 + signature: 0x... + responses: + '200': + description: Current RFQ snapshot after the quote was accepted + content: + application/json: + schema: + $ref: '#/components/schemas/RFQSnapshot' + '400': + $ref: '#/components/responses/BadRequest' + '401': + $ref: '#/components/responses/Unauthorized' + '403': + $ref: '#/components/responses/Forbidden' + '404': + $ref: '#/components/responses/NotFound' + '409': + $ref: '#/components/responses/Conflict' + '429': + $ref: '#/components/responses/TooManyRequests' + '503': + $ref: '#/components/responses/ServiceUnavailable' + security: + - polyApiKey: [] + polyAddress: [] + polySignature: [] + polyPassphrase: [] + polyTimestamp: [] +components: + schemas: + Quote: + type: object + description: A signed maker quote. + properties: + quote_id: + type: string + description: Maker-generated quote ID (required for REST submissions). + example: quote_ + rfq_id: + type: string + description: RFQ ID from the `RFQ_REQUEST`. + example: rfq_ + auth_address: + type: string + description: Derived from the authenticated session; ignored if provided. + readOnly: true + signer_address: + type: string + example: 0xYourSigner + maker_address: + type: string + example: 0xYourQuoterWallet + signature_type: + $ref: '#/components/schemas/SignatureType' + price_e6: + type: string + description: Quote price in six-decimal fixed-point units (must be positive). + example: '450000' + size_e6: + type: string + description: > + Fillable share count in six-decimal fixed-point units (must be + positive). + + Note this differs from the request's size field, which may be + notional or shares. + example: '1000000' + valid_until: + type: integer + format: int64 + description: Optional quote expiry in Unix milliseconds. + signed_order: + $ref: '#/components/schemas/ExchangeV3Order' + received_at: + type: integer + format: int64 + description: Server-assigned receipt time in Unix milliseconds. + readOnly: true + required: + - quote_id + - rfq_id + - signer_address + - maker_address + - signature_type + - price_e6 + - size_e6 + - signed_order + RFQSnapshot: + type: object + description: Point-in-time view of an RFQ and its competition/confirmation windows. + properties: + request: + $ref: '#/components/schemas/RFQRequest' + status: + $ref: '#/components/schemas/RFQStatus' + competition_started_at: + type: integer + format: int64 + description: Unix milliseconds. + competition_ends_at: + type: integer + format: int64 + description: Unix milliseconds. + confirmation_started_at: + type: integer + format: int64 + description: Unix milliseconds. + confirmation_ends_at: + type: integer + format: int64 + description: Unix milliseconds. + quote_id: + type: string + bundle: + $ref: '#/components/schemas/FillBundle' + maker_confirmations: + type: array + items: + $ref: '#/components/schemas/MakerConfirmationSnapshot' + required: + - request + - status + SignatureType: + type: integer + description: | + CLOB signature type: + - `0` EOA + - `1` POLY_PROXY + - `2` GNOSIS_SAFE + - `3` POLY_1271 + enum: + - 0 + - 1 + - 2 + - 3 + example: 0 + ExchangeV3Order: + type: object + description: >- + Signed Exchange v3 order. Combinatorial RFQ trades settle through + Exchange v3. + properties: + salt: + type: string + description: Order salt (uint256 as a decimal string) + maker: + type: string + description: Wallet that funds the order + example: 0xYourQuoterWallet + signer: + type: string + description: Address that signs the order + example: 0xYourSigner + tokenId: + type: string + description: YES or NO combo position ID (uint256 as a decimal string) + makerAmount: + type: string + description: >- + Amount the maker pays, in six-decimal base units (uint256 as a + string) + takerAmount: + type: string + description: >- + Amount the maker receives, in six-decimal base units (uint256 as a + string) + side: + type: integer + description: Order side — `0` BUY, `1` SELL + enum: + - 0 + - 1 + signatureType: + $ref: '#/components/schemas/SignatureType' + timestamp: + type: string + description: Order timestamp in Unix seconds (as a string) + metadata: + type: string + description: 32-byte hex field; defaults to the zero value + example: '0x0000000000000000000000000000000000000000000000000000000000000000' + builder: + type: string + description: 32-byte hex field; defaults to the zero value + example: '0x0000000000000000000000000000000000000000000000000000000000000000' + signature: + type: string + description: EIP-712 signature over the order + example: 0x... + required: + - salt + - maker + - signer + - tokenId + - makerAmount + - takerAmount + - side + - signatureType + - timestamp + - signature + RFQRequest: + type: object + description: The RFQ request as stored by the engine. + properties: + rfq_id: + type: string + auth_address: + type: string + signer_address: + type: string + maker_address: + type: string + signature_type: + $ref: '#/components/schemas/SignatureType' + requestor_public_id: + type: string + leg_position_ids: + type: array + items: + type: string + condition_id: + type: string + yes_position_id: + type: string + no_position_id: + type: string + direction: + $ref: '#/components/schemas/Direction' + side: + $ref: '#/components/schemas/Side' + requested_size: + $ref: '#/components/schemas/RequestedSize' + created_at: + type: integer + format: int64 + description: Creation time in Unix milliseconds. + required: + - rfq_id + - leg_position_ids + - direction + - side + RFQStatus: + type: string + description: Lifecycle status of the RFQ + enum: + - CREATED + - COLLECTING_QUOTES + - AWAITING_REQUESTER_ACCEPTANCE + - AWAITING_MAKER_CONFIRMATION + - EXECUTING + - FILLED + - FAILED + - EXPIRED + - CANCELED + - REJECTED + FillBundle: + type: object + description: The selected executable bundle of maker allocations. + properties: + requested_shares_e6: + type: string + description: Requested share size in six-decimal fixed-point units. + requested_notional_e6: + type: string + description: Requested notional in six-decimal fixed-point units (BUY RFQs only). + blended_price_e6: + type: string + description: Blended bundle price in six-decimal fixed-point units. + allocations: + type: array + items: + $ref: '#/components/schemas/FillAllocation' + required: + - requested_shares_e6 + - blended_price_e6 + - allocations + MakerConfirmationSnapshot: + type: object + properties: + quote_id: + type: string + signer_address: + type: string + maker_address: + type: string + decision: + type: string + enum: + - CONFIRM + - DECLINE + - TIMED_OUT + reason: + type: string + responded_at: + type: integer + format: int64 + description: Response time in Unix milliseconds. + required: + - quote_id + - signer_address + - maker_address + ErrorResponse: + type: object + properties: + error: + type: string + description: Human-readable error detail + required: + - error + Direction: + type: string + description: Requester trade direction + enum: + - BUY + - SELL + Side: + type: string + description: Combinatorial position side. Currently only `YES` is supported. + enum: + - 'YES' + - 'NO' + RequestedSize: + type: object + description: Requested RFQ size and unit + properties: + unit: + type: string + description: > + `notional` for requester BUY RFQs and `shares` for requester SELL + RFQs. + enum: + - notional + - shares + value_e6: + type: string + description: Six-decimal fixed-point value encoded as a string. + example: '1000000' + required: + - unit + - value_e6 + FillAllocation: + type: object + properties: + maker_quote_id: + type: string + signer_address: + type: string + maker_address: + type: string + size_e6: + type: string + description: >- + Accepted fill size for this maker quote, in six-decimal fixed-point + units. + price_e6: + type: string + description: Fill price in six-decimal fixed-point units. + received_at: + type: integer + format: int64 + description: Receipt time in Unix milliseconds. + required: + - maker_quote_id + - signer_address + - maker_address + - size_e6 + - price_e6 + responses: + BadRequest: + description: >- + Invalid request (malformed JSON, invalid parameters, or failed + validation) + content: + application/json: + schema: + $ref: '#/components/schemas/ErrorResponse' + example: + error: invalid quote + Unauthorized: + description: Missing or invalid CLOB L2 authentication + content: + application/json: + schema: + $ref: '#/components/schemas/ErrorResponse' + example: + error: unauthenticated + Forbidden: + description: >- + Authenticated identity does not match the request, or role is not + allowed + content: + application/json: + schema: + $ref: '#/components/schemas/ErrorResponse' + example: + error: auth address mismatch + NotFound: + description: The referenced RFQ is not active or no longer exists + content: + application/json: + schema: + $ref: '#/components/schemas/ErrorResponse' + example: + error: unknown rfq + Conflict: + description: The RFQ is not in a state that accepts this command + content: + application/json: + schema: + $ref: '#/components/schemas/ErrorResponse' + example: + error: competition window closed + TooManyRequests: + description: Rate limited + content: + application/json: + schema: + $ref: '#/components/schemas/ErrorResponse' + example: + error: rate limited + ServiceUnavailable: + description: An RFQ service dependency is temporarily unavailable + content: + application/json: + schema: + $ref: '#/components/schemas/ErrorResponse' + example: + error: service unavailable + securitySchemes: + polyApiKey: + type: apiKey + in: header + name: POLY_API_KEY + description: CLOB API key + polyAddress: + type: apiKey + in: header + name: POLY_ADDRESS + description: Wallet address associated with the API key + polySignature: + type: apiKey + in: header + name: POLY_SIGNATURE + description: HMAC-SHA256 signature of the request + polyPassphrase: + type: apiKey + in: header + name: POLY_PASSPHRASE + description: CLOB API key passphrase + polyTimestamp: + type: apiKey + in: header + name: POLY_TIMESTAMP + description: Unix timestamp of the request + +```` \ No newline at end of file diff --git a/PolymarketDocumentation-main/docs/api-reference/market-data/get-fee-rate-by-path-parameter.md b/PolymarketDocumentation-main/docs/api-reference/market-data/get-fee-rate-by-path-parameter.md new file mode 100644 index 00000000..637cf6db --- /dev/null +++ b/PolymarketDocumentation-main/docs/api-reference/market-data/get-fee-rate-by-path-parameter.md @@ -0,0 +1,121 @@ +> ## Documentation Index +> Fetch the complete documentation index at: https://docs.polymarket.com/llms.txt +> Use this file to discover all available pages before exploring further. + +# Get fee rate by path parameter + +> Retrieves the base fee rate for a specific token ID using the token ID as a path parameter. + + + + +## OpenAPI + +````yaml /api-spec/clob-openapi.yaml get /fee-rate/{token_id} +openapi: 3.1.0 +info: + title: Polymarket CLOB API + description: Polymarket CLOB API Reference + license: + name: MIT + identifier: MIT + version: 1.0.0 +servers: + - url: https://clob.polymarket.com + description: Production CLOB API + - url: https://clob-staging.polymarket.com + description: Staging CLOB API +security: [] +tags: + - name: Trade + description: Trade endpoints + - name: Markets + description: Market data endpoints + - name: Account + description: Account and authentication endpoints + - name: Notifications + description: User notification endpoints + - name: Rewards + description: Rewards and earnings endpoints + - name: Rebates + description: Maker rebate endpoints +paths: + /fee-rate/{token_id}: + get: + tags: + - Market Data + summary: Get fee rate by path parameter + description: > + Retrieves the base fee rate for a specific token ID using the token ID + as a path parameter. + operationId: getFeeRateByPath + parameters: + - name: token_id + in: path + description: Token ID (asset ID) + required: true + schema: + type: string + example: 0xabc123def456... + responses: + '200': + description: Successfully retrieved fee rate + content: + application/json: + schema: + $ref: '#/components/schemas/FeeRate' + example: + base_fee: 30 + '400': + description: Bad request - Invalid token id + content: + application/json: + schema: + $ref: '#/components/schemas/ErrorResponse' + example: + error: Invalid token id + '404': + description: Not found - Fee rate not found for market + content: + application/json: + schema: + $ref: '#/components/schemas/ErrorResponse' + example: + error: fee rate not found for market + '500': + description: Internal server error + content: + application/json: + schema: + $ref: '#/components/schemas/ErrorResponse' + example: + error: Internal server error + security: [] +components: + schemas: + FeeRate: + type: object + required: + - base_fee + properties: + base_fee: + type: integer + format: int64 + description: Base fee in basis points + example: 30 + ErrorResponse: + type: object + required: + - error + properties: + error: + type: string + description: Error message + code: + type: string + description: Machine-readable error code, when provided + retry_after_seconds: + type: integer + description: Number of seconds to wait before retrying, when provided + +```` \ No newline at end of file diff --git a/PolymarketDocumentation-main/docs/api-reference/market-data/get-fee-rate.md b/PolymarketDocumentation-main/docs/api-reference/market-data/get-fee-rate.md new file mode 100644 index 00000000..cdb25d5c --- /dev/null +++ b/PolymarketDocumentation-main/docs/api-reference/market-data/get-fee-rate.md @@ -0,0 +1,124 @@ +> ## Documentation Index +> Fetch the complete documentation index at: https://docs.polymarket.com/llms.txt +> Use this file to discover all available pages before exploring further. + +# Get fee rate + +> Retrieves the base fee rate for a specific token ID. +The fee rate can be provided either as a query parameter or as a path parameter. + + + + +## OpenAPI + +````yaml /api-spec/clob-openapi.yaml get /fee-rate +openapi: 3.1.0 +info: + title: Polymarket CLOB API + description: Polymarket CLOB API Reference + license: + name: MIT + identifier: MIT + version: 1.0.0 +servers: + - url: https://clob.polymarket.com + description: Production CLOB API + - url: https://clob-staging.polymarket.com + description: Staging CLOB API +security: [] +tags: + - name: Trade + description: Trade endpoints + - name: Markets + description: Market data endpoints + - name: Account + description: Account and authentication endpoints + - name: Notifications + description: User notification endpoints + - name: Rewards + description: Rewards and earnings endpoints + - name: Rebates + description: Maker rebate endpoints +paths: + /fee-rate: + get: + tags: + - Market Data + summary: Get fee rate + description: > + Retrieves the base fee rate for a specific token ID. + + The fee rate can be provided either as a query parameter or as a path + parameter. + operationId: getFeeRate + parameters: + - name: token_id + in: query + description: Token ID (asset ID) + required: false + schema: + type: string + example: 0xabc123def456... + responses: + '200': + description: Successfully retrieved fee rate + content: + application/json: + schema: + $ref: '#/components/schemas/FeeRate' + example: + base_fee: 30 + '400': + description: Bad request - Invalid token id + content: + application/json: + schema: + $ref: '#/components/schemas/ErrorResponse' + example: + error: Invalid token id + '404': + description: Not found - Fee rate not found for market + content: + application/json: + schema: + $ref: '#/components/schemas/ErrorResponse' + example: + error: fee rate not found for market + '500': + description: Internal server error + content: + application/json: + schema: + $ref: '#/components/schemas/ErrorResponse' + example: + error: Internal server error + security: [] +components: + schemas: + FeeRate: + type: object + required: + - base_fee + properties: + base_fee: + type: integer + format: int64 + description: Base fee in basis points + example: 30 + ErrorResponse: + type: object + required: + - error + properties: + error: + type: string + description: Error message + code: + type: string + description: Machine-readable error code, when provided + retry_after_seconds: + type: integer + description: Number of seconds to wait before retrying, when provided + +```` \ No newline at end of file diff --git a/PolymarketDocumentation-main/docs/api-reference/market-data/get-last-trade-price.md b/PolymarketDocumentation-main/docs/api-reference/market-data/get-last-trade-price.md new file mode 100644 index 00000000..6800eb41 --- /dev/null +++ b/PolymarketDocumentation-main/docs/api-reference/market-data/get-last-trade-price.md @@ -0,0 +1,120 @@ +> ## Documentation Index +> Fetch the complete documentation index at: https://docs.polymarket.com/llms.txt +> Use this file to discover all available pages before exploring further. + +# Get last trade price + +> Retrieves the last trade price and side for a specific token ID. +Returns default values of "0.5" for price and empty string for side if no trades found. + + + + +## OpenAPI + +````yaml /api-spec/clob-openapi.yaml get /last-trade-price +openapi: 3.1.0 +info: + title: Polymarket CLOB API + description: Polymarket CLOB API Reference + license: + name: MIT + identifier: MIT + version: 1.0.0 +servers: + - url: https://clob.polymarket.com + description: Production CLOB API + - url: https://clob-staging.polymarket.com + description: Staging CLOB API +security: [] +tags: + - name: Trade + description: Trade endpoints + - name: Markets + description: Market data endpoints + - name: Account + description: Account and authentication endpoints + - name: Notifications + description: User notification endpoints + - name: Rewards + description: Rewards and earnings endpoints + - name: Rebates + description: Maker rebate endpoints +paths: + /last-trade-price: + get: + tags: + - Market Data + summary: Get last trade price + description: > + Retrieves the last trade price and side for a specific token ID. + + Returns default values of "0.5" for price and empty string for side if + no trades found. + operationId: getLastTradePrice + parameters: + - name: token_id + in: query + description: Token ID (asset ID) + required: true + schema: + type: string + example: 0xabc123def456... + responses: + '200': + description: Successfully retrieved last trade price + content: + application/json: + schema: + type: object + required: + - price + - side + properties: + price: + type: string + description: Last trade price + example: '0.45' + side: + type: string + description: Last trade side (BUY or SELL) + enum: + - BUY + - SELL + - '' + example: BUY + '400': + description: Bad request - Invalid token id + content: + application/json: + schema: + $ref: '#/components/schemas/ErrorResponse' + example: + error: Invalid token id + '500': + description: Internal server error + content: + application/json: + schema: + $ref: '#/components/schemas/ErrorResponse' + example: + error: Internal server error + security: [] +components: + schemas: + ErrorResponse: + type: object + required: + - error + properties: + error: + type: string + description: Error message + code: + type: string + description: Machine-readable error code, when provided + retry_after_seconds: + type: integer + description: Number of seconds to wait before retrying, when provided + +```` \ No newline at end of file diff --git a/PolymarketDocumentation-main/docs/api-reference/market-data/get-last-trade-prices-query-parameters.md b/PolymarketDocumentation-main/docs/api-reference/market-data/get-last-trade-prices-query-parameters.md new file mode 100644 index 00000000..b61cf09e --- /dev/null +++ b/PolymarketDocumentation-main/docs/api-reference/market-data/get-last-trade-prices-query-parameters.md @@ -0,0 +1,140 @@ +> ## Documentation Index +> Fetch the complete documentation index at: https://docs.polymarket.com/llms.txt +> Use this file to discover all available pages before exploring further. + +# Get last trade prices (query parameters) + +> Retrieves last trade prices for multiple token IDs using query parameters. +Maximum 500 token IDs can be requested per call. + + + + +## OpenAPI + +````yaml /api-spec/clob-openapi.yaml get /last-trades-prices +openapi: 3.1.0 +info: + title: Polymarket CLOB API + description: Polymarket CLOB API Reference + license: + name: MIT + identifier: MIT + version: 1.0.0 +servers: + - url: https://clob.polymarket.com + description: Production CLOB API + - url: https://clob-staging.polymarket.com + description: Staging CLOB API +security: [] +tags: + - name: Trade + description: Trade endpoints + - name: Markets + description: Market data endpoints + - name: Account + description: Account and authentication endpoints + - name: Notifications + description: User notification endpoints + - name: Rewards + description: Rewards and earnings endpoints + - name: Rebates + description: Maker rebate endpoints +paths: + /last-trades-prices: + get: + tags: + - Market Data + summary: Get last trade prices (query parameters) + description: > + Retrieves last trade prices for multiple token IDs using query + parameters. + + Maximum 500 token IDs can be requested per call. + operationId: getLastTradesPricesGet + parameters: + - name: token_ids + in: query + description: Comma-separated list of token IDs (max 500) + required: true + schema: + type: string + example: 0xabc123...,0xdef456... + responses: + '200': + description: Successfully retrieved last trade prices + content: + application/json: + schema: + type: array + items: + type: object + required: + - token_id + - price + - side + properties: + token_id: + type: string + description: Token ID (asset ID) + example: 0xabc123def456... + price: + type: string + description: Last trade price + example: '0.45' + side: + type: string + description: Last trade side (BUY or SELL) + enum: + - BUY + - SELL + example: BUY + example: + - token_id: 0xabc123def456... + price: '0.45' + side: BUY + - token_id: 0xdef456abc123... + price: '0.52' + side: SELL + '400': + description: Bad request - Invalid payload or exceeds limit + content: + application/json: + schema: + $ref: '#/components/schemas/ErrorResponse' + examples: + invalid_payload: + summary: Invalid payload + value: + error: Invalid payload + exceeds_limit: + summary: Payload exceeds limit + value: + error: Payload exceeds the limit + '500': + description: Internal server error + content: + application/json: + schema: + $ref: '#/components/schemas/ErrorResponse' + example: + error: Internal server error + security: [] +components: + schemas: + ErrorResponse: + type: object + required: + - error + properties: + error: + type: string + description: Error message + code: + type: string + description: Machine-readable error code, when provided + retry_after_seconds: + type: integer + description: Number of seconds to wait before retrying, when provided + +```` \ No newline at end of file diff --git a/PolymarketDocumentation-main/docs/api-reference/market-data/get-last-trade-prices-request-body.md b/PolymarketDocumentation-main/docs/api-reference/market-data/get-last-trade-prices-request-body.md new file mode 100644 index 00000000..98b3ad9f --- /dev/null +++ b/PolymarketDocumentation-main/docs/api-reference/market-data/get-last-trade-prices-request-body.md @@ -0,0 +1,157 @@ +> ## Documentation Index +> Fetch the complete documentation index at: https://docs.polymarket.com/llms.txt +> Use this file to discover all available pages before exploring further. + +# Get last trade prices (request body) + +> Retrieves last trade prices for multiple token IDs using a request body. +Maximum 500 token IDs can be requested per call. + + + + +## OpenAPI + +````yaml /api-spec/clob-openapi.yaml post /last-trades-prices +openapi: 3.1.0 +info: + title: Polymarket CLOB API + description: Polymarket CLOB API Reference + license: + name: MIT + identifier: MIT + version: 1.0.0 +servers: + - url: https://clob.polymarket.com + description: Production CLOB API + - url: https://clob-staging.polymarket.com + description: Staging CLOB API +security: [] +tags: + - name: Trade + description: Trade endpoints + - name: Markets + description: Market data endpoints + - name: Account + description: Account and authentication endpoints + - name: Notifications + description: User notification endpoints + - name: Rewards + description: Rewards and earnings endpoints + - name: Rebates + description: Maker rebate endpoints +paths: + /last-trades-prices: + post: + tags: + - Market Data + summary: Get last trade prices (request body) + description: | + Retrieves last trade prices for multiple token IDs using a request body. + Maximum 500 token IDs can be requested per call. + operationId: getLastTradesPricesPost + requestBody: + required: true + content: + application/json: + schema: + type: array + items: + $ref: '#/components/schemas/BookRequest' + example: + - token_id: 0xabc123def456... + - token_id: 0xdef456abc123... + responses: + '200': + description: Successfully retrieved last trade prices + content: + application/json: + schema: + type: array + items: + type: object + required: + - token_id + - price + - side + properties: + token_id: + type: string + description: Token ID (asset ID) + example: 0xabc123def456... + price: + type: string + description: Last trade price + example: '0.45' + side: + type: string + description: Last trade side (BUY or SELL) + enum: + - BUY + - SELL + example: BUY + example: + - token_id: 0xabc123def456... + price: '0.45' + side: BUY + - token_id: 0xdef456abc123... + price: '0.52' + side: SELL + '400': + description: Bad request - Invalid payload or exceeds limit + content: + application/json: + schema: + $ref: '#/components/schemas/ErrorResponse' + examples: + invalid_payload: + summary: Invalid payload + value: + error: Invalid payload + exceeds_limit: + summary: Payload exceeds limit + value: + error: Payload exceeds the limit + '500': + description: Internal server error + content: + application/json: + schema: + $ref: '#/components/schemas/ErrorResponse' + example: + error: Internal server error + security: [] +components: + schemas: + BookRequest: + type: object + required: + - token_id + properties: + token_id: + type: string + description: Token ID (asset ID) + example: 0xabc123def456... + side: + type: string + description: Order side (optional, not used for midpoint calculation) + enum: + - BUY + - SELL + example: BUY + ErrorResponse: + type: object + required: + - error + properties: + error: + type: string + description: Error message + code: + type: string + description: Machine-readable error code, when provided + retry_after_seconds: + type: integer + description: Number of seconds to wait before retrying, when provided + +```` \ No newline at end of file diff --git a/PolymarketDocumentation-main/docs/api-reference/market-data/get-market-price.md b/PolymarketDocumentation-main/docs/api-reference/market-data/get-market-price.md new file mode 100644 index 00000000..41b89a68 --- /dev/null +++ b/PolymarketDocumentation-main/docs/api-reference/market-data/get-market-price.md @@ -0,0 +1,139 @@ +> ## Documentation Index +> Fetch the complete documentation index at: https://docs.polymarket.com/llms.txt +> Use this file to discover all available pages before exploring further. + +# Get market price + +> Retrieves the best market price for a specific token ID and side (bid or ask). +Returns the best bid price for BUY side or best ask price for SELL side. + + + + +## OpenAPI + +````yaml /api-spec/clob-openapi.yaml get /price +openapi: 3.1.0 +info: + title: Polymarket CLOB API + description: Polymarket CLOB API Reference + license: + name: MIT + identifier: MIT + version: 1.0.0 +servers: + - url: https://clob.polymarket.com + description: Production CLOB API + - url: https://clob-staging.polymarket.com + description: Staging CLOB API +security: [] +tags: + - name: Trade + description: Trade endpoints + - name: Markets + description: Market data endpoints + - name: Account + description: Account and authentication endpoints + - name: Notifications + description: User notification endpoints + - name: Rewards + description: Rewards and earnings endpoints + - name: Rebates + description: Maker rebate endpoints +paths: + /price: + get: + tags: + - Market Data + summary: Get market price + description: > + Retrieves the best market price for a specific token ID and side (bid or + ask). + + Returns the best bid price for BUY side or best ask price for SELL side. + operationId: getPrice + parameters: + - name: token_id + in: query + description: Token ID (asset ID) + required: true + schema: + type: string + example: 0xabc123def456... + - name: side + in: query + description: Order side + required: true + schema: + type: string + enum: + - BUY + - SELL + example: BUY + responses: + '200': + description: Successfully retrieved market price + content: + application/json: + schema: + type: object + required: + - price + properties: + price: + type: number + format: double + description: Market price as a decimal number + example: 0.45 + example: + price: 0.45 + '400': + description: Bad request - Invalid token id or side + content: + application/json: + schema: + $ref: '#/components/schemas/ErrorResponse' + examples: + invalid_token_id: + summary: Invalid token id + value: + error: Invalid token id + invalid_side: + summary: Invalid side + value: + error: Invalid side + '404': + description: Not found - No orderbook exists for the requested token id + content: + application/json: + schema: + $ref: '#/components/schemas/ErrorResponse' + example: + error: No orderbook exists for the requested token id + '500': + description: Internal server error + content: + application/json: + schema: + $ref: '#/components/schemas/ErrorResponse' + example: + error: Internal server error + security: [] +components: + schemas: + ErrorResponse: + type: object + required: + - error + properties: + error: + type: string + description: Error message + code: + type: string + description: Machine-readable error code, when provided + retry_after_seconds: + type: integer + description: Number of seconds to wait before retrying, when provided + +```` \ No newline at end of file diff --git a/PolymarketDocumentation-main/docs/api-reference/market-data/get-market-prices-query-parameters.md b/PolymarketDocumentation-main/docs/api-reference/market-data/get-market-prices-query-parameters.md new file mode 100644 index 00000000..cb0f9a35 --- /dev/null +++ b/PolymarketDocumentation-main/docs/api-reference/market-data/get-market-prices-query-parameters.md @@ -0,0 +1,136 @@ +> ## Documentation Index +> Fetch the complete documentation index at: https://docs.polymarket.com/llms.txt +> Use this file to discover all available pages before exploring further. + +# Get market prices (query parameters) + +> Retrieves market prices for multiple token IDs and sides using query parameters. + + + + +## OpenAPI + +````yaml /api-spec/clob-openapi.yaml get /prices +openapi: 3.1.0 +info: + title: Polymarket CLOB API + description: Polymarket CLOB API Reference + license: + name: MIT + identifier: MIT + version: 1.0.0 +servers: + - url: https://clob.polymarket.com + description: Production CLOB API + - url: https://clob-staging.polymarket.com + description: Staging CLOB API +security: [] +tags: + - name: Trade + description: Trade endpoints + - name: Markets + description: Market data endpoints + - name: Account + description: Account and authentication endpoints + - name: Notifications + description: User notification endpoints + - name: Rewards + description: Rewards and earnings endpoints + - name: Rebates + description: Maker rebate endpoints +paths: + /prices: + get: + tags: + - Market Data + summary: Get market prices (query parameters) + description: > + Retrieves market prices for multiple token IDs and sides using query + parameters. + operationId: getPricesGet + parameters: + - name: token_ids + in: query + description: Comma-separated list of token IDs + required: true + schema: + type: string + example: 0xabc123...,0xdef456... + - name: sides + in: query + description: >- + Comma-separated list of sides (BUY or SELL) corresponding to token + IDs + required: true + schema: + type: string + example: BUY,SELL + responses: + '200': + description: Successfully retrieved market prices + content: + application/json: + schema: + type: object + additionalProperties: + type: object + additionalProperties: + type: number + format: double + description: Map of token ID to map of side to price + example: + 0xabc123def456...: + BUY: 0.45 + 0xdef456abc123...: + SELL: 0.52 + '400': + description: Bad request - Invalid payload or side + content: + application/json: + schema: + $ref: '#/components/schemas/ErrorResponse' + examples: + invalid_payload: + summary: Invalid payload + value: + error: Invalid payload + invalid_side: + summary: Invalid side + value: + error: Invalid side + '404': + description: Not found - No orderbook exists for the requested token id + content: + application/json: + schema: + $ref: '#/components/schemas/ErrorResponse' + example: + error: No orderbook exists for the requested token id + '500': + description: Internal server error + content: + application/json: + schema: + $ref: '#/components/schemas/ErrorResponse' + example: + error: Internal server error + security: [] +components: + schemas: + ErrorResponse: + type: object + required: + - error + properties: + error: + type: string + description: Error message + code: + type: string + description: Machine-readable error code, when provided + retry_after_seconds: + type: integer + description: Number of seconds to wait before retrying, when provided + +```` \ No newline at end of file diff --git a/PolymarketDocumentation-main/docs/api-reference/market-data/get-market-prices-request-body.md b/PolymarketDocumentation-main/docs/api-reference/market-data/get-market-prices-request-body.md new file mode 100644 index 00000000..32c95597 --- /dev/null +++ b/PolymarketDocumentation-main/docs/api-reference/market-data/get-market-prices-request-body.md @@ -0,0 +1,151 @@ +> ## Documentation Index +> Fetch the complete documentation index at: https://docs.polymarket.com/llms.txt +> Use this file to discover all available pages before exploring further. + +# Get market prices (request body) + +> Retrieves market prices for multiple token IDs and sides using a request body. +Each request must include both token_id and side. + + + + +## OpenAPI + +````yaml /api-spec/clob-openapi.yaml post /prices +openapi: 3.1.0 +info: + title: Polymarket CLOB API + description: Polymarket CLOB API Reference + license: + name: MIT + identifier: MIT + version: 1.0.0 +servers: + - url: https://clob.polymarket.com + description: Production CLOB API + - url: https://clob-staging.polymarket.com + description: Staging CLOB API +security: [] +tags: + - name: Trade + description: Trade endpoints + - name: Markets + description: Market data endpoints + - name: Account + description: Account and authentication endpoints + - name: Notifications + description: User notification endpoints + - name: Rewards + description: Rewards and earnings endpoints + - name: Rebates + description: Maker rebate endpoints +paths: + /prices: + post: + tags: + - Market Data + summary: Get market prices (request body) + description: > + Retrieves market prices for multiple token IDs and sides using a request + body. + + Each request must include both token_id and side. + operationId: getPricesPost + requestBody: + required: true + content: + application/json: + schema: + type: array + items: + $ref: '#/components/schemas/BookRequest' + example: + - token_id: 0xabc123def456... + side: BUY + - token_id: 0xdef456abc123... + side: SELL + responses: + '200': + description: Successfully retrieved market prices + content: + application/json: + schema: + type: object + additionalProperties: + type: object + additionalProperties: + type: number + format: double + description: Map of token ID to map of side to price + example: + 0xabc123def456...: + BUY: 0.45 + 0xdef456abc123...: + SELL: 0.52 + '400': + description: Bad request - Invalid payload or side + content: + application/json: + schema: + $ref: '#/components/schemas/ErrorResponse' + examples: + invalid_payload: + summary: Invalid payload + value: + error: Invalid payload + invalid_side: + summary: Invalid side + value: + error: Invalid side + '404': + description: Not found - No orderbook exists for the requested token id + content: + application/json: + schema: + $ref: '#/components/schemas/ErrorResponse' + example: + error: No orderbook exists for the requested token id + '500': + description: Internal server error + content: + application/json: + schema: + $ref: '#/components/schemas/ErrorResponse' + example: + error: Internal server error + security: [] +components: + schemas: + BookRequest: + type: object + required: + - token_id + properties: + token_id: + type: string + description: Token ID (asset ID) + example: 0xabc123def456... + side: + type: string + description: Order side (optional, not used for midpoint calculation) + enum: + - BUY + - SELL + example: BUY + ErrorResponse: + type: object + required: + - error + properties: + error: + type: string + description: Error message + code: + type: string + description: Machine-readable error code, when provided + retry_after_seconds: + type: integer + description: Number of seconds to wait before retrying, when provided + +```` \ No newline at end of file diff --git a/PolymarketDocumentation-main/docs/api-reference/market-data/get-midpoint-prices-query-parameters.md b/PolymarketDocumentation-main/docs/api-reference/market-data/get-midpoint-prices-query-parameters.md new file mode 100644 index 00000000..d21b9e66 --- /dev/null +++ b/PolymarketDocumentation-main/docs/api-reference/market-data/get-midpoint-prices-query-parameters.md @@ -0,0 +1,110 @@ +> ## Documentation Index +> Fetch the complete documentation index at: https://docs.polymarket.com/llms.txt +> Use this file to discover all available pages before exploring further. + +# Get midpoint prices (query parameters) + +> Retrieves midpoint prices for multiple token IDs using query parameters. +The midpoint is calculated as the average of the best bid and best ask prices. + + + + +## OpenAPI + +````yaml /api-spec/clob-openapi.yaml get /midpoints +openapi: 3.1.0 +info: + title: Polymarket CLOB API + description: Polymarket CLOB API Reference + license: + name: MIT + identifier: MIT + version: 1.0.0 +servers: + - url: https://clob.polymarket.com + description: Production CLOB API + - url: https://clob-staging.polymarket.com + description: Staging CLOB API +security: [] +tags: + - name: Trade + description: Trade endpoints + - name: Markets + description: Market data endpoints + - name: Account + description: Account and authentication endpoints + - name: Notifications + description: User notification endpoints + - name: Rewards + description: Rewards and earnings endpoints + - name: Rebates + description: Maker rebate endpoints +paths: + /midpoints: + get: + tags: + - Market Data + summary: Get midpoint prices (query parameters) + description: > + Retrieves midpoint prices for multiple token IDs using query parameters. + + The midpoint is calculated as the average of the best bid and best ask + prices. + operationId: getMidpointsGet + parameters: + - name: token_ids + in: query + description: Comma-separated list of token IDs + required: true + schema: + type: string + example: 0xabc123...,0xdef456... + responses: + '200': + description: Successfully retrieved midpoint prices + content: + application/json: + schema: + type: object + additionalProperties: + type: string + description: Map of token ID to midpoint price + example: + 0xabc123def456...: '0.45' + 0xdef456abc123...: '0.52' + '400': + description: Bad request - Invalid payload + content: + application/json: + schema: + $ref: '#/components/schemas/ErrorResponse' + example: + error: Invalid payload + '500': + description: Internal server error + content: + application/json: + schema: + $ref: '#/components/schemas/ErrorResponse' + example: + error: error getting the mid price + security: [] +components: + schemas: + ErrorResponse: + type: object + required: + - error + properties: + error: + type: string + description: Error message + code: + type: string + description: Machine-readable error code, when provided + retry_after_seconds: + type: integer + description: Number of seconds to wait before retrying, when provided + +```` \ No newline at end of file diff --git a/PolymarketDocumentation-main/docs/api-reference/market-data/get-midpoint-prices-request-body.md b/PolymarketDocumentation-main/docs/api-reference/market-data/get-midpoint-prices-request-body.md new file mode 100644 index 00000000..b86c55a1 --- /dev/null +++ b/PolymarketDocumentation-main/docs/api-reference/market-data/get-midpoint-prices-request-body.md @@ -0,0 +1,129 @@ +> ## Documentation Index +> Fetch the complete documentation index at: https://docs.polymarket.com/llms.txt +> Use this file to discover all available pages before exploring further. + +# Get midpoint prices (request body) + +> Retrieves midpoint prices for multiple token IDs using a request body. +The midpoint is calculated as the average of the best bid and best ask prices. + + + + +## OpenAPI + +````yaml /api-spec/clob-openapi.yaml post /midpoints +openapi: 3.1.0 +info: + title: Polymarket CLOB API + description: Polymarket CLOB API Reference + license: + name: MIT + identifier: MIT + version: 1.0.0 +servers: + - url: https://clob.polymarket.com + description: Production CLOB API + - url: https://clob-staging.polymarket.com + description: Staging CLOB API +security: [] +tags: + - name: Trade + description: Trade endpoints + - name: Markets + description: Market data endpoints + - name: Account + description: Account and authentication endpoints + - name: Notifications + description: User notification endpoints + - name: Rewards + description: Rewards and earnings endpoints + - name: Rebates + description: Maker rebate endpoints +paths: + /midpoints: + post: + tags: + - Market Data + summary: Get midpoint prices (request body) + description: > + Retrieves midpoint prices for multiple token IDs using a request body. + + The midpoint is calculated as the average of the best bid and best ask + prices. + operationId: getMidpointsPost + requestBody: + required: true + content: + application/json: + schema: + type: array + items: + $ref: '#/components/schemas/BookRequest' + example: + - token_id: 0xabc123def456... + - token_id: 0xdef456abc123... + responses: + '200': + description: Successfully retrieved midpoint prices + content: + application/json: + schema: + type: object + additionalProperties: + type: string + description: Map of token ID to midpoint price + example: + 0xabc123def456...: '0.45' + 0xdef456abc123...: '0.52' + '400': + description: Bad request - Invalid payload + content: + application/json: + schema: + $ref: '#/components/schemas/ErrorResponse' + example: + error: Invalid payload + '500': + description: Internal server error + content: + application/json: + schema: + $ref: '#/components/schemas/ErrorResponse' + example: + error: error getting the mid price + security: [] +components: + schemas: + BookRequest: + type: object + required: + - token_id + properties: + token_id: + type: string + description: Token ID (asset ID) + example: 0xabc123def456... + side: + type: string + description: Order side (optional, not used for midpoint calculation) + enum: + - BUY + - SELL + example: BUY + ErrorResponse: + type: object + required: + - error + properties: + error: + type: string + description: Error message + code: + type: string + description: Machine-readable error code, when provided + retry_after_seconds: + type: integer + description: Number of seconds to wait before retrying, when provided + +```` \ No newline at end of file diff --git a/PolymarketDocumentation-main/docs/api-reference/market-data/get-order-book.md b/PolymarketDocumentation-main/docs/api-reference/market-data/get-order-book.md new file mode 100644 index 00000000..383df69d --- /dev/null +++ b/PolymarketDocumentation-main/docs/api-reference/market-data/get-order-book.md @@ -0,0 +1,199 @@ +> ## Documentation Index +> Fetch the complete documentation index at: https://docs.polymarket.com/llms.txt +> Use this file to discover all available pages before exploring further. + +# Get order book + +> Retrieves the order book summary for a specific token ID. +Includes bids, asks, market details, and last trade price. + + + + +## OpenAPI + +````yaml /api-spec/clob-openapi.yaml get /book +openapi: 3.1.0 +info: + title: Polymarket CLOB API + description: Polymarket CLOB API Reference + license: + name: MIT + identifier: MIT + version: 1.0.0 +servers: + - url: https://clob.polymarket.com + description: Production CLOB API + - url: https://clob-staging.polymarket.com + description: Staging CLOB API +security: [] +tags: + - name: Trade + description: Trade endpoints + - name: Markets + description: Market data endpoints + - name: Account + description: Account and authentication endpoints + - name: Notifications + description: User notification endpoints + - name: Rewards + description: Rewards and earnings endpoints + - name: Rebates + description: Maker rebate endpoints +paths: + /book: + get: + tags: + - Market Data + summary: Get order book + description: | + Retrieves the order book summary for a specific token ID. + Includes bids, asks, market details, and last trade price. + operationId: getBook + parameters: + - name: token_id + in: query + description: Token ID (asset ID) + required: true + schema: + type: string + example: 0xabc123def456... + responses: + '200': + description: Successfully retrieved order book + content: + application/json: + schema: + $ref: '#/components/schemas/OrderBookSummary' + example: + market: '0x1234567890123456789012345678901234567890' + asset_id: 0xabc123def456... + timestamp: '1234567890' + hash: a1b2c3d4e5f6... + bids: + - price: '0.45' + size: '100' + - price: '0.44' + size: '200' + asks: + - price: '0.46' + size: '150' + - price: '0.47' + size: '250' + min_order_size: '1' + tick_size: '0.01' + neg_risk: false + last_trade_price: '0.45' + '400': + description: Bad request - Invalid token id + content: + application/json: + schema: + $ref: '#/components/schemas/ErrorResponse' + example: + error: Invalid token id + '404': + description: Not found - No orderbook exists for the requested token id + content: + application/json: + schema: + $ref: '#/components/schemas/ErrorResponse' + example: + error: No orderbook exists for the requested token id + '500': + description: Internal server error + content: + application/json: + schema: + $ref: '#/components/schemas/ErrorResponse' + example: + error: error getting the orderbook + security: [] +components: + schemas: + OrderBookSummary: + type: object + required: + - market + - asset_id + - timestamp + - hash + - bids + - asks + - min_order_size + - tick_size + - neg_risk + - last_trade_price + properties: + market: + type: string + description: Market condition ID + example: '0x1234567890123456789012345678901234567890' + asset_id: + type: string + description: Token ID (asset ID) + example: 0xabc123def456... + timestamp: + type: string + description: Timestamp of the order book snapshot + example: '1234567890' + hash: + type: string + description: Hash of the order book summary + example: a1b2c3d4e5f6... + bids: + type: array + description: List of bid orders (sorted by price descending) + items: + $ref: '#/components/schemas/OrderSummary' + asks: + type: array + description: List of ask orders (sorted by price ascending) + items: + $ref: '#/components/schemas/OrderSummary' + min_order_size: + type: string + description: Minimum order size + example: '1' + tick_size: + type: string + description: Minimum price increment (tick size) + example: '0.01' + neg_risk: + type: boolean + description: Whether negative risk is enabled for this market + example: false + last_trade_price: + type: string + description: Last trade price + example: '0.45' + ErrorResponse: + type: object + required: + - error + properties: + error: + type: string + description: Error message + code: + type: string + description: Machine-readable error code, when provided + retry_after_seconds: + type: integer + description: Number of seconds to wait before retrying, when provided + OrderSummary: + type: object + required: + - price + - size + properties: + price: + type: string + description: Order price + example: '0.45' + size: + type: string + description: Order size + example: '100' + +```` \ No newline at end of file diff --git a/PolymarketDocumentation-main/docs/api-reference/market-data/get-order-books-request-body.md b/PolymarketDocumentation-main/docs/api-reference/market-data/get-order-books-request-body.md new file mode 100644 index 00000000..1c4a1349 --- /dev/null +++ b/PolymarketDocumentation-main/docs/api-reference/market-data/get-order-books-request-body.md @@ -0,0 +1,199 @@ +> ## Documentation Index +> Fetch the complete documentation index at: https://docs.polymarket.com/llms.txt +> Use this file to discover all available pages before exploring further. + +# Get order books (request body) + +> Retrieves order book summaries for multiple token IDs using a request body. + + + + +## OpenAPI + +````yaml /api-spec/clob-openapi.yaml post /books +openapi: 3.1.0 +info: + title: Polymarket CLOB API + description: Polymarket CLOB API Reference + license: + name: MIT + identifier: MIT + version: 1.0.0 +servers: + - url: https://clob.polymarket.com + description: Production CLOB API + - url: https://clob-staging.polymarket.com + description: Staging CLOB API +security: [] +tags: + - name: Trade + description: Trade endpoints + - name: Markets + description: Market data endpoints + - name: Account + description: Account and authentication endpoints + - name: Notifications + description: User notification endpoints + - name: Rewards + description: Rewards and earnings endpoints + - name: Rebates + description: Maker rebate endpoints +paths: + /books: + post: + tags: + - Market Data + summary: Get order books (request body) + description: > + Retrieves order book summaries for multiple token IDs using a request + body. + operationId: getBooksPost + requestBody: + required: true + content: + application/json: + schema: + type: array + items: + $ref: '#/components/schemas/BookRequest' + example: + - token_id: 0xabc123def456... + - token_id: 0xdef456abc123... + responses: + '200': + description: Successfully retrieved order books + content: + application/json: + schema: + type: array + items: + $ref: '#/components/schemas/OrderBookSummary' + example: + - market: '0x1234567890123456789012345678901234567890' + asset_id: 0xabc123def456... + timestamp: '1234567890' + hash: a1b2c3d4e5f6... + bids: + - price: '0.45' + size: '100' + asks: + - price: '0.46' + size: '150' + min_order_size: '1' + tick_size: '0.01' + neg_risk: false + last_trade_price: '0.45' + '400': + description: Bad request - Invalid payload + content: + application/json: + schema: + $ref: '#/components/schemas/ErrorResponse' + example: + error: Invalid payload + security: [] +components: + schemas: + BookRequest: + type: object + required: + - token_id + properties: + token_id: + type: string + description: Token ID (asset ID) + example: 0xabc123def456... + side: + type: string + description: Order side (optional, not used for midpoint calculation) + enum: + - BUY + - SELL + example: BUY + OrderBookSummary: + type: object + required: + - market + - asset_id + - timestamp + - hash + - bids + - asks + - min_order_size + - tick_size + - neg_risk + - last_trade_price + properties: + market: + type: string + description: Market condition ID + example: '0x1234567890123456789012345678901234567890' + asset_id: + type: string + description: Token ID (asset ID) + example: 0xabc123def456... + timestamp: + type: string + description: Timestamp of the order book snapshot + example: '1234567890' + hash: + type: string + description: Hash of the order book summary + example: a1b2c3d4e5f6... + bids: + type: array + description: List of bid orders (sorted by price descending) + items: + $ref: '#/components/schemas/OrderSummary' + asks: + type: array + description: List of ask orders (sorted by price ascending) + items: + $ref: '#/components/schemas/OrderSummary' + min_order_size: + type: string + description: Minimum order size + example: '1' + tick_size: + type: string + description: Minimum price increment (tick size) + example: '0.01' + neg_risk: + type: boolean + description: Whether negative risk is enabled for this market + example: false + last_trade_price: + type: string + description: Last trade price + example: '0.45' + ErrorResponse: + type: object + required: + - error + properties: + error: + type: string + description: Error message + code: + type: string + description: Machine-readable error code, when provided + retry_after_seconds: + type: integer + description: Number of seconds to wait before retrying, when provided + OrderSummary: + type: object + required: + - price + - size + properties: + price: + type: string + description: Order price + example: '0.45' + size: + type: string + description: Order size + example: '100' + +```` \ No newline at end of file diff --git a/PolymarketDocumentation-main/docs/api-reference/market-data/get-spread.md b/PolymarketDocumentation-main/docs/api-reference/market-data/get-spread.md new file mode 100644 index 00000000..7bef021c --- /dev/null +++ b/PolymarketDocumentation-main/docs/api-reference/market-data/get-spread.md @@ -0,0 +1,109 @@ +> ## Documentation Index +> Fetch the complete documentation index at: https://docs.polymarket.com/llms.txt +> Use this file to discover all available pages before exploring further. + +# Get spread + +> Retrieves the spread for a specific token ID. +The spread is the difference between the best ask and best bid prices. + + + + +## OpenAPI + +````yaml /api-spec/clob-openapi.yaml get /spread +openapi: 3.1.0 +info: + title: Polymarket CLOB API + description: Polymarket CLOB API Reference + license: + name: MIT + identifier: MIT + version: 1.0.0 +servers: + - url: https://clob.polymarket.com + description: Production CLOB API + - url: https://clob-staging.polymarket.com + description: Staging CLOB API +security: [] +tags: + - name: Trade + description: Trade endpoints + - name: Markets + description: Market data endpoints + - name: Account + description: Account and authentication endpoints + - name: Notifications + description: User notification endpoints + - name: Rewards + description: Rewards and earnings endpoints + - name: Rebates + description: Maker rebate endpoints +paths: + /spread: + get: + tags: + - Market Data + summary: Get spread + description: | + Retrieves the spread for a specific token ID. + The spread is the difference between the best ask and best bid prices. + operationId: getSpread + parameters: + - name: token_id + in: query + description: Token ID (asset ID) + required: true + schema: + type: string + example: 0xabc123def456... + responses: + '200': + description: Successfully retrieved spread + content: + application/json: + schema: + type: object + required: + - spread + properties: + spread: + type: string + description: Spread as a string + example: '0.02' + '400': + description: Bad request - Invalid token id + content: + application/json: + schema: + $ref: '#/components/schemas/ErrorResponse' + example: + error: Invalid token id + '404': + description: Not found - No orderbook exists for the requested token id + content: + application/json: + schema: + $ref: '#/components/schemas/ErrorResponse' + example: + error: No orderbook exists for the requested token id + security: [] +components: + schemas: + ErrorResponse: + type: object + required: + - error + properties: + error: + type: string + description: Error message + code: + type: string + description: Machine-readable error code, when provided + retry_after_seconds: + type: integer + description: Number of seconds to wait before retrying, when provided + +```` \ No newline at end of file diff --git a/PolymarketDocumentation-main/docs/api-reference/market-data/get-spreads.md b/PolymarketDocumentation-main/docs/api-reference/market-data/get-spreads.md new file mode 100644 index 00000000..f6b97333 --- /dev/null +++ b/PolymarketDocumentation-main/docs/api-reference/market-data/get-spreads.md @@ -0,0 +1,127 @@ +> ## Documentation Index +> Fetch the complete documentation index at: https://docs.polymarket.com/llms.txt +> Use this file to discover all available pages before exploring further. + +# Get spreads + +> Retrieves spreads for multiple token IDs. +The spread is the difference between the best ask and best bid prices. + + + + +## OpenAPI + +````yaml /api-spec/clob-openapi.yaml post /spreads +openapi: 3.1.0 +info: + title: Polymarket CLOB API + description: Polymarket CLOB API Reference + license: + name: MIT + identifier: MIT + version: 1.0.0 +servers: + - url: https://clob.polymarket.com + description: Production CLOB API + - url: https://clob-staging.polymarket.com + description: Staging CLOB API +security: [] +tags: + - name: Trade + description: Trade endpoints + - name: Markets + description: Market data endpoints + - name: Account + description: Account and authentication endpoints + - name: Notifications + description: User notification endpoints + - name: Rewards + description: Rewards and earnings endpoints + - name: Rebates + description: Maker rebate endpoints +paths: + /spreads: + post: + tags: + - Market Data + summary: Get spreads + description: | + Retrieves spreads for multiple token IDs. + The spread is the difference between the best ask and best bid prices. + operationId: getSpreads + requestBody: + required: true + content: + application/json: + schema: + type: array + items: + $ref: '#/components/schemas/BookRequest' + example: + - token_id: 0xabc123def456... + - token_id: 0xdef456abc123... + responses: + '200': + description: Successfully retrieved spreads + content: + application/json: + schema: + type: object + additionalProperties: + type: string + description: Map of token ID to spread + example: + 0xabc123def456...: '0.02' + 0xdef456abc123...: '0.015' + '400': + description: Bad request - Invalid payload + content: + application/json: + schema: + $ref: '#/components/schemas/ErrorResponse' + example: + error: Invalid payload + '500': + description: Internal server error + content: + application/json: + schema: + $ref: '#/components/schemas/ErrorResponse' + example: + error: error getting the spread + security: [] +components: + schemas: + BookRequest: + type: object + required: + - token_id + properties: + token_id: + type: string + description: Token ID (asset ID) + example: 0xabc123def456... + side: + type: string + description: Order side (optional, not used for midpoint calculation) + enum: + - BUY + - SELL + example: BUY + ErrorResponse: + type: object + required: + - error + properties: + error: + type: string + description: Error message + code: + type: string + description: Machine-readable error code, when provided + retry_after_seconds: + type: integer + description: Number of seconds to wait before retrying, when provided + +```` \ No newline at end of file diff --git a/PolymarketDocumentation-main/docs/api-reference/market-data/get-tick-size-by-path-parameter.md b/PolymarketDocumentation-main/docs/api-reference/market-data/get-tick-size-by-path-parameter.md new file mode 100644 index 00000000..76a11d07 --- /dev/null +++ b/PolymarketDocumentation-main/docs/api-reference/market-data/get-tick-size-by-path-parameter.md @@ -0,0 +1,121 @@ +> ## Documentation Index +> Fetch the complete documentation index at: https://docs.polymarket.com/llms.txt +> Use this file to discover all available pages before exploring further. + +# Get tick size by path parameter + +> Retrieves the minimum tick size (price increment) for a specific token ID using the token ID as a path parameter. + + + + +## OpenAPI + +````yaml /api-spec/clob-openapi.yaml get /tick-size/{token_id} +openapi: 3.1.0 +info: + title: Polymarket CLOB API + description: Polymarket CLOB API Reference + license: + name: MIT + identifier: MIT + version: 1.0.0 +servers: + - url: https://clob.polymarket.com + description: Production CLOB API + - url: https://clob-staging.polymarket.com + description: Staging CLOB API +security: [] +tags: + - name: Trade + description: Trade endpoints + - name: Markets + description: Market data endpoints + - name: Account + description: Account and authentication endpoints + - name: Notifications + description: User notification endpoints + - name: Rewards + description: Rewards and earnings endpoints + - name: Rebates + description: Maker rebate endpoints +paths: + /tick-size/{token_id}: + get: + tags: + - Market Data + summary: Get tick size by path parameter + description: > + Retrieves the minimum tick size (price increment) for a specific token + ID using the token ID as a path parameter. + operationId: getTickSizeByPath + parameters: + - name: token_id + in: path + description: Token ID (asset ID) + required: true + schema: + type: string + example: 0xabc123def456... + responses: + '200': + description: Successfully retrieved tick size + content: + application/json: + schema: + $ref: '#/components/schemas/TickSize' + example: + minimum_tick_size: 0.01 + '400': + description: Bad request - Invalid token id + content: + application/json: + schema: + $ref: '#/components/schemas/ErrorResponse' + example: + error: Invalid token id + '404': + description: Not found - Market not found + content: + application/json: + schema: + $ref: '#/components/schemas/ErrorResponse' + example: + error: market not found + '500': + description: Internal server error + content: + application/json: + schema: + $ref: '#/components/schemas/ErrorResponse' + example: + error: Internal server error + security: [] +components: + schemas: + TickSize: + type: object + required: + - minimum_tick_size + properties: + minimum_tick_size: + type: number + format: double + description: Minimum tick size (price increment) + example: 0.01 + ErrorResponse: + type: object + required: + - error + properties: + error: + type: string + description: Error message + code: + type: string + description: Machine-readable error code, when provided + retry_after_seconds: + type: integer + description: Number of seconds to wait before retrying, when provided + +```` \ No newline at end of file diff --git a/PolymarketDocumentation-main/docs/api-reference/market-data/get-tick-size.md b/PolymarketDocumentation-main/docs/api-reference/market-data/get-tick-size.md new file mode 100644 index 00000000..88553ee8 --- /dev/null +++ b/PolymarketDocumentation-main/docs/api-reference/market-data/get-tick-size.md @@ -0,0 +1,125 @@ +> ## Documentation Index +> Fetch the complete documentation index at: https://docs.polymarket.com/llms.txt +> Use this file to discover all available pages before exploring further. + +# Get tick size + +> Retrieves the minimum tick size (price increment) for a specific token ID. +The tick size can be provided either as a query parameter or as a path parameter. + + + + +## OpenAPI + +````yaml /api-spec/clob-openapi.yaml get /tick-size +openapi: 3.1.0 +info: + title: Polymarket CLOB API + description: Polymarket CLOB API Reference + license: + name: MIT + identifier: MIT + version: 1.0.0 +servers: + - url: https://clob.polymarket.com + description: Production CLOB API + - url: https://clob-staging.polymarket.com + description: Staging CLOB API +security: [] +tags: + - name: Trade + description: Trade endpoints + - name: Markets + description: Market data endpoints + - name: Account + description: Account and authentication endpoints + - name: Notifications + description: User notification endpoints + - name: Rewards + description: Rewards and earnings endpoints + - name: Rebates + description: Maker rebate endpoints +paths: + /tick-size: + get: + tags: + - Market Data + summary: Get tick size + description: > + Retrieves the minimum tick size (price increment) for a specific token + ID. + + The tick size can be provided either as a query parameter or as a path + parameter. + operationId: getTickSize + parameters: + - name: token_id + in: query + description: Token ID (asset ID) + required: false + schema: + type: string + example: 0xabc123def456... + responses: + '200': + description: Successfully retrieved tick size + content: + application/json: + schema: + $ref: '#/components/schemas/TickSize' + example: + minimum_tick_size: 0.01 + '400': + description: Bad request - Invalid token id + content: + application/json: + schema: + $ref: '#/components/schemas/ErrorResponse' + example: + error: Invalid token id + '404': + description: Not found - Market not found + content: + application/json: + schema: + $ref: '#/components/schemas/ErrorResponse' + example: + error: market not found + '500': + description: Internal server error + content: + application/json: + schema: + $ref: '#/components/schemas/ErrorResponse' + example: + error: Internal server error + security: [] +components: + schemas: + TickSize: + type: object + required: + - minimum_tick_size + properties: + minimum_tick_size: + type: number + format: double + description: Minimum tick size (price increment) + example: 0.01 + ErrorResponse: + type: object + required: + - error + properties: + error: + type: string + description: Error message + code: + type: string + description: Machine-readable error code, when provided + retry_after_seconds: + type: integer + description: Number of seconds to wait before retrying, when provided + +```` \ No newline at end of file diff --git a/PolymarketDocumentation-main/docs/api-reference/markets/get-batch-prices-history.md b/PolymarketDocumentation-main/docs/api-reference/markets/get-batch-prices-history.md new file mode 100644 index 00000000..7d92de2a --- /dev/null +++ b/PolymarketDocumentation-main/docs/api-reference/markets/get-batch-prices-history.md @@ -0,0 +1,144 @@ +> ## Documentation Index +> Fetch the complete documentation index at: https://docs.polymarket.com/llms.txt +> Use this file to discover all available pages before exploring further. + +# Get batch prices history + +> Retrieve historical price data for multiple markets in a single request. + + + +## OpenAPI + +````yaml /api-spec/clob-openapi.yaml post /batch-prices-history +openapi: 3.1.0 +info: + title: Polymarket CLOB API + description: Polymarket CLOB API Reference + license: + name: MIT + identifier: MIT + version: 1.0.0 +servers: + - url: https://clob.polymarket.com + description: Production CLOB API + - url: https://clob-staging.polymarket.com + description: Staging CLOB API +security: [] +tags: + - name: Trade + description: Trade endpoints + - name: Markets + description: Market data endpoints + - name: Account + description: Account and authentication endpoints + - name: Notifications + description: User notification endpoints + - name: Rewards + description: Rewards and earnings endpoints + - name: Rebates + description: Maker rebate endpoints +paths: + /batch-prices-history: + post: + tags: + - Markets + summary: Get batch prices history + description: Retrieve historical price data for multiple markets in a single request. + operationId: getBatchPricesHistory + requestBody: + required: true + content: + application/json: + schema: + $ref: '#/components/schemas/BatchPricesHistoryRequest' + responses: + '200': + description: Successful response with price history for each market + content: + application/json: + schema: + $ref: '#/components/schemas/BatchPricesHistoryResponse' + '400': + description: Bad Request - Missing or invalid parameters + content: + application/json: + schema: + $ref: '#/components/schemas/ErrorResponse' + '500': + description: Internal server error + content: + application/json: + schema: + $ref: '#/components/schemas/ErrorResponse' + security: [] +components: + schemas: + BatchPricesHistoryRequest: + type: object + required: + - markets + properties: + markets: + type: array + items: + type: string + description: List of market asset ids to query. Maximum 20. + maxItems: 20 + start_ts: + type: number + format: double + description: Filter by items after this unix timestamp (seconds). + end_ts: + type: number + format: double + description: Filter by items before this unix timestamp (seconds). + interval: + type: string + enum: + - max + - all + - 1m + - 1w + - 1d + - 6h + - 1h + description: Time interval for data aggregation. + fidelity: + type: integer + description: Accuracy of the data expressed in minutes. Default is 1 minute. + BatchPricesHistoryResponse: + type: object + properties: + history: + type: object + additionalProperties: + type: array + items: + $ref: '#/components/schemas/MarketPrice' + description: Map of market asset id to array of price data points. + ErrorResponse: + type: object + required: + - error + properties: + error: + type: string + description: Error message + code: + type: string + description: Machine-readable error code, when provided + retry_after_seconds: + type: integer + description: Number of seconds to wait before retrying, when provided + MarketPrice: + type: object + properties: + t: + type: integer + format: uint32 + p: + type: number + format: float + +```` \ No newline at end of file diff --git a/PolymarketDocumentation-main/docs/api-reference/markets/get-clob-market-info.md b/PolymarketDocumentation-main/docs/api-reference/markets/get-clob-market-info.md new file mode 100644 index 00000000..43ef68e0 --- /dev/null +++ b/PolymarketDocumentation-main/docs/api-reference/markets/get-clob-market-info.md @@ -0,0 +1,192 @@ +> ## Documentation Index +> Fetch the complete documentation index at: https://docs.polymarket.com/llms.txt +> Use this file to discover all available pages before exploring further. + +# Get CLOB market info + +> Returns all CLOB-level parameters for a market in a single call — +tokens, tick size, base fees, rewards, RFQ status, and fee details. + + + + +## OpenAPI + +````yaml /api-spec/clob-openapi.yaml get /clob-markets/{condition_id} +openapi: 3.1.0 +info: + title: Polymarket CLOB API + description: Polymarket CLOB API Reference + license: + name: MIT + identifier: MIT + version: 1.0.0 +servers: + - url: https://clob.polymarket.com + description: Production CLOB API + - url: https://clob-staging.polymarket.com + description: Staging CLOB API +security: [] +tags: + - name: Trade + description: Trade endpoints + - name: Markets + description: Market data endpoints + - name: Account + description: Account and authentication endpoints + - name: Notifications + description: User notification endpoints + - name: Rewards + description: Rewards and earnings endpoints + - name: Rebates + description: Maker rebate endpoints +paths: + /clob-markets/{condition_id}: + get: + tags: + - Markets + summary: Get CLOB market info + description: | + Returns all CLOB-level parameters for a market in a single call — + tokens, tick size, base fees, rewards, RFQ status, and fee details. + operationId: getClobMarketInfo + parameters: + - name: condition_id + in: path + required: true + description: The condition ID of the market + schema: + type: string + example: '0xbd31dc8a20211944f6b70f31557f1001557b59905b7738480ca09bd4532f84af' + responses: + '200': + description: Successfully retrieved CLOB market info + content: + application/json: + schema: + $ref: '#/components/schemas/ClobMarketDetails' + '400': + description: Bad request - Invalid condition ID + content: + application/json: + schema: + $ref: '#/components/schemas/ErrorResponse' + '500': + description: Internal server error + content: + application/json: + schema: + $ref: '#/components/schemas/ErrorResponse' +components: + schemas: + ClobMarketDetails: + type: object + description: >- + CLOB-level parameters for a market — tokens, tick size, base fees, + rewards, RFQ status, and fee details. + properties: + gst: + type: string + format: date-time + nullable: true + description: >- + Game start time (used for sports markets), ISO 8601 timestamp or + null + r: + $ref: '#/components/schemas/ClobRewards' + t: + type: array + description: Tokens for this market + items: + $ref: '#/components/schemas/ClobToken' + mos: + type: number + format: float + description: Minimum order size + example: 5 + mts: + type: number + format: float + description: Minimum tick size (price increment) + example: 0.01 + mbf: + type: integer + format: int64 + description: Maker base fee in basis points + example: 0 + tbf: + type: integer + format: int64 + description: Taker base fee in basis points + example: 0 + rfqe: + type: boolean + description: Whether RFQ (Request for Quote) is enabled for this market + itode: + type: boolean + description: >- + Whether taker order delay is enabled for this market. When true, + marketable orders are held for the 250 ms taker-delay window before + synchronous processing. This field is omitted when false. + ibce: + type: boolean + description: Whether Blockaid check is enabled + fd: + $ref: '#/components/schemas/FeeDetails' + oas: + type: integer + description: Minimum order age in seconds + ErrorResponse: + type: object + required: + - error + properties: + error: + type: string + description: Error message + code: + type: string + description: Machine-readable error code, when provided + retry_after_seconds: + type: integer + description: Number of seconds to wait before retrying, when provided + ClobRewards: + type: object + description: Rewards configuration for a market. + additionalProperties: true + ClobToken: + type: object + description: A token in a CLOB market with its ID and outcome label. + properties: + t: + type: string + description: The token ID + example: >- + 71321045679252212594626385532706912750332728571942532289631379312455583992563 + o: + type: string + description: Outcome label for the token (e.g. "Yes", "No") + example: 'Yes' + FeeDetails: + type: object + description: Fee curve parameters for a market. + properties: + r: + type: number + format: float + nullable: true + description: Fee rate + example: 0.02 + e: + type: number + format: float + nullable: true + description: Fee curve exponent + example: 2 + to: + type: boolean + nullable: true + description: Whether fees apply to takers only + example: true + +```` \ No newline at end of file diff --git a/PolymarketDocumentation-main/docs/api-reference/markets/get-market-by-id.md b/PolymarketDocumentation-main/docs/api-reference/markets/get-market-by-id.md new file mode 100644 index 00000000..49d69a58 --- /dev/null +++ b/PolymarketDocumentation-main/docs/api-reference/markets/get-market-by-id.md @@ -0,0 +1,1209 @@ +> ## Documentation Index +> Fetch the complete documentation index at: https://docs.polymarket.com/llms.txt +> Use this file to discover all available pages before exploring further. + +# Get market by id + + + +## OpenAPI + +````yaml /api-spec/gamma-openapi.yaml get /markets/{id} +openapi: 3.0.3 +info: + title: Markets API + version: 1.0.0 + description: REST API specification for public endpoints used by the Markets service. +servers: + - url: https://gamma-api.polymarket.com + description: Polymarket Gamma API Production Server +security: [] +tags: + - name: Gamma Status + description: Gamma API status and health check + - name: Sports + description: Sports-related endpoints including teams and game data + - name: Tags + description: Tag management and related tag operations + - name: Events + description: Event management and event-related operations + - name: Markets + description: Market data and market-related operations + - name: Comments + description: Comment system and user interactions + - name: Series + description: Series management and related operations + - name: Profiles + description: User profile management + - name: Search + description: Search functionality across different entity types +paths: + /markets/{id}: + get: + tags: + - Markets + summary: Get market by id + operationId: getMarket + parameters: + - $ref: '#/components/parameters/pathId' + - name: include_tag + in: query + schema: + type: boolean + responses: + '200': + description: Market + content: + application/json: + schema: + $ref: '#/components/schemas/Market' + '404': + description: Not found +components: + parameters: + pathId: + name: id + in: path + required: true + schema: + type: integer + schemas: + Market: + type: object + properties: + id: + type: string + question: + type: string + nullable: true + conditionId: + type: string + slug: + type: string + nullable: true + twitterCardImage: + type: string + nullable: true + resolutionSource: + type: string + nullable: true + endDate: + type: string + format: date-time + nullable: true + category: + type: string + nullable: true + ammType: + type: string + nullable: true + liquidity: + type: string + nullable: true + sponsorName: + type: string + nullable: true + sponsorImage: + type: string + nullable: true + startDate: + type: string + format: date-time + nullable: true + xAxisValue: + type: string + nullable: true + yAxisValue: + type: string + nullable: true + denominationToken: + type: string + nullable: true + fee: + type: string + nullable: true + image: + type: string + nullable: true + icon: + type: string + nullable: true + lowerBound: + type: string + nullable: true + upperBound: + type: string + nullable: true + description: + type: string + nullable: true + outcomes: + type: string + nullable: true + outcomePrices: + type: string + nullable: true + volume: + type: string + nullable: true + active: + type: boolean + nullable: true + marketType: + type: string + nullable: true + formatType: + type: string + nullable: true + lowerBoundDate: + type: string + nullable: true + upperBoundDate: + type: string + nullable: true + closed: + type: boolean + nullable: true + marketMakerAddress: + type: string + createdBy: + type: integer + nullable: true + updatedBy: + type: integer + nullable: true + createdAt: + type: string + format: date-time + nullable: true + updatedAt: + type: string + format: date-time + nullable: true + closedTime: + type: string + nullable: true + wideFormat: + type: boolean + nullable: true + new: + type: boolean + nullable: true + mailchimpTag: + type: string + nullable: true + featured: + type: boolean + nullable: true + archived: + type: boolean + nullable: true + resolvedBy: + type: string + nullable: true + restricted: + type: boolean + nullable: true + marketGroup: + type: integer + nullable: true + groupItemTitle: + type: string + nullable: true + groupItemThreshold: + type: string + nullable: true + questionID: + type: string + nullable: true + umaEndDate: + type: string + nullable: true + enableOrderBook: + type: boolean + nullable: true + orderPriceMinTickSize: + type: number + nullable: true + orderMinSize: + type: number + nullable: true + umaResolutionStatus: + type: string + nullable: true + curationOrder: + type: integer + nullable: true + volumeNum: + type: number + nullable: true + liquidityNum: + type: number + nullable: true + endDateIso: + type: string + nullable: true + startDateIso: + type: string + nullable: true + umaEndDateIso: + type: string + nullable: true + hasReviewedDates: + type: boolean + nullable: true + readyForCron: + type: boolean + nullable: true + commentsEnabled: + type: boolean + nullable: true + volume24hr: + type: number + nullable: true + volume1wk: + type: number + nullable: true + volume1mo: + type: number + nullable: true + volume1yr: + type: number + nullable: true + gameStartTime: + type: string + nullable: true + secondsDelay: + type: integer + nullable: true + clobTokenIds: + type: string + nullable: true + disqusThread: + type: string + nullable: true + shortOutcomes: + type: string + nullable: true + teamAID: + type: string + nullable: true + teamBID: + type: string + nullable: true + umaBond: + type: string + nullable: true + umaReward: + type: string + nullable: true + fpmmLive: + type: boolean + nullable: true + volume24hrAmm: + type: number + nullable: true + volume1wkAmm: + type: number + nullable: true + volume1moAmm: + type: number + nullable: true + volume1yrAmm: + type: number + nullable: true + volume24hrClob: + type: number + nullable: true + volume1wkClob: + type: number + nullable: true + volume1moClob: + type: number + nullable: true + volume1yrClob: + type: number + nullable: true + volumeAmm: + type: number + nullable: true + volumeClob: + type: number + nullable: true + liquidityAmm: + type: number + nullable: true + liquidityClob: + type: number + nullable: true + makerBaseFee: + type: integer + nullable: true + takerBaseFee: + type: integer + nullable: true + customLiveness: + type: integer + nullable: true + acceptingOrders: + type: boolean + nullable: true + notificationsEnabled: + type: boolean + nullable: true + score: + type: integer + nullable: true + imageOptimized: + $ref: '#/components/schemas/ImageOptimization' + iconOptimized: + $ref: '#/components/schemas/ImageOptimization' + events: + type: array + items: + $ref: '#/components/schemas/Event' + categories: + type: array + items: + $ref: '#/components/schemas/Category' + tags: + type: array + items: + $ref: '#/components/schemas/Tag' + creator: + type: string + nullable: true + ready: + type: boolean + nullable: true + funded: + type: boolean + nullable: true + pastSlugs: + type: string + nullable: true + readyTimestamp: + type: string + format: date-time + nullable: true + fundedTimestamp: + type: string + format: date-time + nullable: true + acceptingOrdersTimestamp: + type: string + format: date-time + nullable: true + competitive: + type: number + nullable: true + rewardsMinSize: + type: number + nullable: true + rewardsMaxSpread: + type: number + nullable: true + spread: + type: number + nullable: true + automaticallyResolved: + type: boolean + nullable: true + oneDayPriceChange: + type: number + nullable: true + oneHourPriceChange: + type: number + nullable: true + oneWeekPriceChange: + type: number + nullable: true + oneMonthPriceChange: + type: number + nullable: true + oneYearPriceChange: + type: number + nullable: true + lastTradePrice: + type: number + nullable: true + bestBid: + type: number + nullable: true + bestAsk: + type: number + nullable: true + automaticallyActive: + type: boolean + nullable: true + clearBookOnStart: + type: boolean + nullable: true + chartColor: + type: string + nullable: true + seriesColor: + type: string + nullable: true + showGmpSeries: + type: boolean + nullable: true + showGmpOutcome: + type: boolean + nullable: true + manualActivation: + type: boolean + nullable: true + negRiskOther: + type: boolean + nullable: true + gameId: + type: string + nullable: true + groupItemRange: + type: string + nullable: true + sportsMarketType: + type: string + nullable: true + line: + type: number + nullable: true + umaResolutionStatuses: + type: string + nullable: true + pendingDeployment: + type: boolean + nullable: true + deploying: + type: boolean + nullable: true + deployingTimestamp: + type: string + format: date-time + nullable: true + scheduledDeploymentTimestamp: + type: string + format: date-time + nullable: true + rfqEnabled: + type: boolean + nullable: true + eventStartTime: + type: string + format: date-time + nullable: true + feesEnabled: + type: boolean + nullable: true + feeSchedule: + $ref: '#/components/schemas/FeeSchedule' + ImageOptimization: + type: object + properties: + id: + type: string + imageUrlSource: + type: string + nullable: true + imageUrlOptimized: + type: string + nullable: true + imageSizeKbSource: + type: number + nullable: true + imageSizeKbOptimized: + type: number + nullable: true + imageOptimizedComplete: + type: boolean + nullable: true + imageOptimizedLastUpdated: + type: string + nullable: true + relID: + type: integer + nullable: true + field: + type: string + nullable: true + relname: + type: string + nullable: true + Event: + type: object + properties: + id: + type: string + ticker: + type: string + nullable: true + slug: + type: string + nullable: true + title: + type: string + nullable: true + subtitle: + type: string + nullable: true + description: + type: string + nullable: true + resolutionSource: + type: string + nullable: true + startDate: + type: string + format: date-time + nullable: true + creationDate: + type: string + format: date-time + nullable: true + endDate: + type: string + format: date-time + nullable: true + image: + type: string + nullable: true + icon: + type: string + nullable: true + active: + type: boolean + nullable: true + closed: + type: boolean + nullable: true + archived: + type: boolean + nullable: true + new: + type: boolean + nullable: true + featured: + type: boolean + nullable: true + restricted: + type: boolean + nullable: true + liquidity: + type: number + nullable: true + volume: + type: number + nullable: true + openInterest: + type: number + nullable: true + sortBy: + type: string + nullable: true + category: + type: string + nullable: true + subcategory: + type: string + nullable: true + isTemplate: + type: boolean + nullable: true + templateVariables: + type: string + nullable: true + published_at: + type: string + nullable: true + createdBy: + type: string + nullable: true + updatedBy: + type: string + nullable: true + createdAt: + type: string + format: date-time + nullable: true + updatedAt: + type: string + format: date-time + nullable: true + commentsEnabled: + type: boolean + nullable: true + competitive: + type: number + nullable: true + volume24hr: + type: number + nullable: true + volume1wk: + type: number + nullable: true + volume1mo: + type: number + nullable: true + volume1yr: + type: number + nullable: true + featuredImage: + type: string + nullable: true + disqusThread: + type: string + nullable: true + parentEvent: + type: string + nullable: true + enableOrderBook: + type: boolean + nullable: true + liquidityAmm: + type: number + nullable: true + liquidityClob: + type: number + nullable: true + negRisk: + type: boolean + nullable: true + negRiskMarketID: + type: string + nullable: true + negRiskFeeBips: + type: integer + nullable: true + commentCount: + type: integer + nullable: true + imageOptimized: + $ref: '#/components/schemas/ImageOptimization' + iconOptimized: + $ref: '#/components/schemas/ImageOptimization' + featuredImageOptimized: + $ref: '#/components/schemas/ImageOptimization' + subEvents: + type: array + items: + type: string + nullable: true + markets: + type: array + items: + $ref: '#/components/schemas/Market' + series: + type: array + items: + $ref: '#/components/schemas/Series' + categories: + type: array + items: + $ref: '#/components/schemas/Category' + collections: + type: array + items: + $ref: '#/components/schemas/Collection' + tags: + type: array + items: + $ref: '#/components/schemas/Tag' + cyom: + type: boolean + nullable: true + closedTime: + type: string + format: date-time + nullable: true + showAllOutcomes: + type: boolean + nullable: true + showMarketImages: + type: boolean + nullable: true + automaticallyResolved: + type: boolean + nullable: true + enableNegRisk: + type: boolean + nullable: true + automaticallyActive: + type: boolean + nullable: true + eventDate: + type: string + nullable: true + startTime: + type: string + format: date-time + nullable: true + eventWeek: + type: integer + nullable: true + seriesSlug: + type: string + nullable: true + score: + type: string + nullable: true + elapsed: + type: string + nullable: true + period: + type: string + nullable: true + live: + type: boolean + nullable: true + ended: + type: boolean + nullable: true + finishedTimestamp: + type: string + format: date-time + nullable: true + gmpChartMode: + type: string + nullable: true + eventCreators: + type: array + items: + $ref: '#/components/schemas/EventCreator' + tweetCount: + type: integer + nullable: true + chats: + type: array + items: + $ref: '#/components/schemas/Chat' + featuredOrder: + type: integer + nullable: true + estimateValue: + type: boolean + nullable: true + cantEstimate: + type: boolean + nullable: true + estimatedValue: + type: string + nullable: true + templates: + type: array + items: + $ref: '#/components/schemas/Template' + spreadsMainLine: + type: number + nullable: true + totalsMainLine: + type: number + nullable: true + carouselMap: + type: string + nullable: true + pendingDeployment: + type: boolean + nullable: true + deploying: + type: boolean + nullable: true + deployingTimestamp: + type: string + format: date-time + nullable: true + scheduledDeploymentTimestamp: + type: string + format: date-time + nullable: true + gameStatus: + type: string + nullable: true + Category: + type: object + properties: + id: + type: string + label: + type: string + nullable: true + parentCategory: + type: string + nullable: true + slug: + type: string + nullable: true + publishedAt: + type: string + nullable: true + createdBy: + type: string + nullable: true + updatedBy: + type: string + nullable: true + createdAt: + type: string + format: date-time + nullable: true + updatedAt: + type: string + format: date-time + nullable: true + Tag: + type: object + properties: + id: + type: string + label: + type: string + nullable: true + slug: + type: string + nullable: true + forceShow: + type: boolean + nullable: true + publishedAt: + type: string + nullable: true + createdBy: + type: integer + nullable: true + updatedBy: + type: integer + nullable: true + createdAt: + type: string + format: date-time + nullable: true + updatedAt: + type: string + format: date-time + nullable: true + forceHide: + type: boolean + nullable: true + isCarousel: + type: boolean + nullable: true + FeeSchedule: + type: object + properties: + exponent: + type: number + nullable: true + rate: + type: number + nullable: true + takerOnly: + type: boolean + nullable: true + rebateRate: + type: number + nullable: true + Series: + type: object + properties: + id: + type: string + ticker: + type: string + nullable: true + slug: + type: string + nullable: true + title: + type: string + nullable: true + subtitle: + type: string + nullable: true + seriesType: + type: string + nullable: true + recurrence: + type: string + nullable: true + description: + type: string + nullable: true + image: + type: string + nullable: true + icon: + type: string + nullable: true + layout: + type: string + nullable: true + active: + type: boolean + nullable: true + closed: + type: boolean + nullable: true + archived: + type: boolean + nullable: true + new: + type: boolean + nullable: true + featured: + type: boolean + nullable: true + restricted: + type: boolean + nullable: true + isTemplate: + type: boolean + nullable: true + templateVariables: + type: boolean + nullable: true + publishedAt: + type: string + nullable: true + createdBy: + type: string + nullable: true + updatedBy: + type: string + nullable: true + createdAt: + type: string + format: date-time + nullable: true + updatedAt: + type: string + format: date-time + nullable: true + commentsEnabled: + type: boolean + nullable: true + competitive: + type: string + nullable: true + volume24hr: + type: number + nullable: true + volume: + type: number + nullable: true + liquidity: + type: number + nullable: true + startDate: + type: string + format: date-time + nullable: true + pythTokenID: + type: string + nullable: true + cgAssetName: + type: string + nullable: true + score: + type: integer + nullable: true + events: + type: array + items: + $ref: '#/components/schemas/Event' + collections: + type: array + items: + $ref: '#/components/schemas/Collection' + categories: + type: array + items: + $ref: '#/components/schemas/Category' + tags: + type: array + items: + $ref: '#/components/schemas/Tag' + commentCount: + type: integer + nullable: true + chats: + type: array + items: + $ref: '#/components/schemas/Chat' + Collection: + type: object + properties: + id: + type: string + ticker: + type: string + nullable: true + slug: + type: string + nullable: true + title: + type: string + nullable: true + subtitle: + type: string + nullable: true + collectionType: + type: string + nullable: true + description: + type: string + nullable: true + tags: + type: string + nullable: true + image: + type: string + nullable: true + icon: + type: string + nullable: true + headerImage: + type: string + nullable: true + layout: + type: string + nullable: true + active: + type: boolean + nullable: true + closed: + type: boolean + nullable: true + archived: + type: boolean + nullable: true + new: + type: boolean + nullable: true + featured: + type: boolean + nullable: true + restricted: + type: boolean + nullable: true + isTemplate: + type: boolean + nullable: true + templateVariables: + type: string + nullable: true + publishedAt: + type: string + nullable: true + createdBy: + type: string + nullable: true + updatedBy: + type: string + nullable: true + createdAt: + type: string + format: date-time + nullable: true + updatedAt: + type: string + format: date-time + nullable: true + commentsEnabled: + type: boolean + nullable: true + imageOptimized: + $ref: '#/components/schemas/ImageOptimization' + iconOptimized: + $ref: '#/components/schemas/ImageOptimization' + headerImageOptimized: + $ref: '#/components/schemas/ImageOptimization' + EventCreator: + type: object + properties: + id: + type: string + creatorName: + type: string + nullable: true + creatorHandle: + type: string + nullable: true + creatorUrl: + type: string + nullable: true + creatorImage: + type: string + nullable: true + createdAt: + type: string + format: date-time + nullable: true + updatedAt: + type: string + format: date-time + nullable: true + Chat: + type: object + properties: + id: + type: string + channelId: + type: string + nullable: true + channelName: + type: string + nullable: true + channelImage: + type: string + nullable: true + live: + type: boolean + nullable: true + startTime: + type: string + format: date-time + nullable: true + endTime: + type: string + format: date-time + nullable: true + Template: + type: object + properties: + id: + type: string + eventTitle: + type: string + nullable: true + eventSlug: + type: string + nullable: true + eventImage: + type: string + nullable: true + marketTitle: + type: string + nullable: true + description: + type: string + nullable: true + resolutionSource: + type: string + nullable: true + negRisk: + type: boolean + nullable: true + sortBy: + type: string + nullable: true + showMarketImages: + type: boolean + nullable: true + seriesSlug: + type: string + nullable: true + outcomes: + type: string + nullable: true + +```` \ No newline at end of file diff --git a/PolymarketDocumentation-main/docs/api-reference/markets/get-market-by-slug.md b/PolymarketDocumentation-main/docs/api-reference/markets/get-market-by-slug.md new file mode 100644 index 00000000..538515f7 --- /dev/null +++ b/PolymarketDocumentation-main/docs/api-reference/markets/get-market-by-slug.md @@ -0,0 +1,1209 @@ +> ## Documentation Index +> Fetch the complete documentation index at: https://docs.polymarket.com/llms.txt +> Use this file to discover all available pages before exploring further. + +# Get market by slug + + + +## OpenAPI + +````yaml /api-spec/gamma-openapi.yaml get /markets/slug/{slug} +openapi: 3.0.3 +info: + title: Markets API + version: 1.0.0 + description: REST API specification for public endpoints used by the Markets service. +servers: + - url: https://gamma-api.polymarket.com + description: Polymarket Gamma API Production Server +security: [] +tags: + - name: Gamma Status + description: Gamma API status and health check + - name: Sports + description: Sports-related endpoints including teams and game data + - name: Tags + description: Tag management and related tag operations + - name: Events + description: Event management and event-related operations + - name: Markets + description: Market data and market-related operations + - name: Comments + description: Comment system and user interactions + - name: Series + description: Series management and related operations + - name: Profiles + description: User profile management + - name: Search + description: Search functionality across different entity types +paths: + /markets/slug/{slug}: + get: + tags: + - Markets + summary: Get market by slug + operationId: getMarketBySlug + parameters: + - $ref: '#/components/parameters/pathSlug' + - name: include_tag + in: query + schema: + type: boolean + responses: + '200': + description: Market + content: + application/json: + schema: + $ref: '#/components/schemas/Market' + '404': + description: Not found +components: + parameters: + pathSlug: + name: slug + in: path + required: true + schema: + type: string + schemas: + Market: + type: object + properties: + id: + type: string + question: + type: string + nullable: true + conditionId: + type: string + slug: + type: string + nullable: true + twitterCardImage: + type: string + nullable: true + resolutionSource: + type: string + nullable: true + endDate: + type: string + format: date-time + nullable: true + category: + type: string + nullable: true + ammType: + type: string + nullable: true + liquidity: + type: string + nullable: true + sponsorName: + type: string + nullable: true + sponsorImage: + type: string + nullable: true + startDate: + type: string + format: date-time + nullable: true + xAxisValue: + type: string + nullable: true + yAxisValue: + type: string + nullable: true + denominationToken: + type: string + nullable: true + fee: + type: string + nullable: true + image: + type: string + nullable: true + icon: + type: string + nullable: true + lowerBound: + type: string + nullable: true + upperBound: + type: string + nullable: true + description: + type: string + nullable: true + outcomes: + type: string + nullable: true + outcomePrices: + type: string + nullable: true + volume: + type: string + nullable: true + active: + type: boolean + nullable: true + marketType: + type: string + nullable: true + formatType: + type: string + nullable: true + lowerBoundDate: + type: string + nullable: true + upperBoundDate: + type: string + nullable: true + closed: + type: boolean + nullable: true + marketMakerAddress: + type: string + createdBy: + type: integer + nullable: true + updatedBy: + type: integer + nullable: true + createdAt: + type: string + format: date-time + nullable: true + updatedAt: + type: string + format: date-time + nullable: true + closedTime: + type: string + nullable: true + wideFormat: + type: boolean + nullable: true + new: + type: boolean + nullable: true + mailchimpTag: + type: string + nullable: true + featured: + type: boolean + nullable: true + archived: + type: boolean + nullable: true + resolvedBy: + type: string + nullable: true + restricted: + type: boolean + nullable: true + marketGroup: + type: integer + nullable: true + groupItemTitle: + type: string + nullable: true + groupItemThreshold: + type: string + nullable: true + questionID: + type: string + nullable: true + umaEndDate: + type: string + nullable: true + enableOrderBook: + type: boolean + nullable: true + orderPriceMinTickSize: + type: number + nullable: true + orderMinSize: + type: number + nullable: true + umaResolutionStatus: + type: string + nullable: true + curationOrder: + type: integer + nullable: true + volumeNum: + type: number + nullable: true + liquidityNum: + type: number + nullable: true + endDateIso: + type: string + nullable: true + startDateIso: + type: string + nullable: true + umaEndDateIso: + type: string + nullable: true + hasReviewedDates: + type: boolean + nullable: true + readyForCron: + type: boolean + nullable: true + commentsEnabled: + type: boolean + nullable: true + volume24hr: + type: number + nullable: true + volume1wk: + type: number + nullable: true + volume1mo: + type: number + nullable: true + volume1yr: + type: number + nullable: true + gameStartTime: + type: string + nullable: true + secondsDelay: + type: integer + nullable: true + clobTokenIds: + type: string + nullable: true + disqusThread: + type: string + nullable: true + shortOutcomes: + type: string + nullable: true + teamAID: + type: string + nullable: true + teamBID: + type: string + nullable: true + umaBond: + type: string + nullable: true + umaReward: + type: string + nullable: true + fpmmLive: + type: boolean + nullable: true + volume24hrAmm: + type: number + nullable: true + volume1wkAmm: + type: number + nullable: true + volume1moAmm: + type: number + nullable: true + volume1yrAmm: + type: number + nullable: true + volume24hrClob: + type: number + nullable: true + volume1wkClob: + type: number + nullable: true + volume1moClob: + type: number + nullable: true + volume1yrClob: + type: number + nullable: true + volumeAmm: + type: number + nullable: true + volumeClob: + type: number + nullable: true + liquidityAmm: + type: number + nullable: true + liquidityClob: + type: number + nullable: true + makerBaseFee: + type: integer + nullable: true + takerBaseFee: + type: integer + nullable: true + customLiveness: + type: integer + nullable: true + acceptingOrders: + type: boolean + nullable: true + notificationsEnabled: + type: boolean + nullable: true + score: + type: integer + nullable: true + imageOptimized: + $ref: '#/components/schemas/ImageOptimization' + iconOptimized: + $ref: '#/components/schemas/ImageOptimization' + events: + type: array + items: + $ref: '#/components/schemas/Event' + categories: + type: array + items: + $ref: '#/components/schemas/Category' + tags: + type: array + items: + $ref: '#/components/schemas/Tag' + creator: + type: string + nullable: true + ready: + type: boolean + nullable: true + funded: + type: boolean + nullable: true + pastSlugs: + type: string + nullable: true + readyTimestamp: + type: string + format: date-time + nullable: true + fundedTimestamp: + type: string + format: date-time + nullable: true + acceptingOrdersTimestamp: + type: string + format: date-time + nullable: true + competitive: + type: number + nullable: true + rewardsMinSize: + type: number + nullable: true + rewardsMaxSpread: + type: number + nullable: true + spread: + type: number + nullable: true + automaticallyResolved: + type: boolean + nullable: true + oneDayPriceChange: + type: number + nullable: true + oneHourPriceChange: + type: number + nullable: true + oneWeekPriceChange: + type: number + nullable: true + oneMonthPriceChange: + type: number + nullable: true + oneYearPriceChange: + type: number + nullable: true + lastTradePrice: + type: number + nullable: true + bestBid: + type: number + nullable: true + bestAsk: + type: number + nullable: true + automaticallyActive: + type: boolean + nullable: true + clearBookOnStart: + type: boolean + nullable: true + chartColor: + type: string + nullable: true + seriesColor: + type: string + nullable: true + showGmpSeries: + type: boolean + nullable: true + showGmpOutcome: + type: boolean + nullable: true + manualActivation: + type: boolean + nullable: true + negRiskOther: + type: boolean + nullable: true + gameId: + type: string + nullable: true + groupItemRange: + type: string + nullable: true + sportsMarketType: + type: string + nullable: true + line: + type: number + nullable: true + umaResolutionStatuses: + type: string + nullable: true + pendingDeployment: + type: boolean + nullable: true + deploying: + type: boolean + nullable: true + deployingTimestamp: + type: string + format: date-time + nullable: true + scheduledDeploymentTimestamp: + type: string + format: date-time + nullable: true + rfqEnabled: + type: boolean + nullable: true + eventStartTime: + type: string + format: date-time + nullable: true + feesEnabled: + type: boolean + nullable: true + feeSchedule: + $ref: '#/components/schemas/FeeSchedule' + ImageOptimization: + type: object + properties: + id: + type: string + imageUrlSource: + type: string + nullable: true + imageUrlOptimized: + type: string + nullable: true + imageSizeKbSource: + type: number + nullable: true + imageSizeKbOptimized: + type: number + nullable: true + imageOptimizedComplete: + type: boolean + nullable: true + imageOptimizedLastUpdated: + type: string + nullable: true + relID: + type: integer + nullable: true + field: + type: string + nullable: true + relname: + type: string + nullable: true + Event: + type: object + properties: + id: + type: string + ticker: + type: string + nullable: true + slug: + type: string + nullable: true + title: + type: string + nullable: true + subtitle: + type: string + nullable: true + description: + type: string + nullable: true + resolutionSource: + type: string + nullable: true + startDate: + type: string + format: date-time + nullable: true + creationDate: + type: string + format: date-time + nullable: true + endDate: + type: string + format: date-time + nullable: true + image: + type: string + nullable: true + icon: + type: string + nullable: true + active: + type: boolean + nullable: true + closed: + type: boolean + nullable: true + archived: + type: boolean + nullable: true + new: + type: boolean + nullable: true + featured: + type: boolean + nullable: true + restricted: + type: boolean + nullable: true + liquidity: + type: number + nullable: true + volume: + type: number + nullable: true + openInterest: + type: number + nullable: true + sortBy: + type: string + nullable: true + category: + type: string + nullable: true + subcategory: + type: string + nullable: true + isTemplate: + type: boolean + nullable: true + templateVariables: + type: string + nullable: true + published_at: + type: string + nullable: true + createdBy: + type: string + nullable: true + updatedBy: + type: string + nullable: true + createdAt: + type: string + format: date-time + nullable: true + updatedAt: + type: string + format: date-time + nullable: true + commentsEnabled: + type: boolean + nullable: true + competitive: + type: number + nullable: true + volume24hr: + type: number + nullable: true + volume1wk: + type: number + nullable: true + volume1mo: + type: number + nullable: true + volume1yr: + type: number + nullable: true + featuredImage: + type: string + nullable: true + disqusThread: + type: string + nullable: true + parentEvent: + type: string + nullable: true + enableOrderBook: + type: boolean + nullable: true + liquidityAmm: + type: number + nullable: true + liquidityClob: + type: number + nullable: true + negRisk: + type: boolean + nullable: true + negRiskMarketID: + type: string + nullable: true + negRiskFeeBips: + type: integer + nullable: true + commentCount: + type: integer + nullable: true + imageOptimized: + $ref: '#/components/schemas/ImageOptimization' + iconOptimized: + $ref: '#/components/schemas/ImageOptimization' + featuredImageOptimized: + $ref: '#/components/schemas/ImageOptimization' + subEvents: + type: array + items: + type: string + nullable: true + markets: + type: array + items: + $ref: '#/components/schemas/Market' + series: + type: array + items: + $ref: '#/components/schemas/Series' + categories: + type: array + items: + $ref: '#/components/schemas/Category' + collections: + type: array + items: + $ref: '#/components/schemas/Collection' + tags: + type: array + items: + $ref: '#/components/schemas/Tag' + cyom: + type: boolean + nullable: true + closedTime: + type: string + format: date-time + nullable: true + showAllOutcomes: + type: boolean + nullable: true + showMarketImages: + type: boolean + nullable: true + automaticallyResolved: + type: boolean + nullable: true + enableNegRisk: + type: boolean + nullable: true + automaticallyActive: + type: boolean + nullable: true + eventDate: + type: string + nullable: true + startTime: + type: string + format: date-time + nullable: true + eventWeek: + type: integer + nullable: true + seriesSlug: + type: string + nullable: true + score: + type: string + nullable: true + elapsed: + type: string + nullable: true + period: + type: string + nullable: true + live: + type: boolean + nullable: true + ended: + type: boolean + nullable: true + finishedTimestamp: + type: string + format: date-time + nullable: true + gmpChartMode: + type: string + nullable: true + eventCreators: + type: array + items: + $ref: '#/components/schemas/EventCreator' + tweetCount: + type: integer + nullable: true + chats: + type: array + items: + $ref: '#/components/schemas/Chat' + featuredOrder: + type: integer + nullable: true + estimateValue: + type: boolean + nullable: true + cantEstimate: + type: boolean + nullable: true + estimatedValue: + type: string + nullable: true + templates: + type: array + items: + $ref: '#/components/schemas/Template' + spreadsMainLine: + type: number + nullable: true + totalsMainLine: + type: number + nullable: true + carouselMap: + type: string + nullable: true + pendingDeployment: + type: boolean + nullable: true + deploying: + type: boolean + nullable: true + deployingTimestamp: + type: string + format: date-time + nullable: true + scheduledDeploymentTimestamp: + type: string + format: date-time + nullable: true + gameStatus: + type: string + nullable: true + Category: + type: object + properties: + id: + type: string + label: + type: string + nullable: true + parentCategory: + type: string + nullable: true + slug: + type: string + nullable: true + publishedAt: + type: string + nullable: true + createdBy: + type: string + nullable: true + updatedBy: + type: string + nullable: true + createdAt: + type: string + format: date-time + nullable: true + updatedAt: + type: string + format: date-time + nullable: true + Tag: + type: object + properties: + id: + type: string + label: + type: string + nullable: true + slug: + type: string + nullable: true + forceShow: + type: boolean + nullable: true + publishedAt: + type: string + nullable: true + createdBy: + type: integer + nullable: true + updatedBy: + type: integer + nullable: true + createdAt: + type: string + format: date-time + nullable: true + updatedAt: + type: string + format: date-time + nullable: true + forceHide: + type: boolean + nullable: true + isCarousel: + type: boolean + nullable: true + FeeSchedule: + type: object + properties: + exponent: + type: number + nullable: true + rate: + type: number + nullable: true + takerOnly: + type: boolean + nullable: true + rebateRate: + type: number + nullable: true + Series: + type: object + properties: + id: + type: string + ticker: + type: string + nullable: true + slug: + type: string + nullable: true + title: + type: string + nullable: true + subtitle: + type: string + nullable: true + seriesType: + type: string + nullable: true + recurrence: + type: string + nullable: true + description: + type: string + nullable: true + image: + type: string + nullable: true + icon: + type: string + nullable: true + layout: + type: string + nullable: true + active: + type: boolean + nullable: true + closed: + type: boolean + nullable: true + archived: + type: boolean + nullable: true + new: + type: boolean + nullable: true + featured: + type: boolean + nullable: true + restricted: + type: boolean + nullable: true + isTemplate: + type: boolean + nullable: true + templateVariables: + type: boolean + nullable: true + publishedAt: + type: string + nullable: true + createdBy: + type: string + nullable: true + updatedBy: + type: string + nullable: true + createdAt: + type: string + format: date-time + nullable: true + updatedAt: + type: string + format: date-time + nullable: true + commentsEnabled: + type: boolean + nullable: true + competitive: + type: string + nullable: true + volume24hr: + type: number + nullable: true + volume: + type: number + nullable: true + liquidity: + type: number + nullable: true + startDate: + type: string + format: date-time + nullable: true + pythTokenID: + type: string + nullable: true + cgAssetName: + type: string + nullable: true + score: + type: integer + nullable: true + events: + type: array + items: + $ref: '#/components/schemas/Event' + collections: + type: array + items: + $ref: '#/components/schemas/Collection' + categories: + type: array + items: + $ref: '#/components/schemas/Category' + tags: + type: array + items: + $ref: '#/components/schemas/Tag' + commentCount: + type: integer + nullable: true + chats: + type: array + items: + $ref: '#/components/schemas/Chat' + Collection: + type: object + properties: + id: + type: string + ticker: + type: string + nullable: true + slug: + type: string + nullable: true + title: + type: string + nullable: true + subtitle: + type: string + nullable: true + collectionType: + type: string + nullable: true + description: + type: string + nullable: true + tags: + type: string + nullable: true + image: + type: string + nullable: true + icon: + type: string + nullable: true + headerImage: + type: string + nullable: true + layout: + type: string + nullable: true + active: + type: boolean + nullable: true + closed: + type: boolean + nullable: true + archived: + type: boolean + nullable: true + new: + type: boolean + nullable: true + featured: + type: boolean + nullable: true + restricted: + type: boolean + nullable: true + isTemplate: + type: boolean + nullable: true + templateVariables: + type: string + nullable: true + publishedAt: + type: string + nullable: true + createdBy: + type: string + nullable: true + updatedBy: + type: string + nullable: true + createdAt: + type: string + format: date-time + nullable: true + updatedAt: + type: string + format: date-time + nullable: true + commentsEnabled: + type: boolean + nullable: true + imageOptimized: + $ref: '#/components/schemas/ImageOptimization' + iconOptimized: + $ref: '#/components/schemas/ImageOptimization' + headerImageOptimized: + $ref: '#/components/schemas/ImageOptimization' + EventCreator: + type: object + properties: + id: + type: string + creatorName: + type: string + nullable: true + creatorHandle: + type: string + nullable: true + creatorUrl: + type: string + nullable: true + creatorImage: + type: string + nullable: true + createdAt: + type: string + format: date-time + nullable: true + updatedAt: + type: string + format: date-time + nullable: true + Chat: + type: object + properties: + id: + type: string + channelId: + type: string + nullable: true + channelName: + type: string + nullable: true + channelImage: + type: string + nullable: true + live: + type: boolean + nullable: true + startTime: + type: string + format: date-time + nullable: true + endTime: + type: string + format: date-time + nullable: true + Template: + type: object + properties: + id: + type: string + eventTitle: + type: string + nullable: true + eventSlug: + type: string + nullable: true + eventImage: + type: string + nullable: true + marketTitle: + type: string + nullable: true + description: + type: string + nullable: true + resolutionSource: + type: string + nullable: true + negRisk: + type: boolean + nullable: true + sortBy: + type: string + nullable: true + showMarketImages: + type: boolean + nullable: true + seriesSlug: + type: string + nullable: true + outcomes: + type: string + nullable: true + +```` \ No newline at end of file diff --git a/PolymarketDocumentation-main/docs/api-reference/markets/get-market-by-token.md b/PolymarketDocumentation-main/docs/api-reference/markets/get-market-by-token.md new file mode 100644 index 00000000..34358832 --- /dev/null +++ b/PolymarketDocumentation-main/docs/api-reference/markets/get-market-by-token.md @@ -0,0 +1,128 @@ +> ## Documentation Index +> Fetch the complete documentation index at: https://docs.polymarket.com/llms.txt +> Use this file to discover all available pages before exploring further. + +# Get market by token + +> Returns the parent market for a given token ID. Useful when you have +a token ID and need to resolve its parent market without knowing the +condition ID in advance. + + + + +## OpenAPI + +````yaml /api-spec/clob-openapi.yaml get /markets-by-token/{token_id} +openapi: 3.1.0 +info: + title: Polymarket CLOB API + description: Polymarket CLOB API Reference + license: + name: MIT + identifier: MIT + version: 1.0.0 +servers: + - url: https://clob.polymarket.com + description: Production CLOB API + - url: https://clob-staging.polymarket.com + description: Staging CLOB API +security: [] +tags: + - name: Trade + description: Trade endpoints + - name: Markets + description: Market data endpoints + - name: Account + description: Account and authentication endpoints + - name: Notifications + description: User notification endpoints + - name: Rewards + description: Rewards and earnings endpoints + - name: Rebates + description: Maker rebate endpoints +paths: + /markets-by-token/{token_id}: + get: + tags: + - Markets + summary: Get market by token + description: | + Returns the parent market for a given token ID. Useful when you have + a token ID and need to resolve its parent market without knowing the + condition ID in advance. + operationId: getMarketByToken + parameters: + - name: token_id + in: path + required: true + description: The token ID to look up the parent market for + schema: + type: string + responses: + '200': + description: Successfully retrieved market + content: + application/json: + schema: + $ref: '#/components/schemas/MarketByTokenResponse' + '400': + description: Invalid market - empty token_id + content: + application/json: + schema: + $ref: '#/components/schemas/ErrorResponse' + '404': + description: Market not found for token + content: + application/json: + schema: + $ref: '#/components/schemas/ErrorResponse' + '500': + description: Internal server error + content: + application/json: + schema: + $ref: '#/components/schemas/ErrorResponse' +components: + schemas: + MarketByTokenResponse: + type: object + description: >- + Response for GET /markets-by-token/{token_id} — condition ID and both + token IDs in the market. + required: + - condition_id + - primary_token_id + - secondary_token_id + properties: + condition_id: + type: string + description: The condition ID of the market containing the given token + example: '0xbd31dc8a20211944f6b70f31557f1001557b59905b7738480ca09bd4532f84af' + primary_token_id: + type: string + description: The primary (Yes) token ID + example: >- + 71321045679252212594626385532706912750332728571942532289631379312455583992563 + secondary_token_id: + type: string + description: The secondary (No) token ID + example: >- + 52114319501245915516055106046884209969926127482827954674443846427813813222426 + ErrorResponse: + type: object + required: + - error + properties: + error: + type: string + description: Error message + code: + type: string + description: Machine-readable error code, when provided + retry_after_seconds: + type: integer + description: Number of seconds to wait before retrying, when provided + +```` \ No newline at end of file diff --git a/PolymarketDocumentation-main/docs/api-reference/markets/get-market-tags-by-id.md b/PolymarketDocumentation-main/docs/api-reference/markets/get-market-tags-by-id.md new file mode 100644 index 00000000..2b554881 --- /dev/null +++ b/PolymarketDocumentation-main/docs/api-reference/markets/get-market-tags-by-id.md @@ -0,0 +1,108 @@ +> ## Documentation Index +> Fetch the complete documentation index at: https://docs.polymarket.com/llms.txt +> Use this file to discover all available pages before exploring further. + +# Get market tags by id + + + +## OpenAPI + +````yaml /api-spec/gamma-openapi.yaml get /markets/{id}/tags +openapi: 3.0.3 +info: + title: Markets API + version: 1.0.0 + description: REST API specification for public endpoints used by the Markets service. +servers: + - url: https://gamma-api.polymarket.com + description: Polymarket Gamma API Production Server +security: [] +tags: + - name: Gamma Status + description: Gamma API status and health check + - name: Sports + description: Sports-related endpoints including teams and game data + - name: Tags + description: Tag management and related tag operations + - name: Events + description: Event management and event-related operations + - name: Markets + description: Market data and market-related operations + - name: Comments + description: Comment system and user interactions + - name: Series + description: Series management and related operations + - name: Profiles + description: User profile management + - name: Search + description: Search functionality across different entity types +paths: + /markets/{id}/tags: + get: + tags: + - Markets + - Tags + summary: Get market tags by id + operationId: getMarketTags + parameters: + - $ref: '#/components/parameters/pathId' + responses: + '200': + description: Tags attached to the market + content: + application/json: + schema: + type: array + items: + $ref: '#/components/schemas/Tag' + '404': + description: Not found +components: + parameters: + pathId: + name: id + in: path + required: true + schema: + type: integer + schemas: + Tag: + type: object + properties: + id: + type: string + label: + type: string + nullable: true + slug: + type: string + nullable: true + forceShow: + type: boolean + nullable: true + publishedAt: + type: string + nullable: true + createdBy: + type: integer + nullable: true + updatedBy: + type: integer + nullable: true + createdAt: + type: string + format: date-time + nullable: true + updatedAt: + type: string + format: date-time + nullable: true + forceHide: + type: boolean + nullable: true + isCarousel: + type: boolean + nullable: true + +```` \ No newline at end of file diff --git a/PolymarketDocumentation-main/docs/api-reference/markets/get-prices-history.md b/PolymarketDocumentation-main/docs/api-reference/markets/get-prices-history.md new file mode 100644 index 00000000..d49f48b7 --- /dev/null +++ b/PolymarketDocumentation-main/docs/api-reference/markets/get-prices-history.md @@ -0,0 +1,143 @@ +> ## Documentation Index +> Fetch the complete documentation index at: https://docs.polymarket.com/llms.txt +> Use this file to discover all available pages before exploring further. + +# Get prices history + +> Retrieve historical price data for a market. + + + +## OpenAPI + +````yaml /api-spec/clob-openapi.yaml get /prices-history +openapi: 3.1.0 +info: + title: Polymarket CLOB API + description: Polymarket CLOB API Reference + license: + name: MIT + identifier: MIT + version: 1.0.0 +servers: + - url: https://clob.polymarket.com + description: Production CLOB API + - url: https://clob-staging.polymarket.com + description: Staging CLOB API +security: [] +tags: + - name: Trade + description: Trade endpoints + - name: Markets + description: Market data endpoints + - name: Account + description: Account and authentication endpoints + - name: Notifications + description: User notification endpoints + - name: Rewards + description: Rewards and earnings endpoints + - name: Rebates + description: Maker rebate endpoints +paths: + /prices-history: + get: + tags: + - Markets + summary: Get prices history + description: Retrieve historical price data for a market. + operationId: getPricesHistory + parameters: + - name: market + in: query + required: true + description: The market (asset id) to query. + schema: + type: string + - name: startTs + in: query + required: false + description: Filter by items after this unix timestamp. + schema: + type: number + format: double + - name: endTs + in: query + required: false + description: Filter by items before this unix timestamp. + schema: + type: number + format: double + - name: interval + in: query + required: false + description: Time interval for data aggregation. + schema: + type: string + enum: + - max + - all + - 1m + - 1w + - 1d + - 6h + - 1h + - name: fidelity + in: query + required: false + description: Accuracy of the data expressed in minutes. Default is 1 minute. + schema: + type: integer + responses: + '200': + description: Successful response with price history + content: + application/json: + schema: + $ref: '#/components/schemas/PricesHistoryResponse' + '400': + description: Bad Request - Missing or invalid query parameters + content: + application/json: + schema: + $ref: '#/components/schemas/ErrorResponse' + '500': + description: Internal server error + content: + application/json: + schema: + $ref: '#/components/schemas/ErrorResponse' + security: [] +components: + schemas: + PricesHistoryResponse: + type: object + properties: + history: + type: array + items: + $ref: '#/components/schemas/MarketPrice' + ErrorResponse: + type: object + required: + - error + properties: + error: + type: string + description: Error message + code: + type: string + description: Machine-readable error code, when provided + retry_after_seconds: + type: integer + description: Number of seconds to wait before retrying, when provided + MarketPrice: + type: object + properties: + t: + type: integer + format: uint32 + p: + type: number + format: float + +```` \ No newline at end of file diff --git a/PolymarketDocumentation-main/docs/api-reference/markets/get-sampling-markets.md b/PolymarketDocumentation-main/docs/api-reference/markets/get-sampling-markets.md new file mode 100644 index 00000000..4fc1372e --- /dev/null +++ b/PolymarketDocumentation-main/docs/api-reference/markets/get-sampling-markets.md @@ -0,0 +1,183 @@ +> ## Documentation Index +> Fetch the complete documentation index at: https://docs.polymarket.com/llms.txt +> Use this file to discover all available pages before exploring further. + +# Get sampling markets + + + +## OpenAPI + +````yaml /api-spec/clob-openapi.yaml get /sampling-markets +openapi: 3.1.0 +info: + title: Polymarket CLOB API + description: Polymarket CLOB API Reference + license: + name: MIT + identifier: MIT + version: 1.0.0 +servers: + - url: https://clob.polymarket.com + description: Production CLOB API + - url: https://clob-staging.polymarket.com + description: Staging CLOB API +security: [] +tags: + - name: Trade + description: Trade endpoints + - name: Markets + description: Market data endpoints + - name: Account + description: Account and authentication endpoints + - name: Notifications + description: User notification endpoints + - name: Rewards + description: Rewards and earnings endpoints + - name: Rebates + description: Maker rebate endpoints +paths: + /sampling-markets: + get: + tags: + - Markets + summary: Get sampling markets + operationId: getSamplingMarkets + parameters: + - name: next_cursor + in: query + required: false + schema: + type: string + responses: + '200': + description: Successful response + content: + application/json: + schema: + $ref: '#/components/schemas/PaginatedMarkets' + '400': + description: Invalid request + '500': + description: Internal server error + security: [] +components: + schemas: + PaginatedMarkets: + type: object + properties: + limit: + type: integer + next_cursor: + type: string + count: + type: integer + data: + type: array + items: + $ref: '#/components/schemas/Market' + Market: + type: object + properties: + enable_order_book: + type: boolean + active: + type: boolean + closed: + type: boolean + archived: + type: boolean + accepting_orders: + type: boolean + accepting_order_timestamp: + type: string + format: date-time + minimum_order_size: + type: number + format: double + minimum_tick_size: + type: number + format: double + condition_id: + type: string + question_id: + type: string + question: + type: string + description: + type: string + market_slug: + type: string + end_date_iso: + type: string + format: date-time + game_start_time: + type: string + format: date-time + seconds_delay: + type: integer + fpmm: + type: string + maker_base_fee: + type: integer + format: int64 + taker_base_fee: + type: integer + format: int64 + notifications_enabled: + type: boolean + neg_risk: + type: boolean + neg_risk_market_id: + type: string + neg_risk_request_id: + type: string + icon: + type: string + image: + type: string + rewards: + $ref: '#/components/schemas/Rewards' + is_50_50_outcome: + type: boolean + tokens: + type: array + items: + $ref: '#/components/schemas/Token' + tags: + type: array + items: + type: string + Rewards: + type: object + properties: + rates: + type: array + items: + type: object + properties: + asset_address: + type: string + rewards_daily_rate: + type: number + format: double + min_size: + type: number + format: double + max_spread: + type: number + format: double + Token: + type: object + properties: + token_id: + type: string + outcome: + type: string + price: + type: number + format: double + winner: + type: boolean + +```` \ No newline at end of file diff --git a/PolymarketDocumentation-main/docs/api-reference/markets/get-sampling-simplified-markets.md b/PolymarketDocumentation-main/docs/api-reference/markets/get-sampling-simplified-markets.md new file mode 100644 index 00000000..443d7f5a --- /dev/null +++ b/PolymarketDocumentation-main/docs/api-reference/markets/get-sampling-simplified-markets.md @@ -0,0 +1,130 @@ +> ## Documentation Index +> Fetch the complete documentation index at: https://docs.polymarket.com/llms.txt +> Use this file to discover all available pages before exploring further. + +# Get sampling simplified markets + + + +## OpenAPI + +````yaml /api-spec/clob-openapi.yaml get /sampling-simplified-markets +openapi: 3.1.0 +info: + title: Polymarket CLOB API + description: Polymarket CLOB API Reference + license: + name: MIT + identifier: MIT + version: 1.0.0 +servers: + - url: https://clob.polymarket.com + description: Production CLOB API + - url: https://clob-staging.polymarket.com + description: Staging CLOB API +security: [] +tags: + - name: Trade + description: Trade endpoints + - name: Markets + description: Market data endpoints + - name: Account + description: Account and authentication endpoints + - name: Notifications + description: User notification endpoints + - name: Rewards + description: Rewards and earnings endpoints + - name: Rebates + description: Maker rebate endpoints +paths: + /sampling-simplified-markets: + get: + tags: + - Markets + summary: Get sampling simplified markets + operationId: getSamplingSimplifiedMarkets + parameters: + - name: next_cursor + in: query + required: false + schema: + type: string + responses: + '200': + description: Successful response + content: + application/json: + schema: + $ref: '#/components/schemas/PaginatedSimplifiedMarkets' + '400': + description: Invalid request + '500': + description: Internal server error + security: [] +components: + schemas: + PaginatedSimplifiedMarkets: + type: object + properties: + limit: + type: integer + next_cursor: + type: string + count: + type: integer + data: + type: array + items: + $ref: '#/components/schemas/SimplifiedMarket' + SimplifiedMarket: + type: object + properties: + condition_id: + type: string + rewards: + $ref: '#/components/schemas/Rewards' + tokens: + type: array + items: + $ref: '#/components/schemas/Token' + active: + type: boolean + closed: + type: boolean + archived: + type: boolean + accepting_orders: + type: boolean + Rewards: + type: object + properties: + rates: + type: array + items: + type: object + properties: + asset_address: + type: string + rewards_daily_rate: + type: number + format: double + min_size: + type: number + format: double + max_spread: + type: number + format: double + Token: + type: object + properties: + token_id: + type: string + outcome: + type: string + price: + type: number + format: double + winner: + type: boolean + +```` \ No newline at end of file diff --git a/PolymarketDocumentation-main/docs/api-reference/markets/get-simplified-markets.md b/PolymarketDocumentation-main/docs/api-reference/markets/get-simplified-markets.md new file mode 100644 index 00000000..73410e96 --- /dev/null +++ b/PolymarketDocumentation-main/docs/api-reference/markets/get-simplified-markets.md @@ -0,0 +1,130 @@ +> ## Documentation Index +> Fetch the complete documentation index at: https://docs.polymarket.com/llms.txt +> Use this file to discover all available pages before exploring further. + +# Get simplified markets + + + +## OpenAPI + +````yaml /api-spec/clob-openapi.yaml get /simplified-markets +openapi: 3.1.0 +info: + title: Polymarket CLOB API + description: Polymarket CLOB API Reference + license: + name: MIT + identifier: MIT + version: 1.0.0 +servers: + - url: https://clob.polymarket.com + description: Production CLOB API + - url: https://clob-staging.polymarket.com + description: Staging CLOB API +security: [] +tags: + - name: Trade + description: Trade endpoints + - name: Markets + description: Market data endpoints + - name: Account + description: Account and authentication endpoints + - name: Notifications + description: User notification endpoints + - name: Rewards + description: Rewards and earnings endpoints + - name: Rebates + description: Maker rebate endpoints +paths: + /simplified-markets: + get: + tags: + - Markets + summary: Get simplified markets + operationId: getSimplifiedMarkets + parameters: + - name: next_cursor + in: query + required: false + schema: + type: string + responses: + '200': + description: Successful response + content: + application/json: + schema: + $ref: '#/components/schemas/PaginatedSimplifiedMarkets' + '400': + description: Invalid request + '500': + description: Internal server error + security: [] +components: + schemas: + PaginatedSimplifiedMarkets: + type: object + properties: + limit: + type: integer + next_cursor: + type: string + count: + type: integer + data: + type: array + items: + $ref: '#/components/schemas/SimplifiedMarket' + SimplifiedMarket: + type: object + properties: + condition_id: + type: string + rewards: + $ref: '#/components/schemas/Rewards' + tokens: + type: array + items: + $ref: '#/components/schemas/Token' + active: + type: boolean + closed: + type: boolean + archived: + type: boolean + accepting_orders: + type: boolean + Rewards: + type: object + properties: + rates: + type: array + items: + type: object + properties: + asset_address: + type: string + rewards_daily_rate: + type: number + format: double + min_size: + type: number + format: double + max_spread: + type: number + format: double + Token: + type: object + properties: + token_id: + type: string + outcome: + type: string + price: + type: number + format: double + winner: + type: boolean + +```` \ No newline at end of file diff --git a/PolymarketDocumentation-main/docs/api-reference/markets/list-markets-keyset-pagination.md b/PolymarketDocumentation-main/docs/api-reference/markets/list-markets-keyset-pagination.md new file mode 100644 index 00000000..728b3208 --- /dev/null +++ b/PolymarketDocumentation-main/docs/api-reference/markets/list-markets-keyset-pagination.md @@ -0,0 +1,1425 @@ +> ## Documentation Index +> Fetch the complete documentation index at: https://docs.polymarket.com/llms.txt +> Use this file to discover all available pages before exploring further. + +# List markets (keyset pagination) + +> Returns markets using cursor-based (keyset) pagination for stable, efficient paging through large result sets. Use `next_cursor` from each response as `after_cursor` in the next request. The `offset` parameter is explicitly rejected; use `after_cursor` instead. + + + + +## OpenAPI + +````yaml /api-spec/gamma-openapi.yaml get /markets/keyset +openapi: 3.0.3 +info: + title: Markets API + version: 1.0.0 + description: REST API specification for public endpoints used by the Markets service. +servers: + - url: https://gamma-api.polymarket.com + description: Polymarket Gamma API Production Server +security: [] +tags: + - name: Gamma Status + description: Gamma API status and health check + - name: Sports + description: Sports-related endpoints including teams and game data + - name: Tags + description: Tag management and related tag operations + - name: Events + description: Event management and event-related operations + - name: Markets + description: Market data and market-related operations + - name: Comments + description: Comment system and user interactions + - name: Series + description: Series management and related operations + - name: Profiles + description: User profile management + - name: Search + description: Search functionality across different entity types +paths: + /markets/keyset: + get: + tags: + - Markets + summary: List markets (keyset pagination) + description: > + Returns markets using cursor-based (keyset) pagination for stable, + efficient paging through large result sets. Use `next_cursor` from each + response as `after_cursor` in the next request. The `offset` parameter + is explicitly rejected; use `after_cursor` instead. + operationId: listMarketsKeyset + parameters: + - name: limit + in: query + description: Maximum number of results to return (max 100) + schema: + type: integer + minimum: 1 + maximum: 100 + default: 20 + - name: order + in: query + description: >- + Comma-separated list of JSON field names to order by, e.g. + volume_num,liquidity_num + schema: + type: string + - name: ascending + in: query + description: Sort direction. Only used when order is set. + schema: + type: boolean + default: true + - name: after_cursor + in: query + description: Opaque cursor token from a previous response's next_cursor + schema: + type: string + - name: offset + in: query + description: Not allowed. Returns 422 if provided. + schema: + type: integer + - name: id + in: query + schema: + type: array + items: + type: integer + - name: slug + in: query + schema: + type: array + items: + type: string + - name: closed + in: query + schema: + type: boolean + default: false + - name: decimalized + in: query + schema: + type: boolean + - name: clob_token_ids + in: query + schema: + type: array + items: + type: string + - name: condition_ids + in: query + schema: + type: array + items: + type: string + - name: question_ids + in: query + schema: + type: array + items: + type: string + - name: market_maker_address + in: query + schema: + type: array + items: + type: string + - name: liquidity_num_min + in: query + schema: + type: number + - name: liquidity_num_max + in: query + schema: + type: number + - name: volume_num_min + in: query + schema: + type: number + - name: volume_num_max + in: query + schema: + type: number + - name: start_date_min + in: query + schema: + type: string + format: date-time + - name: start_date_max + in: query + schema: + type: string + format: date-time + - name: end_date_min + in: query + schema: + type: string + format: date-time + - name: end_date_max + in: query + schema: + type: string + format: date-time + - name: tag_id + in: query + schema: + type: array + items: + type: integer + - name: related_tags + in: query + schema: + type: boolean + - name: tag_match + in: query + schema: + type: string + - name: cyom + in: query + schema: + type: boolean + - name: rfq_enabled + in: query + schema: + type: boolean + - name: uma_resolution_status + in: query + schema: + type: string + - name: game_id + in: query + schema: + type: string + - name: sports_market_types + in: query + schema: + type: array + items: + type: string + - name: include_tag + in: query + description: When true, includes Tags relation on each market + schema: + type: boolean + - name: locale + in: query + schema: + type: string + responses: + '200': + description: > + Paginated list of markets. Includes Events and Events.Series + relations. Tags included only when include_tag=true. Nested + clob_rewards and fee_schedule are populated on each market. + content: + application/json: + schema: + $ref: '#/components/schemas/KeysetMarketsResponse' + '422': + description: > + Validation error. Returned when offset is provided, cursor is + invalid, order fields are not valid, or other filter validation + fails. + content: + application/json: + schema: + $ref: '#/components/schemas/ValidationError' + '500': + description: Internal server error (DB failures, cursor encode failures) + content: + application/json: + schema: + $ref: '#/components/schemas/InternalError' + '503': + description: Service unavailable when keyset pagination is not configured + content: + application/json: + schema: + $ref: '#/components/schemas/ServiceUnavailableError' +components: + schemas: + KeysetMarketsResponse: + type: object + properties: + markets: + type: array + description: Array of Market objects. Empty array if none found. + items: + $ref: '#/components/schemas/Market' + next_cursor: + type: string + description: > + Opaque cursor token for fetching the next page. Present only when + the number of returned markets equals the effective limit. Omitted + on the last page. + ValidationError: + type: object + properties: + type: + type: string + example: validation error + error: + type: string + example: offset is not allowed on keyset endpoints + InternalError: + type: object + properties: + type: + type: string + example: internal error + error: + type: string + example: cannot get the information + ServiceUnavailableError: + type: object + properties: + type: + type: string + example: service unavailable + error: + type: string + example: keyset pagination is not configured + Market: + type: object + properties: + id: + type: string + question: + type: string + nullable: true + conditionId: + type: string + slug: + type: string + nullable: true + twitterCardImage: + type: string + nullable: true + resolutionSource: + type: string + nullable: true + endDate: + type: string + format: date-time + nullable: true + category: + type: string + nullable: true + ammType: + type: string + nullable: true + liquidity: + type: string + nullable: true + sponsorName: + type: string + nullable: true + sponsorImage: + type: string + nullable: true + startDate: + type: string + format: date-time + nullable: true + xAxisValue: + type: string + nullable: true + yAxisValue: + type: string + nullable: true + denominationToken: + type: string + nullable: true + fee: + type: string + nullable: true + image: + type: string + nullable: true + icon: + type: string + nullable: true + lowerBound: + type: string + nullable: true + upperBound: + type: string + nullable: true + description: + type: string + nullable: true + outcomes: + type: string + nullable: true + outcomePrices: + type: string + nullable: true + volume: + type: string + nullable: true + active: + type: boolean + nullable: true + marketType: + type: string + nullable: true + formatType: + type: string + nullable: true + lowerBoundDate: + type: string + nullable: true + upperBoundDate: + type: string + nullable: true + closed: + type: boolean + nullable: true + marketMakerAddress: + type: string + createdBy: + type: integer + nullable: true + updatedBy: + type: integer + nullable: true + createdAt: + type: string + format: date-time + nullable: true + updatedAt: + type: string + format: date-time + nullable: true + closedTime: + type: string + nullable: true + wideFormat: + type: boolean + nullable: true + new: + type: boolean + nullable: true + mailchimpTag: + type: string + nullable: true + featured: + type: boolean + nullable: true + archived: + type: boolean + nullable: true + resolvedBy: + type: string + nullable: true + restricted: + type: boolean + nullable: true + marketGroup: + type: integer + nullable: true + groupItemTitle: + type: string + nullable: true + groupItemThreshold: + type: string + nullable: true + questionID: + type: string + nullable: true + umaEndDate: + type: string + nullable: true + enableOrderBook: + type: boolean + nullable: true + orderPriceMinTickSize: + type: number + nullable: true + orderMinSize: + type: number + nullable: true + umaResolutionStatus: + type: string + nullable: true + curationOrder: + type: integer + nullable: true + volumeNum: + type: number + nullable: true + liquidityNum: + type: number + nullable: true + endDateIso: + type: string + nullable: true + startDateIso: + type: string + nullable: true + umaEndDateIso: + type: string + nullable: true + hasReviewedDates: + type: boolean + nullable: true + readyForCron: + type: boolean + nullable: true + commentsEnabled: + type: boolean + nullable: true + volume24hr: + type: number + nullable: true + volume1wk: + type: number + nullable: true + volume1mo: + type: number + nullable: true + volume1yr: + type: number + nullable: true + gameStartTime: + type: string + nullable: true + secondsDelay: + type: integer + nullable: true + clobTokenIds: + type: string + nullable: true + disqusThread: + type: string + nullable: true + shortOutcomes: + type: string + nullable: true + teamAID: + type: string + nullable: true + teamBID: + type: string + nullable: true + umaBond: + type: string + nullable: true + umaReward: + type: string + nullable: true + fpmmLive: + type: boolean + nullable: true + volume24hrAmm: + type: number + nullable: true + volume1wkAmm: + type: number + nullable: true + volume1moAmm: + type: number + nullable: true + volume1yrAmm: + type: number + nullable: true + volume24hrClob: + type: number + nullable: true + volume1wkClob: + type: number + nullable: true + volume1moClob: + type: number + nullable: true + volume1yrClob: + type: number + nullable: true + volumeAmm: + type: number + nullable: true + volumeClob: + type: number + nullable: true + liquidityAmm: + type: number + nullable: true + liquidityClob: + type: number + nullable: true + makerBaseFee: + type: integer + nullable: true + takerBaseFee: + type: integer + nullable: true + customLiveness: + type: integer + nullable: true + acceptingOrders: + type: boolean + nullable: true + notificationsEnabled: + type: boolean + nullable: true + score: + type: integer + nullable: true + imageOptimized: + $ref: '#/components/schemas/ImageOptimization' + iconOptimized: + $ref: '#/components/schemas/ImageOptimization' + events: + type: array + items: + $ref: '#/components/schemas/Event' + categories: + type: array + items: + $ref: '#/components/schemas/Category' + tags: + type: array + items: + $ref: '#/components/schemas/Tag' + creator: + type: string + nullable: true + ready: + type: boolean + nullable: true + funded: + type: boolean + nullable: true + pastSlugs: + type: string + nullable: true + readyTimestamp: + type: string + format: date-time + nullable: true + fundedTimestamp: + type: string + format: date-time + nullable: true + acceptingOrdersTimestamp: + type: string + format: date-time + nullable: true + competitive: + type: number + nullable: true + rewardsMinSize: + type: number + nullable: true + rewardsMaxSpread: + type: number + nullable: true + spread: + type: number + nullable: true + automaticallyResolved: + type: boolean + nullable: true + oneDayPriceChange: + type: number + nullable: true + oneHourPriceChange: + type: number + nullable: true + oneWeekPriceChange: + type: number + nullable: true + oneMonthPriceChange: + type: number + nullable: true + oneYearPriceChange: + type: number + nullable: true + lastTradePrice: + type: number + nullable: true + bestBid: + type: number + nullable: true + bestAsk: + type: number + nullable: true + automaticallyActive: + type: boolean + nullable: true + clearBookOnStart: + type: boolean + nullable: true + chartColor: + type: string + nullable: true + seriesColor: + type: string + nullable: true + showGmpSeries: + type: boolean + nullable: true + showGmpOutcome: + type: boolean + nullable: true + manualActivation: + type: boolean + nullable: true + negRiskOther: + type: boolean + nullable: true + gameId: + type: string + nullable: true + groupItemRange: + type: string + nullable: true + sportsMarketType: + type: string + nullable: true + line: + type: number + nullable: true + umaResolutionStatuses: + type: string + nullable: true + pendingDeployment: + type: boolean + nullable: true + deploying: + type: boolean + nullable: true + deployingTimestamp: + type: string + format: date-time + nullable: true + scheduledDeploymentTimestamp: + type: string + format: date-time + nullable: true + rfqEnabled: + type: boolean + nullable: true + eventStartTime: + type: string + format: date-time + nullable: true + feesEnabled: + type: boolean + nullable: true + feeSchedule: + $ref: '#/components/schemas/FeeSchedule' + ImageOptimization: + type: object + properties: + id: + type: string + imageUrlSource: + type: string + nullable: true + imageUrlOptimized: + type: string + nullable: true + imageSizeKbSource: + type: number + nullable: true + imageSizeKbOptimized: + type: number + nullable: true + imageOptimizedComplete: + type: boolean + nullable: true + imageOptimizedLastUpdated: + type: string + nullable: true + relID: + type: integer + nullable: true + field: + type: string + nullable: true + relname: + type: string + nullable: true + Event: + type: object + properties: + id: + type: string + ticker: + type: string + nullable: true + slug: + type: string + nullable: true + title: + type: string + nullable: true + subtitle: + type: string + nullable: true + description: + type: string + nullable: true + resolutionSource: + type: string + nullable: true + startDate: + type: string + format: date-time + nullable: true + creationDate: + type: string + format: date-time + nullable: true + endDate: + type: string + format: date-time + nullable: true + image: + type: string + nullable: true + icon: + type: string + nullable: true + active: + type: boolean + nullable: true + closed: + type: boolean + nullable: true + archived: + type: boolean + nullable: true + new: + type: boolean + nullable: true + featured: + type: boolean + nullable: true + restricted: + type: boolean + nullable: true + liquidity: + type: number + nullable: true + volume: + type: number + nullable: true + openInterest: + type: number + nullable: true + sortBy: + type: string + nullable: true + category: + type: string + nullable: true + subcategory: + type: string + nullable: true + isTemplate: + type: boolean + nullable: true + templateVariables: + type: string + nullable: true + published_at: + type: string + nullable: true + createdBy: + type: string + nullable: true + updatedBy: + type: string + nullable: true + createdAt: + type: string + format: date-time + nullable: true + updatedAt: + type: string + format: date-time + nullable: true + commentsEnabled: + type: boolean + nullable: true + competitive: + type: number + nullable: true + volume24hr: + type: number + nullable: true + volume1wk: + type: number + nullable: true + volume1mo: + type: number + nullable: true + volume1yr: + type: number + nullable: true + featuredImage: + type: string + nullable: true + disqusThread: + type: string + nullable: true + parentEvent: + type: string + nullable: true + enableOrderBook: + type: boolean + nullable: true + liquidityAmm: + type: number + nullable: true + liquidityClob: + type: number + nullable: true + negRisk: + type: boolean + nullable: true + negRiskMarketID: + type: string + nullable: true + negRiskFeeBips: + type: integer + nullable: true + commentCount: + type: integer + nullable: true + imageOptimized: + $ref: '#/components/schemas/ImageOptimization' + iconOptimized: + $ref: '#/components/schemas/ImageOptimization' + featuredImageOptimized: + $ref: '#/components/schemas/ImageOptimization' + subEvents: + type: array + items: + type: string + nullable: true + markets: + type: array + items: + $ref: '#/components/schemas/Market' + series: + type: array + items: + $ref: '#/components/schemas/Series' + categories: + type: array + items: + $ref: '#/components/schemas/Category' + collections: + type: array + items: + $ref: '#/components/schemas/Collection' + tags: + type: array + items: + $ref: '#/components/schemas/Tag' + cyom: + type: boolean + nullable: true + closedTime: + type: string + format: date-time + nullable: true + showAllOutcomes: + type: boolean + nullable: true + showMarketImages: + type: boolean + nullable: true + automaticallyResolved: + type: boolean + nullable: true + enableNegRisk: + type: boolean + nullable: true + automaticallyActive: + type: boolean + nullable: true + eventDate: + type: string + nullable: true + startTime: + type: string + format: date-time + nullable: true + eventWeek: + type: integer + nullable: true + seriesSlug: + type: string + nullable: true + score: + type: string + nullable: true + elapsed: + type: string + nullable: true + period: + type: string + nullable: true + live: + type: boolean + nullable: true + ended: + type: boolean + nullable: true + finishedTimestamp: + type: string + format: date-time + nullable: true + gmpChartMode: + type: string + nullable: true + eventCreators: + type: array + items: + $ref: '#/components/schemas/EventCreator' + tweetCount: + type: integer + nullable: true + chats: + type: array + items: + $ref: '#/components/schemas/Chat' + featuredOrder: + type: integer + nullable: true + estimateValue: + type: boolean + nullable: true + cantEstimate: + type: boolean + nullable: true + estimatedValue: + type: string + nullable: true + templates: + type: array + items: + $ref: '#/components/schemas/Template' + spreadsMainLine: + type: number + nullable: true + totalsMainLine: + type: number + nullable: true + carouselMap: + type: string + nullable: true + pendingDeployment: + type: boolean + nullable: true + deploying: + type: boolean + nullable: true + deployingTimestamp: + type: string + format: date-time + nullable: true + scheduledDeploymentTimestamp: + type: string + format: date-time + nullable: true + gameStatus: + type: string + nullable: true + Category: + type: object + properties: + id: + type: string + label: + type: string + nullable: true + parentCategory: + type: string + nullable: true + slug: + type: string + nullable: true + publishedAt: + type: string + nullable: true + createdBy: + type: string + nullable: true + updatedBy: + type: string + nullable: true + createdAt: + type: string + format: date-time + nullable: true + updatedAt: + type: string + format: date-time + nullable: true + Tag: + type: object + properties: + id: + type: string + label: + type: string + nullable: true + slug: + type: string + nullable: true + forceShow: + type: boolean + nullable: true + publishedAt: + type: string + nullable: true + createdBy: + type: integer + nullable: true + updatedBy: + type: integer + nullable: true + createdAt: + type: string + format: date-time + nullable: true + updatedAt: + type: string + format: date-time + nullable: true + forceHide: + type: boolean + nullable: true + isCarousel: + type: boolean + nullable: true + FeeSchedule: + type: object + properties: + exponent: + type: number + nullable: true + rate: + type: number + nullable: true + takerOnly: + type: boolean + nullable: true + rebateRate: + type: number + nullable: true + Series: + type: object + properties: + id: + type: string + ticker: + type: string + nullable: true + slug: + type: string + nullable: true + title: + type: string + nullable: true + subtitle: + type: string + nullable: true + seriesType: + type: string + nullable: true + recurrence: + type: string + nullable: true + description: + type: string + nullable: true + image: + type: string + nullable: true + icon: + type: string + nullable: true + layout: + type: string + nullable: true + active: + type: boolean + nullable: true + closed: + type: boolean + nullable: true + archived: + type: boolean + nullable: true + new: + type: boolean + nullable: true + featured: + type: boolean + nullable: true + restricted: + type: boolean + nullable: true + isTemplate: + type: boolean + nullable: true + templateVariables: + type: boolean + nullable: true + publishedAt: + type: string + nullable: true + createdBy: + type: string + nullable: true + updatedBy: + type: string + nullable: true + createdAt: + type: string + format: date-time + nullable: true + updatedAt: + type: string + format: date-time + nullable: true + commentsEnabled: + type: boolean + nullable: true + competitive: + type: string + nullable: true + volume24hr: + type: number + nullable: true + volume: + type: number + nullable: true + liquidity: + type: number + nullable: true + startDate: + type: string + format: date-time + nullable: true + pythTokenID: + type: string + nullable: true + cgAssetName: + type: string + nullable: true + score: + type: integer + nullable: true + events: + type: array + items: + $ref: '#/components/schemas/Event' + collections: + type: array + items: + $ref: '#/components/schemas/Collection' + categories: + type: array + items: + $ref: '#/components/schemas/Category' + tags: + type: array + items: + $ref: '#/components/schemas/Tag' + commentCount: + type: integer + nullable: true + chats: + type: array + items: + $ref: '#/components/schemas/Chat' + Collection: + type: object + properties: + id: + type: string + ticker: + type: string + nullable: true + slug: + type: string + nullable: true + title: + type: string + nullable: true + subtitle: + type: string + nullable: true + collectionType: + type: string + nullable: true + description: + type: string + nullable: true + tags: + type: string + nullable: true + image: + type: string + nullable: true + icon: + type: string + nullable: true + headerImage: + type: string + nullable: true + layout: + type: string + nullable: true + active: + type: boolean + nullable: true + closed: + type: boolean + nullable: true + archived: + type: boolean + nullable: true + new: + type: boolean + nullable: true + featured: + type: boolean + nullable: true + restricted: + type: boolean + nullable: true + isTemplate: + type: boolean + nullable: true + templateVariables: + type: string + nullable: true + publishedAt: + type: string + nullable: true + createdBy: + type: string + nullable: true + updatedBy: + type: string + nullable: true + createdAt: + type: string + format: date-time + nullable: true + updatedAt: + type: string + format: date-time + nullable: true + commentsEnabled: + type: boolean + nullable: true + imageOptimized: + $ref: '#/components/schemas/ImageOptimization' + iconOptimized: + $ref: '#/components/schemas/ImageOptimization' + headerImageOptimized: + $ref: '#/components/schemas/ImageOptimization' + EventCreator: + type: object + properties: + id: + type: string + creatorName: + type: string + nullable: true + creatorHandle: + type: string + nullable: true + creatorUrl: + type: string + nullable: true + creatorImage: + type: string + nullable: true + createdAt: + type: string + format: date-time + nullable: true + updatedAt: + type: string + format: date-time + nullable: true + Chat: + type: object + properties: + id: + type: string + channelId: + type: string + nullable: true + channelName: + type: string + nullable: true + channelImage: + type: string + nullable: true + live: + type: boolean + nullable: true + startTime: + type: string + format: date-time + nullable: true + endTime: + type: string + format: date-time + nullable: true + Template: + type: object + properties: + id: + type: string + eventTitle: + type: string + nullable: true + eventSlug: + type: string + nullable: true + eventImage: + type: string + nullable: true + marketTitle: + type: string + nullable: true + description: + type: string + nullable: true + resolutionSource: + type: string + nullable: true + negRisk: + type: boolean + nullable: true + sortBy: + type: string + nullable: true + showMarketImages: + type: boolean + nullable: true + seriesSlug: + type: string + nullable: true + outcomes: + type: string + nullable: true + +```` \ No newline at end of file diff --git a/PolymarketDocumentation-main/docs/api-reference/markets/list-markets.md b/PolymarketDocumentation-main/docs/api-reference/markets/list-markets.md new file mode 100644 index 00000000..cc7dd5cd --- /dev/null +++ b/PolymarketDocumentation-main/docs/api-reference/markets/list-markets.md @@ -0,0 +1,1336 @@ +> ## Documentation Index +> Fetch the complete documentation index at: https://docs.polymarket.com/llms.txt +> Use this file to discover all available pages before exploring further. + +# List markets + + + +## OpenAPI + +````yaml /api-spec/gamma-openapi.yaml get /markets +openapi: 3.0.3 +info: + title: Markets API + version: 1.0.0 + description: REST API specification for public endpoints used by the Markets service. +servers: + - url: https://gamma-api.polymarket.com + description: Polymarket Gamma API Production Server +security: [] +tags: + - name: Gamma Status + description: Gamma API status and health check + - name: Sports + description: Sports-related endpoints including teams and game data + - name: Tags + description: Tag management and related tag operations + - name: Events + description: Event management and event-related operations + - name: Markets + description: Market data and market-related operations + - name: Comments + description: Comment system and user interactions + - name: Series + description: Series management and related operations + - name: Profiles + description: User profile management + - name: Search + description: Search functionality across different entity types +paths: + /markets: + get: + tags: + - Markets + summary: List markets + operationId: listMarkets + parameters: + - $ref: '#/components/parameters/limit' + - $ref: '#/components/parameters/offset' + - $ref: '#/components/parameters/order' + - $ref: '#/components/parameters/ascending' + - name: id + in: query + schema: + type: array + items: + type: integer + - name: slug + in: query + schema: + type: array + items: + type: string + - name: clob_token_ids + in: query + schema: + type: array + items: + type: string + - name: condition_ids + in: query + schema: + type: array + items: + type: string + - name: market_maker_address + in: query + schema: + type: array + items: + type: string + - name: liquidity_num_min + in: query + schema: + type: number + - name: liquidity_num_max + in: query + schema: + type: number + - name: volume_num_min + in: query + schema: + type: number + - name: volume_num_max + in: query + schema: + type: number + - name: start_date_min + in: query + schema: + type: string + format: date-time + - name: start_date_max + in: query + schema: + type: string + format: date-time + - name: end_date_min + in: query + schema: + type: string + format: date-time + - name: end_date_max + in: query + schema: + type: string + format: date-time + - name: tag_id + in: query + schema: + type: integer + - name: related_tags + in: query + schema: + type: boolean + - name: cyom + in: query + schema: + type: boolean + - name: uma_resolution_status + in: query + schema: + type: string + - name: game_id + in: query + schema: + type: string + - name: sports_market_types + in: query + schema: + type: array + items: + type: string + - name: rewards_min_size + in: query + schema: + type: number + - name: question_ids + in: query + schema: + type: array + items: + type: string + - name: include_tag + in: query + schema: + type: boolean + - name: closed + in: query + schema: + type: boolean + default: false + responses: + '200': + description: List of markets + content: + application/json: + schema: + type: array + items: + $ref: '#/components/schemas/Market' +components: + parameters: + limit: + name: limit + in: query + schema: + type: integer + minimum: 0 + offset: + name: offset + in: query + schema: + type: integer + minimum: 0 + order: + name: order + in: query + schema: + type: string + description: Comma-separated list of fields to order by + ascending: + name: ascending + in: query + schema: + type: boolean + schemas: + Market: + type: object + properties: + id: + type: string + question: + type: string + nullable: true + conditionId: + type: string + slug: + type: string + nullable: true + twitterCardImage: + type: string + nullable: true + resolutionSource: + type: string + nullable: true + endDate: + type: string + format: date-time + nullable: true + category: + type: string + nullable: true + ammType: + type: string + nullable: true + liquidity: + type: string + nullable: true + sponsorName: + type: string + nullable: true + sponsorImage: + type: string + nullable: true + startDate: + type: string + format: date-time + nullable: true + xAxisValue: + type: string + nullable: true + yAxisValue: + type: string + nullable: true + denominationToken: + type: string + nullable: true + fee: + type: string + nullable: true + image: + type: string + nullable: true + icon: + type: string + nullable: true + lowerBound: + type: string + nullable: true + upperBound: + type: string + nullable: true + description: + type: string + nullable: true + outcomes: + type: string + nullable: true + outcomePrices: + type: string + nullable: true + volume: + type: string + nullable: true + active: + type: boolean + nullable: true + marketType: + type: string + nullable: true + formatType: + type: string + nullable: true + lowerBoundDate: + type: string + nullable: true + upperBoundDate: + type: string + nullable: true + closed: + type: boolean + nullable: true + marketMakerAddress: + type: string + createdBy: + type: integer + nullable: true + updatedBy: + type: integer + nullable: true + createdAt: + type: string + format: date-time + nullable: true + updatedAt: + type: string + format: date-time + nullable: true + closedTime: + type: string + nullable: true + wideFormat: + type: boolean + nullable: true + new: + type: boolean + nullable: true + mailchimpTag: + type: string + nullable: true + featured: + type: boolean + nullable: true + archived: + type: boolean + nullable: true + resolvedBy: + type: string + nullable: true + restricted: + type: boolean + nullable: true + marketGroup: + type: integer + nullable: true + groupItemTitle: + type: string + nullable: true + groupItemThreshold: + type: string + nullable: true + questionID: + type: string + nullable: true + umaEndDate: + type: string + nullable: true + enableOrderBook: + type: boolean + nullable: true + orderPriceMinTickSize: + type: number + nullable: true + orderMinSize: + type: number + nullable: true + umaResolutionStatus: + type: string + nullable: true + curationOrder: + type: integer + nullable: true + volumeNum: + type: number + nullable: true + liquidityNum: + type: number + nullable: true + endDateIso: + type: string + nullable: true + startDateIso: + type: string + nullable: true + umaEndDateIso: + type: string + nullable: true + hasReviewedDates: + type: boolean + nullable: true + readyForCron: + type: boolean + nullable: true + commentsEnabled: + type: boolean + nullable: true + volume24hr: + type: number + nullable: true + volume1wk: + type: number + nullable: true + volume1mo: + type: number + nullable: true + volume1yr: + type: number + nullable: true + gameStartTime: + type: string + nullable: true + secondsDelay: + type: integer + nullable: true + clobTokenIds: + type: string + nullable: true + disqusThread: + type: string + nullable: true + shortOutcomes: + type: string + nullable: true + teamAID: + type: string + nullable: true + teamBID: + type: string + nullable: true + umaBond: + type: string + nullable: true + umaReward: + type: string + nullable: true + fpmmLive: + type: boolean + nullable: true + volume24hrAmm: + type: number + nullable: true + volume1wkAmm: + type: number + nullable: true + volume1moAmm: + type: number + nullable: true + volume1yrAmm: + type: number + nullable: true + volume24hrClob: + type: number + nullable: true + volume1wkClob: + type: number + nullable: true + volume1moClob: + type: number + nullable: true + volume1yrClob: + type: number + nullable: true + volumeAmm: + type: number + nullable: true + volumeClob: + type: number + nullable: true + liquidityAmm: + type: number + nullable: true + liquidityClob: + type: number + nullable: true + makerBaseFee: + type: integer + nullable: true + takerBaseFee: + type: integer + nullable: true + customLiveness: + type: integer + nullable: true + acceptingOrders: + type: boolean + nullable: true + notificationsEnabled: + type: boolean + nullable: true + score: + type: integer + nullable: true + imageOptimized: + $ref: '#/components/schemas/ImageOptimization' + iconOptimized: + $ref: '#/components/schemas/ImageOptimization' + events: + type: array + items: + $ref: '#/components/schemas/Event' + categories: + type: array + items: + $ref: '#/components/schemas/Category' + tags: + type: array + items: + $ref: '#/components/schemas/Tag' + creator: + type: string + nullable: true + ready: + type: boolean + nullable: true + funded: + type: boolean + nullable: true + pastSlugs: + type: string + nullable: true + readyTimestamp: + type: string + format: date-time + nullable: true + fundedTimestamp: + type: string + format: date-time + nullable: true + acceptingOrdersTimestamp: + type: string + format: date-time + nullable: true + competitive: + type: number + nullable: true + rewardsMinSize: + type: number + nullable: true + rewardsMaxSpread: + type: number + nullable: true + spread: + type: number + nullable: true + automaticallyResolved: + type: boolean + nullable: true + oneDayPriceChange: + type: number + nullable: true + oneHourPriceChange: + type: number + nullable: true + oneWeekPriceChange: + type: number + nullable: true + oneMonthPriceChange: + type: number + nullable: true + oneYearPriceChange: + type: number + nullable: true + lastTradePrice: + type: number + nullable: true + bestBid: + type: number + nullable: true + bestAsk: + type: number + nullable: true + automaticallyActive: + type: boolean + nullable: true + clearBookOnStart: + type: boolean + nullable: true + chartColor: + type: string + nullable: true + seriesColor: + type: string + nullable: true + showGmpSeries: + type: boolean + nullable: true + showGmpOutcome: + type: boolean + nullable: true + manualActivation: + type: boolean + nullable: true + negRiskOther: + type: boolean + nullable: true + gameId: + type: string + nullable: true + groupItemRange: + type: string + nullable: true + sportsMarketType: + type: string + nullable: true + line: + type: number + nullable: true + umaResolutionStatuses: + type: string + nullable: true + pendingDeployment: + type: boolean + nullable: true + deploying: + type: boolean + nullable: true + deployingTimestamp: + type: string + format: date-time + nullable: true + scheduledDeploymentTimestamp: + type: string + format: date-time + nullable: true + rfqEnabled: + type: boolean + nullable: true + eventStartTime: + type: string + format: date-time + nullable: true + feesEnabled: + type: boolean + nullable: true + feeSchedule: + $ref: '#/components/schemas/FeeSchedule' + ImageOptimization: + type: object + properties: + id: + type: string + imageUrlSource: + type: string + nullable: true + imageUrlOptimized: + type: string + nullable: true + imageSizeKbSource: + type: number + nullable: true + imageSizeKbOptimized: + type: number + nullable: true + imageOptimizedComplete: + type: boolean + nullable: true + imageOptimizedLastUpdated: + type: string + nullable: true + relID: + type: integer + nullable: true + field: + type: string + nullable: true + relname: + type: string + nullable: true + Event: + type: object + properties: + id: + type: string + ticker: + type: string + nullable: true + slug: + type: string + nullable: true + title: + type: string + nullable: true + subtitle: + type: string + nullable: true + description: + type: string + nullable: true + resolutionSource: + type: string + nullable: true + startDate: + type: string + format: date-time + nullable: true + creationDate: + type: string + format: date-time + nullable: true + endDate: + type: string + format: date-time + nullable: true + image: + type: string + nullable: true + icon: + type: string + nullable: true + active: + type: boolean + nullable: true + closed: + type: boolean + nullable: true + archived: + type: boolean + nullable: true + new: + type: boolean + nullable: true + featured: + type: boolean + nullable: true + restricted: + type: boolean + nullable: true + liquidity: + type: number + nullable: true + volume: + type: number + nullable: true + openInterest: + type: number + nullable: true + sortBy: + type: string + nullable: true + category: + type: string + nullable: true + subcategory: + type: string + nullable: true + isTemplate: + type: boolean + nullable: true + templateVariables: + type: string + nullable: true + published_at: + type: string + nullable: true + createdBy: + type: string + nullable: true + updatedBy: + type: string + nullable: true + createdAt: + type: string + format: date-time + nullable: true + updatedAt: + type: string + format: date-time + nullable: true + commentsEnabled: + type: boolean + nullable: true + competitive: + type: number + nullable: true + volume24hr: + type: number + nullable: true + volume1wk: + type: number + nullable: true + volume1mo: + type: number + nullable: true + volume1yr: + type: number + nullable: true + featuredImage: + type: string + nullable: true + disqusThread: + type: string + nullable: true + parentEvent: + type: string + nullable: true + enableOrderBook: + type: boolean + nullable: true + liquidityAmm: + type: number + nullable: true + liquidityClob: + type: number + nullable: true + negRisk: + type: boolean + nullable: true + negRiskMarketID: + type: string + nullable: true + negRiskFeeBips: + type: integer + nullable: true + commentCount: + type: integer + nullable: true + imageOptimized: + $ref: '#/components/schemas/ImageOptimization' + iconOptimized: + $ref: '#/components/schemas/ImageOptimization' + featuredImageOptimized: + $ref: '#/components/schemas/ImageOptimization' + subEvents: + type: array + items: + type: string + nullable: true + markets: + type: array + items: + $ref: '#/components/schemas/Market' + series: + type: array + items: + $ref: '#/components/schemas/Series' + categories: + type: array + items: + $ref: '#/components/schemas/Category' + collections: + type: array + items: + $ref: '#/components/schemas/Collection' + tags: + type: array + items: + $ref: '#/components/schemas/Tag' + cyom: + type: boolean + nullable: true + closedTime: + type: string + format: date-time + nullable: true + showAllOutcomes: + type: boolean + nullable: true + showMarketImages: + type: boolean + nullable: true + automaticallyResolved: + type: boolean + nullable: true + enableNegRisk: + type: boolean + nullable: true + automaticallyActive: + type: boolean + nullable: true + eventDate: + type: string + nullable: true + startTime: + type: string + format: date-time + nullable: true + eventWeek: + type: integer + nullable: true + seriesSlug: + type: string + nullable: true + score: + type: string + nullable: true + elapsed: + type: string + nullable: true + period: + type: string + nullable: true + live: + type: boolean + nullable: true + ended: + type: boolean + nullable: true + finishedTimestamp: + type: string + format: date-time + nullable: true + gmpChartMode: + type: string + nullable: true + eventCreators: + type: array + items: + $ref: '#/components/schemas/EventCreator' + tweetCount: + type: integer + nullable: true + chats: + type: array + items: + $ref: '#/components/schemas/Chat' + featuredOrder: + type: integer + nullable: true + estimateValue: + type: boolean + nullable: true + cantEstimate: + type: boolean + nullable: true + estimatedValue: + type: string + nullable: true + templates: + type: array + items: + $ref: '#/components/schemas/Template' + spreadsMainLine: + type: number + nullable: true + totalsMainLine: + type: number + nullable: true + carouselMap: + type: string + nullable: true + pendingDeployment: + type: boolean + nullable: true + deploying: + type: boolean + nullable: true + deployingTimestamp: + type: string + format: date-time + nullable: true + scheduledDeploymentTimestamp: + type: string + format: date-time + nullable: true + gameStatus: + type: string + nullable: true + Category: + type: object + properties: + id: + type: string + label: + type: string + nullable: true + parentCategory: + type: string + nullable: true + slug: + type: string + nullable: true + publishedAt: + type: string + nullable: true + createdBy: + type: string + nullable: true + updatedBy: + type: string + nullable: true + createdAt: + type: string + format: date-time + nullable: true + updatedAt: + type: string + format: date-time + nullable: true + Tag: + type: object + properties: + id: + type: string + label: + type: string + nullable: true + slug: + type: string + nullable: true + forceShow: + type: boolean + nullable: true + publishedAt: + type: string + nullable: true + createdBy: + type: integer + nullable: true + updatedBy: + type: integer + nullable: true + createdAt: + type: string + format: date-time + nullable: true + updatedAt: + type: string + format: date-time + nullable: true + forceHide: + type: boolean + nullable: true + isCarousel: + type: boolean + nullable: true + FeeSchedule: + type: object + properties: + exponent: + type: number + nullable: true + rate: + type: number + nullable: true + takerOnly: + type: boolean + nullable: true + rebateRate: + type: number + nullable: true + Series: + type: object + properties: + id: + type: string + ticker: + type: string + nullable: true + slug: + type: string + nullable: true + title: + type: string + nullable: true + subtitle: + type: string + nullable: true + seriesType: + type: string + nullable: true + recurrence: + type: string + nullable: true + description: + type: string + nullable: true + image: + type: string + nullable: true + icon: + type: string + nullable: true + layout: + type: string + nullable: true + active: + type: boolean + nullable: true + closed: + type: boolean + nullable: true + archived: + type: boolean + nullable: true + new: + type: boolean + nullable: true + featured: + type: boolean + nullable: true + restricted: + type: boolean + nullable: true + isTemplate: + type: boolean + nullable: true + templateVariables: + type: boolean + nullable: true + publishedAt: + type: string + nullable: true + createdBy: + type: string + nullable: true + updatedBy: + type: string + nullable: true + createdAt: + type: string + format: date-time + nullable: true + updatedAt: + type: string + format: date-time + nullable: true + commentsEnabled: + type: boolean + nullable: true + competitive: + type: string + nullable: true + volume24hr: + type: number + nullable: true + volume: + type: number + nullable: true + liquidity: + type: number + nullable: true + startDate: + type: string + format: date-time + nullable: true + pythTokenID: + type: string + nullable: true + cgAssetName: + type: string + nullable: true + score: + type: integer + nullable: true + events: + type: array + items: + $ref: '#/components/schemas/Event' + collections: + type: array + items: + $ref: '#/components/schemas/Collection' + categories: + type: array + items: + $ref: '#/components/schemas/Category' + tags: + type: array + items: + $ref: '#/components/schemas/Tag' + commentCount: + type: integer + nullable: true + chats: + type: array + items: + $ref: '#/components/schemas/Chat' + Collection: + type: object + properties: + id: + type: string + ticker: + type: string + nullable: true + slug: + type: string + nullable: true + title: + type: string + nullable: true + subtitle: + type: string + nullable: true + collectionType: + type: string + nullable: true + description: + type: string + nullable: true + tags: + type: string + nullable: true + image: + type: string + nullable: true + icon: + type: string + nullable: true + headerImage: + type: string + nullable: true + layout: + type: string + nullable: true + active: + type: boolean + nullable: true + closed: + type: boolean + nullable: true + archived: + type: boolean + nullable: true + new: + type: boolean + nullable: true + featured: + type: boolean + nullable: true + restricted: + type: boolean + nullable: true + isTemplate: + type: boolean + nullable: true + templateVariables: + type: string + nullable: true + publishedAt: + type: string + nullable: true + createdBy: + type: string + nullable: true + updatedBy: + type: string + nullable: true + createdAt: + type: string + format: date-time + nullable: true + updatedAt: + type: string + format: date-time + nullable: true + commentsEnabled: + type: boolean + nullable: true + imageOptimized: + $ref: '#/components/schemas/ImageOptimization' + iconOptimized: + $ref: '#/components/schemas/ImageOptimization' + headerImageOptimized: + $ref: '#/components/schemas/ImageOptimization' + EventCreator: + type: object + properties: + id: + type: string + creatorName: + type: string + nullable: true + creatorHandle: + type: string + nullable: true + creatorUrl: + type: string + nullable: true + creatorImage: + type: string + nullable: true + createdAt: + type: string + format: date-time + nullable: true + updatedAt: + type: string + format: date-time + nullable: true + Chat: + type: object + properties: + id: + type: string + channelId: + type: string + nullable: true + channelName: + type: string + nullable: true + channelImage: + type: string + nullable: true + live: + type: boolean + nullable: true + startTime: + type: string + format: date-time + nullable: true + endTime: + type: string + format: date-time + nullable: true + Template: + type: object + properties: + id: + type: string + eventTitle: + type: string + nullable: true + eventSlug: + type: string + nullable: true + eventImage: + type: string + nullable: true + marketTitle: + type: string + nullable: true + description: + type: string + nullable: true + resolutionSource: + type: string + nullable: true + negRisk: + type: boolean + nullable: true + sortBy: + type: string + nullable: true + showMarketImages: + type: boolean + nullable: true + seriesSlug: + type: string + nullable: true + outcomes: + type: string + nullable: true + +```` \ No newline at end of file diff --git a/PolymarketDocumentation-main/docs/api-reference/misc/download-an-accounting-snapshot-zip-of-csvs.md b/PolymarketDocumentation-main/docs/api-reference/misc/download-an-accounting-snapshot-zip-of-csvs.md new file mode 100644 index 00000000..9fe592c3 --- /dev/null +++ b/PolymarketDocumentation-main/docs/api-reference/misc/download-an-accounting-snapshot-zip-of-csvs.md @@ -0,0 +1,77 @@ +> ## Documentation Index +> Fetch the complete documentation index at: https://docs.polymarket.com/llms.txt +> Use this file to discover all available pages before exploring further. + +# Download an accounting snapshot (ZIP of CSVs) + + + +## OpenAPI + +````yaml /api-spec/data-openapi.yaml get /v1/accounting/snapshot +openapi: 3.0.3 +info: + title: Polymarket Data API + version: 1.0.0 + description: > + HTTP API for Polymarket data. This specification documents all public + routes. +servers: + - url: https://data-api.polymarket.com + description: Relative server (same host) +security: [] +tags: + - name: Data API Status + description: Data API health check + - name: Core + - name: Builders + - name: Misc +paths: + /v1/accounting/snapshot: + get: + tags: + - Misc + summary: Download an accounting snapshot (ZIP of CSVs) + parameters: + - in: query + name: user + required: true + schema: + $ref: '#/components/schemas/Address' + description: User address (0x-prefixed) + responses: + '200': + description: ZIP file containing `positions.csv` and `equity.csv`. + content: + application/zip: + schema: + type: string + format: binary + '400': + description: Bad Request + content: + application/json: + schema: + $ref: '#/components/schemas/ErrorResponse' + '500': + description: Server Error + content: + application/json: + schema: + $ref: '#/components/schemas/ErrorResponse' +components: + schemas: + Address: + type: string + description: User Profile Address (0x-prefixed, 40 hex chars) + pattern: ^0x[a-fA-F0-9]{40}$ + example: '0x56687bf447db6ffa42ffe2204a05edaa20f55839' + ErrorResponse: + type: object + properties: + error: + type: string + required: + - error + +```` \ No newline at end of file diff --git a/PolymarketDocumentation-main/docs/api-reference/misc/get-live-volume-for-an-event.md b/PolymarketDocumentation-main/docs/api-reference/misc/get-live-volume-for-an-event.md new file mode 100644 index 00000000..7314bb53 --- /dev/null +++ b/PolymarketDocumentation-main/docs/api-reference/misc/get-live-volume-for-an-event.md @@ -0,0 +1,94 @@ +> ## Documentation Index +> Fetch the complete documentation index at: https://docs.polymarket.com/llms.txt +> Use this file to discover all available pages before exploring further. + +# Get live volume for an event + + + +## OpenAPI + +````yaml /api-spec/data-openapi.yaml get /live-volume +openapi: 3.0.3 +info: + title: Polymarket Data API + version: 1.0.0 + description: > + HTTP API for Polymarket data. This specification documents all public + routes. +servers: + - url: https://data-api.polymarket.com + description: Relative server (same host) +security: [] +tags: + - name: Data API Status + description: Data API health check + - name: Core + - name: Builders + - name: Misc +paths: + /live-volume: + get: + tags: + - Misc + summary: Get live volume for an event + parameters: + - in: query + name: id + required: true + schema: + type: integer + minimum: 1 + responses: + '200': + description: Success + content: + application/json: + schema: + type: array + items: + $ref: '#/components/schemas/LiveVolume' + '400': + description: Bad Request + content: + application/json: + schema: + $ref: '#/components/schemas/ErrorResponse' + '500': + description: Server Error + content: + application/json: + schema: + $ref: '#/components/schemas/ErrorResponse' +components: + schemas: + LiveVolume: + type: object + properties: + total: + type: number + markets: + type: array + items: + $ref: '#/components/schemas/MarketVolume' + ErrorResponse: + type: object + properties: + error: + type: string + required: + - error + MarketVolume: + type: object + properties: + market: + $ref: '#/components/schemas/Hash64' + value: + type: number + Hash64: + type: string + description: 0x-prefixed 64-hex string + pattern: ^0x[a-fA-F0-9]{64}$ + example: '0xdd22472e552920b8438158ea7238bfadfa4f736aa4cee91a6b86c39ead110917' + +```` \ No newline at end of file diff --git a/PolymarketDocumentation-main/docs/api-reference/misc/get-open-interest.md b/PolymarketDocumentation-main/docs/api-reference/misc/get-open-interest.md new file mode 100644 index 00000000..d82df3e6 --- /dev/null +++ b/PolymarketDocumentation-main/docs/api-reference/misc/get-open-interest.md @@ -0,0 +1,87 @@ +> ## Documentation Index +> Fetch the complete documentation index at: https://docs.polymarket.com/llms.txt +> Use this file to discover all available pages before exploring further. + +# Get open interest + + + +## OpenAPI + +````yaml /api-spec/data-openapi.yaml get /oi +openapi: 3.0.3 +info: + title: Polymarket Data API + version: 1.0.0 + description: > + HTTP API for Polymarket data. This specification documents all public + routes. +servers: + - url: https://data-api.polymarket.com + description: Relative server (same host) +security: [] +tags: + - name: Data API Status + description: Data API health check + - name: Core + - name: Builders + - name: Misc +paths: + /oi: + get: + tags: + - Misc + summary: Get open interest + parameters: + - in: query + name: market + style: form + explode: false + schema: + type: array + items: + $ref: '#/components/schemas/Hash64' + responses: + '200': + description: Success + content: + application/json: + schema: + type: array + items: + $ref: '#/components/schemas/OpenInterest' + '400': + description: Bad Request + content: + application/json: + schema: + $ref: '#/components/schemas/ErrorResponse' + '500': + description: Server Error + content: + application/json: + schema: + $ref: '#/components/schemas/ErrorResponse' +components: + schemas: + Hash64: + type: string + description: 0x-prefixed 64-hex string + pattern: ^0x[a-fA-F0-9]{64}$ + example: '0xdd22472e552920b8438158ea7238bfadfa4f736aa4cee91a6b86c39ead110917' + OpenInterest: + type: object + properties: + market: + $ref: '#/components/schemas/Hash64' + value: + type: number + ErrorResponse: + type: object + properties: + error: + type: string + required: + - error + +```` \ No newline at end of file diff --git a/PolymarketDocumentation-main/docs/api-reference/misc/get-total-markets-a-user-has-traded.md b/PolymarketDocumentation-main/docs/api-reference/misc/get-total-markets-a-user-has-traded.md new file mode 100644 index 00000000..ce57fdcb --- /dev/null +++ b/PolymarketDocumentation-main/docs/api-reference/misc/get-total-markets-a-user-has-traded.md @@ -0,0 +1,88 @@ +> ## Documentation Index +> Fetch the complete documentation index at: https://docs.polymarket.com/llms.txt +> Use this file to discover all available pages before exploring further. + +# Get total markets a user has traded + + + +## OpenAPI + +````yaml /api-spec/data-openapi.yaml get /traded +openapi: 3.0.3 +info: + title: Polymarket Data API + version: 1.0.0 + description: > + HTTP API for Polymarket data. This specification documents all public + routes. +servers: + - url: https://data-api.polymarket.com + description: Relative server (same host) +security: [] +tags: + - name: Data API Status + description: Data API health check + - name: Core + - name: Builders + - name: Misc +paths: + /traded: + get: + tags: + - Misc + summary: Get total markets a user has traded + parameters: + - in: query + name: user + required: true + schema: + $ref: '#/components/schemas/Address' + responses: + '200': + description: Success + content: + application/json: + schema: + $ref: '#/components/schemas/Traded' + '400': + description: Bad Request + content: + application/json: + schema: + $ref: '#/components/schemas/ErrorResponse' + '401': + description: Unauthorized + content: + application/json: + schema: + $ref: '#/components/schemas/ErrorResponse' + '500': + description: Server Error + content: + application/json: + schema: + $ref: '#/components/schemas/ErrorResponse' +components: + schemas: + Address: + type: string + description: User Profile Address (0x-prefixed, 40 hex chars) + pattern: ^0x[a-fA-F0-9]{40}$ + example: '0x56687bf447db6ffa42ffe2204a05edaa20f55839' + Traded: + type: object + properties: + user: + $ref: '#/components/schemas/Address' + traded: + type: integer + ErrorResponse: + type: object + properties: + error: + type: string + required: + - error + +```` \ No newline at end of file diff --git a/PolymarketDocumentation-main/docs/api-reference/profiles/get-public-profile-by-wallet-address.md b/PolymarketDocumentation-main/docs/api-reference/profiles/get-public-profile-by-wallet-address.md new file mode 100644 index 00000000..fc1a1101 --- /dev/null +++ b/PolymarketDocumentation-main/docs/api-reference/profiles/get-public-profile-by-wallet-address.md @@ -0,0 +1,154 @@ +> ## Documentation Index +> Fetch the complete documentation index at: https://docs.polymarket.com/llms.txt +> Use this file to discover all available pages before exploring further. + +# Get public profile by wallet address + + + +## OpenAPI + +````yaml /api-spec/gamma-openapi.yaml get /public-profile +openapi: 3.0.3 +info: + title: Markets API + version: 1.0.0 + description: REST API specification for public endpoints used by the Markets service. +servers: + - url: https://gamma-api.polymarket.com + description: Polymarket Gamma API Production Server +security: [] +tags: + - name: Gamma Status + description: Gamma API status and health check + - name: Sports + description: Sports-related endpoints including teams and game data + - name: Tags + description: Tag management and related tag operations + - name: Events + description: Event management and event-related operations + - name: Markets + description: Market data and market-related operations + - name: Comments + description: Comment system and user interactions + - name: Series + description: Series management and related operations + - name: Profiles + description: User profile management + - name: Search + description: Search functionality across different entity types +paths: + /public-profile: + get: + tags: + - Profiles + summary: Get public profile by wallet address + operationId: getPublicProfile + parameters: + - name: address + in: query + required: true + description: The wallet address (proxy wallet or user address) + schema: + type: string + pattern: ^0x[a-fA-F0-9]{40}$ + example: '0x7c3db723f1d4d8cb9c550095203b686cb11e5c6b' + responses: + '200': + description: Public profile information + content: + application/json: + schema: + $ref: '#/components/schemas/PublicProfileResponse' + '400': + description: Invalid address format + content: + application/json: + schema: + $ref: '#/components/schemas/PublicProfileError' + example: + type: validation error + error: invalid address + '404': + description: Profile not found + content: + application/json: + schema: + $ref: '#/components/schemas/PublicProfileError' + example: + type: not found error + error: profile not found +components: + schemas: + PublicProfileResponse: + type: object + properties: + createdAt: + type: string + format: date-time + description: ISO 8601 timestamp of when the profile was created + nullable: true + proxyWallet: + type: string + description: The proxy wallet address + nullable: true + profileImage: + type: string + format: uri + description: URL to the profile image + nullable: true + displayUsernamePublic: + type: boolean + description: Whether the username is displayed publicly + nullable: true + bio: + type: string + description: Profile bio + nullable: true + pseudonym: + type: string + description: Auto-generated pseudonym + nullable: true + name: + type: string + description: User-chosen display name + nullable: true + users: + type: array + description: Array of associated user objects + nullable: true + items: + $ref: '#/components/schemas/PublicProfileUser' + xUsername: + type: string + description: X (Twitter) username + nullable: true + verifiedBadge: + type: boolean + description: Whether the profile has a verified badge + nullable: true + PublicProfileError: + type: object + description: Error response for public profile endpoint + properties: + type: + type: string + description: Error type classification + error: + type: string + description: Error message + PublicProfileUser: + type: object + description: User object associated with a public profile + properties: + id: + type: string + description: User ID + creator: + type: boolean + description: Whether the user is a creator + mod: + type: boolean + description: Whether the user is a moderator + +```` \ No newline at end of file diff --git a/PolymarketDocumentation-main/docs/api-reference/rate-limits.md b/PolymarketDocumentation-main/docs/api-reference/rate-limits.md new file mode 100644 index 00000000..7b39a0a3 --- /dev/null +++ b/PolymarketDocumentation-main/docs/api-reference/rate-limits.md @@ -0,0 +1,136 @@ +> ## Documentation Index +> Fetch the complete documentation index at: https://docs.polymarket.com/llms.txt +> Use this file to discover all available pages before exploring further. + +# Rate Limits + +> API rate limits for all Polymarket endpoints + +All API rate limits are enforced using Cloudflare's throttling system. When you exceed the limit for any endpoint, requests are throttled (delayed/queued) rather than immediately rejected. Limits reset on sliding time windows. + +*** + +## General + +| Endpoint | Limit | +| --------------------- | ---------------- | +| General rate limiting | 15,000 req / 10s | +| Health check (`/ok`) | 100 req / 10s | + +*** + +## Gamma API + +Base URL: `https://gamma-api.polymarket.com` + +| Endpoint | Limit | +| ------------------------------ | --------------- | +| General | 4,000 req / 10s | +| `/events` | 500 req / 10s | +| `/markets` | 300 req / 10s | +| `/markets` + `/events` listing | 900 req / 10s | +| `/comments` | 200 req / 10s | +| `/tags` | 200 req / 10s | +| `/public-search` | 350 req / 10s | + +*** + +## Data API + +Base URL: `https://data-api.polymarket.com` + +| Endpoint | Limit | +| -------------------- | --------------- | +| General | 1,000 req / 10s | +| `/trades` | 200 req / 10s | +| `/positions` | 150 req / 10s | +| `/closed-positions` | 150 req / 10s | +| Health check (`/ok`) | 100 req / 10s | + +*** + +## CLOB API + +Base URL: `https://clob.polymarket.com` + +### General + +| Endpoint | Limit | +| -------------------------- | --------------- | +| General | 9,000 req / 10s | +| `GET` balance allowance | 200 req / 10s | +| `UPDATE` balance allowance | 50 req / 10s | + +### Market Data + +| Endpoint | Limit | +| ----------------- | --------------- | +| `/book` | 1,500 req / 10s | +| `/books` | 500 req / 10s | +| `/price` | 1,500 req / 10s | +| `/prices` | 500 req / 10s | +| `/midpoint` | 1,500 req / 10s | +| `/midpoints` | 500 req / 10s | +| `/prices-history` | 1,000 req / 10s | +| Market tick size | 200 req / 10s | + +### Ledger + +| Endpoint | Limit | +| ------------------------------------------------ | ------------- | +| `/trades`, `/orders`, `/notifications`, `/order` | 900 req / 10s | +| `/data/orders` | 500 req / 10s | +| `/data/trades` | 500 req / 10s | +| `/notifications` | 125 req / 10s | + +### Authentication + +| Endpoint | Limit | +| ----------------- | ------------- | +| API key endpoints | 100 req / 10s | + +### Trading + +Trading endpoints have both **burst** limits (short spikes allowed) and **sustained** limits (longer-term average). + +| Endpoint | Burst Limit | Sustained Limit | +| ------------------------------ | --------------- | -------------------- | +| `POST /order` | 5,000 req / 10s | 120,000 req / 10 min | +| `DELETE /order` | 5,000 req / 10s | 120,000 req / 10 min | +| `POST /orders` | 2,000 req / 10s | 21,000 req / 10 min | +| `DELETE /orders` | 2,000 req / 10s | 15,000 req / 10 min | +| `DELETE /cancel-all` | 250 req / 10s | 6,000 req / 10 min | +| `DELETE /cancel-market-orders` | 1,500 req / 10s | 21,000 req / 10 min | + +*** + +## Bridge API + +Base URL: `https://bridge.polymarket.com` + +| Endpoint | Limit | +| -------- | ------------ | +| General | 50 req / 10s | + +*** + +## Other + +| Endpoint | Limit | +| ----------------- | -------------- | +| Relayer `/submit` | 25 req / 1 min | +| User PNL API | 200 req / 10s | + +*** + +## Next Steps + + + + Learn how to authenticate trading requests. + + + + Official TypeScript, Python, and Rust libraries. + + diff --git a/PolymarketDocumentation-main/docs/api-reference/rebates/get-current-rebated-fees-for-a-maker.md b/PolymarketDocumentation-main/docs/api-reference/rebates/get-current-rebated-fees-for-a-maker.md new file mode 100644 index 00000000..44155a1b --- /dev/null +++ b/PolymarketDocumentation-main/docs/api-reference/rebates/get-current-rebated-fees-for-a-maker.md @@ -0,0 +1,164 @@ +> ## Documentation Index +> Fetch the complete documentation index at: https://docs.polymarket.com/llms.txt +> Use this file to discover all available pages before exploring further. + +# Get current rebated fees for a maker + +> Returns the current rebated fees for a maker address on a given date. + +Each entry includes the condition ID, asset address, and the USDC amount rebated. + +This endpoint does not require authentication. + + + + +## OpenAPI + +````yaml /api-spec/clob-openapi.yaml get /rebates/current +openapi: 3.1.0 +info: + title: Polymarket CLOB API + description: Polymarket CLOB API Reference + license: + name: MIT + identifier: MIT + version: 1.0.0 +servers: + - url: https://clob.polymarket.com + description: Production CLOB API + - url: https://clob-staging.polymarket.com + description: Staging CLOB API +security: [] +tags: + - name: Trade + description: Trade endpoints + - name: Markets + description: Market data endpoints + - name: Account + description: Account and authentication endpoints + - name: Notifications + description: User notification endpoints + - name: Rewards + description: Rewards and earnings endpoints + - name: Rebates + description: Maker rebate endpoints +paths: + /rebates/current: + get: + tags: + - Rebates + summary: Get current rebated fees for a maker + description: > + Returns the current rebated fees for a maker address on a given date. + + + Each entry includes the condition ID, asset address, and the USDC amount + rebated. + + + This endpoint does not require authentication. + operationId: getCurrentRebatedFees + parameters: + - name: date + in: query + description: Date in YYYY-MM-DD format + required: true + schema: + type: string + format: date + example: '2026-02-27' + - name: maker_address + in: query + description: Ethereum address of the maker + required: true + schema: + type: string + example: '0xFeA4cB3dD4ca7CefD3368653B7D6FF9BcDFca604' + responses: + '200': + description: Successfully retrieved rebated fees + content: + application/json: + schema: + type: array + items: + $ref: '#/components/schemas/RebatedFees' + example: + - date: '2026-02-27' + condition_id: >- + 0xbd31dc8a20211944f6b70f31557f1001557b59905b7738480ca09bd4532f84af + asset_address: '0xC011a7E12a19f7B1f670d46F03B03f3342E82DFB' + maker_address: '0xFeA4cB3dD4ca7CefD3368653B7D6FF9BcDFca604' + rebated_fees_usdc: '0.237519' + '400': + description: Bad request - Invalid parameters + content: + application/json: + schema: + $ref: '#/components/schemas/ErrorResponse' + examples: + invalid_date: + summary: Invalid date + value: + error: Invalid date + invalid_maker_address: + summary: Invalid maker address + value: + error: Invalid maker_address + '500': + description: Internal server error + content: + application/json: + schema: + $ref: '#/components/schemas/ErrorResponse' + example: + error: Internal server error +components: + schemas: + RebatedFees: + type: object + description: Rebated fees for a maker on a specific market and date + required: + - date + - condition_id + - asset_address + - maker_address + - rebated_fees_usdc + properties: + date: + type: string + description: Date of the rebate (YYYY-MM-DD) + example: '2026-02-27' + condition_id: + type: string + description: Condition ID of the market + example: '0xbd31dc8a20211944f6b70f31557f1001557b59905b7738480ca09bd4532f84af' + asset_address: + type: string + description: Asset address (e.g. USDC contract) + example: '0xC011a7E12a19f7B1f670d46F03B03f3342E82DFB' + maker_address: + type: string + description: Maker's Ethereum address + example: '0xFeA4cB3dD4ca7CefD3368653B7D6FF9BcDFca604' + rebated_fees_usdc: + type: string + description: Rebated fee amount in USDC + example: '0.237519' + ErrorResponse: + type: object + required: + - error + properties: + error: + type: string + description: Error message + code: + type: string + description: Machine-readable error code, when provided + retry_after_seconds: + type: integer + description: Number of seconds to wait before retrying, when provided + +```` \ No newline at end of file diff --git a/PolymarketDocumentation-main/docs/api-reference/relayer-api-keys/get-all-relayer-api-keys.md b/PolymarketDocumentation-main/docs/api-reference/relayer-api-keys/get-all-relayer-api-keys.md new file mode 100644 index 00000000..e4549e60 --- /dev/null +++ b/PolymarketDocumentation-main/docs/api-reference/relayer-api-keys/get-all-relayer-api-keys.md @@ -0,0 +1,139 @@ +> ## Documentation Index +> Fetch the complete documentation index at: https://docs.polymarket.com/llms.txt +> Use this file to discover all available pages before exploring further. + +# Get all relayer API keys + +> Returns all relayer API keys for the authenticated address. Auth allowed: Gamma auth or Relayer API key auth (`RELAYER_API_KEY` + `RELAYER_API_KEY_ADDRESS`). + + + + +## OpenAPI + +````yaml /api-spec/relayer-openapi.yaml get /relayer/api/keys +openapi: 3.0.3 +info: + title: Polymarket Relayer API + version: 1.0.0 + description: HTTP API for the Polymarket Relayer. Submit and track gasless transactions. +servers: + - url: https://relayer-v2.polymarket.com + description: Polymarket Relayer API +security: [] +tags: + - name: Relayer + description: Relayer transaction operations + - name: Relayer API Keys + description: > + Relayer API keys let a user authenticate requests to relayer endpoints + without Gamma auth. + + However, Relayer API keys can only be created using Gamma auth. Every + address can create a maximum of 100 keys. + + + The API key auth headers are: + + - `RELAYER_API_KEY` + + - `RELAYER_API_KEY_ADDRESS` + + + `RELAYER_API_KEY_ADDRESS` must match the address that owns the key. +paths: + /relayer/api/keys: + get: + tags: + - Relayer API Keys + summary: Get all relayer API keys + description: > + Returns all relayer API keys for the authenticated address. Auth + allowed: Gamma auth or Relayer API key auth (`RELAYER_API_KEY` + + `RELAYER_API_KEY_ADDRESS`). + parameters: + - name: RELAYER_API_KEY + in: header + required: false + description: Relayer API key (when using relayer API key auth) + schema: + type: string + example: 01967c03-b8c8-7000-8f68-8b8eaec6fd3d + - name: RELAYER_API_KEY_ADDRESS + in: header + required: false + description: >- + Address that owns the key (when using relayer API key auth). Must + match the address that owns the key. + schema: + $ref: '#/components/schemas/Address' + example: 0xabc... + responses: + '200': + description: >- + API keys retrieved successfully. Returns an empty array if no keys + exist for the authenticated address. + content: + application/json: + schema: + type: array + items: + $ref: '#/components/schemas/RelayerApiKey' + example: + - apiKey: 01967c03-b8c8-7000-8f68-8b8eaec6fd3d + address: 0xabc... + createdAt: '2026-02-24T18:20:11.237485Z' + updatedAt: '2026-02-24T18:20:11.237485Z' + '401': + description: Unauthorized - Missing or invalid auth + content: + application/json: + schema: + $ref: '#/components/schemas/ErrorResponse' + example: + error: invalid authorization + '403': + description: Forbidden - Unsupported auth mechanism + content: + application/json: + schema: + $ref: '#/components/schemas/ErrorResponse' + example: + error: not allowed +components: + schemas: + Address: + type: string + description: Ethereum address (0x-prefixed, 40 hex chars) + pattern: ^0x[a-fA-F0-9]{40}$ + example: '0x6e0c80c90ea6c15917308F820Eac91Ce2724B5b5' + RelayerApiKey: + type: object + properties: + apiKey: + type: string + description: The relayer API key + example: 01967c03-b8c8-7000-8f68-8b8eaec6fd3d + address: + $ref: '#/components/schemas/Address' + description: The address that owns the key + example: 0xabc... + createdAt: + type: string + format: date-time + description: Timestamp when the key was created + example: '2026-02-24T18:20:11.237485Z' + updatedAt: + type: string + format: date-time + description: Timestamp when the key was last updated + example: '2026-02-24T18:20:11.237485Z' + ErrorResponse: + type: object + properties: + error: + type: string + required: + - error + +```` \ No newline at end of file diff --git a/PolymarketDocumentation-main/docs/api-reference/relayer/check-if-a-safe-is-deployed.md b/PolymarketDocumentation-main/docs/api-reference/relayer/check-if-a-safe-is-deployed.md new file mode 100644 index 00000000..ab83f175 --- /dev/null +++ b/PolymarketDocumentation-main/docs/api-reference/relayer/check-if-a-safe-is-deployed.md @@ -0,0 +1,137 @@ +> ## Documentation Index +> Fetch the complete documentation index at: https://docs.polymarket.com/llms.txt +> Use this file to discover all available pages before exploring further. + +# Check if a wallet is deployed + +> Returns whether the wallet at the given address is deployed onchain. + +Use the `type` query parameter to choose which wallet type to check: + +- Pass user's Polymarket `SAFE` address (default): Gnosis Safe (SignatureType `2`). +- Pass user's Polymarket `WALLET` Deposit Wallet address: Deposit Wallet (signatureType `3`). See the [Deposit Wallet Guide](/trading/deposit-wallets) for setup. + +Omitting `type` is equivalent to `type=SAFE`. + + + + +## OpenAPI + +````yaml /api-spec/relayer-openapi.yaml get /deployed +openapi: 3.0.3 +info: + title: Polymarket Relayer API + version: 1.0.0 + description: HTTP API for the Polymarket Relayer. Submit and track gasless transactions. +servers: + - url: https://relayer-v2.polymarket.com + description: Polymarket Relayer API +security: [] +tags: + - name: Relayer + description: Relayer transaction operations + - name: Relayer API Keys + description: > + Relayer API keys let a user authenticate requests to relayer endpoints + without Gamma auth. + + However, Relayer API keys can only be created using Gamma auth. Every + address can create a maximum of 100 keys. + + + The API key auth headers are: + + - `RELAYER_API_KEY` + + - `RELAYER_API_KEY_ADDRESS` + + + `RELAYER_API_KEY_ADDRESS` must match the address that owns the key. +paths: + /deployed: + get: + tags: + - Relayer + summary: Check if a wallet is deployed + description: > + Returns whether the wallet at the given address is deployed onchain. + + + Use the `type` query parameter to choose which wallet type to check: + + + - Pass user's Polymarket `SAFE` address (default): Gnosis Safe + (SignatureType `2`). + + - Pass user's Polymarket `WALLET` Deposit Wallet address: Deposit Wallet + (signatureType `3`). See the [Deposit Wallet + Guide](/trading/deposit-wallets) for setup. + + + Omitting `type` is equivalent to `type=SAFE`. + parameters: + - name: address + in: query + required: true + description: Address of the wallet to check + schema: + $ref: '#/components/schemas/Address' + example: '0x6d8c4e9aDF5748Af82Dabe2C6225207770d6B4fa' + - name: type + in: query + required: false + description: Wallet type to check. Defaults to `SAFE` when omitted. + schema: + type: string + enum: + - SAFE + - WALLET + default: SAFE + example: WALLET + responses: + '200': + description: Deployment status retrieved successfully + content: + application/json: + schema: + $ref: '#/components/schemas/DeployedResponse' + example: + deployed: true + '400': + description: Bad Request - Missing or invalid address + content: + application/json: + schema: + $ref: '#/components/schemas/ErrorResponse' + example: + error: invalid address + '500': + description: Server Error + content: + application/json: + schema: + $ref: '#/components/schemas/ErrorResponse' +components: + schemas: + Address: + type: string + description: Ethereum address (0x-prefixed, 40 hex chars) + pattern: ^0x[a-fA-F0-9]{40}$ + example: '0x6e0c80c90ea6c15917308F820Eac91Ce2724B5b5' + DeployedResponse: + type: object + properties: + deployed: + type: boolean + description: Whether the wallet is deployed + example: true + ErrorResponse: + type: object + properties: + error: + type: string + required: + - error + +```` \ No newline at end of file diff --git a/PolymarketDocumentation-main/docs/api-reference/relayer/check-if-a-wallet-is-deployed.md b/PolymarketDocumentation-main/docs/api-reference/relayer/check-if-a-wallet-is-deployed.md new file mode 100644 index 00000000..ab83f175 --- /dev/null +++ b/PolymarketDocumentation-main/docs/api-reference/relayer/check-if-a-wallet-is-deployed.md @@ -0,0 +1,137 @@ +> ## Documentation Index +> Fetch the complete documentation index at: https://docs.polymarket.com/llms.txt +> Use this file to discover all available pages before exploring further. + +# Check if a wallet is deployed + +> Returns whether the wallet at the given address is deployed onchain. + +Use the `type` query parameter to choose which wallet type to check: + +- Pass user's Polymarket `SAFE` address (default): Gnosis Safe (SignatureType `2`). +- Pass user's Polymarket `WALLET` Deposit Wallet address: Deposit Wallet (signatureType `3`). See the [Deposit Wallet Guide](/trading/deposit-wallets) for setup. + +Omitting `type` is equivalent to `type=SAFE`. + + + + +## OpenAPI + +````yaml /api-spec/relayer-openapi.yaml get /deployed +openapi: 3.0.3 +info: + title: Polymarket Relayer API + version: 1.0.0 + description: HTTP API for the Polymarket Relayer. Submit and track gasless transactions. +servers: + - url: https://relayer-v2.polymarket.com + description: Polymarket Relayer API +security: [] +tags: + - name: Relayer + description: Relayer transaction operations + - name: Relayer API Keys + description: > + Relayer API keys let a user authenticate requests to relayer endpoints + without Gamma auth. + + However, Relayer API keys can only be created using Gamma auth. Every + address can create a maximum of 100 keys. + + + The API key auth headers are: + + - `RELAYER_API_KEY` + + - `RELAYER_API_KEY_ADDRESS` + + + `RELAYER_API_KEY_ADDRESS` must match the address that owns the key. +paths: + /deployed: + get: + tags: + - Relayer + summary: Check if a wallet is deployed + description: > + Returns whether the wallet at the given address is deployed onchain. + + + Use the `type` query parameter to choose which wallet type to check: + + + - Pass user's Polymarket `SAFE` address (default): Gnosis Safe + (SignatureType `2`). + + - Pass user's Polymarket `WALLET` Deposit Wallet address: Deposit Wallet + (signatureType `3`). See the [Deposit Wallet + Guide](/trading/deposit-wallets) for setup. + + + Omitting `type` is equivalent to `type=SAFE`. + parameters: + - name: address + in: query + required: true + description: Address of the wallet to check + schema: + $ref: '#/components/schemas/Address' + example: '0x6d8c4e9aDF5748Af82Dabe2C6225207770d6B4fa' + - name: type + in: query + required: false + description: Wallet type to check. Defaults to `SAFE` when omitted. + schema: + type: string + enum: + - SAFE + - WALLET + default: SAFE + example: WALLET + responses: + '200': + description: Deployment status retrieved successfully + content: + application/json: + schema: + $ref: '#/components/schemas/DeployedResponse' + example: + deployed: true + '400': + description: Bad Request - Missing or invalid address + content: + application/json: + schema: + $ref: '#/components/schemas/ErrorResponse' + example: + error: invalid address + '500': + description: Server Error + content: + application/json: + schema: + $ref: '#/components/schemas/ErrorResponse' +components: + schemas: + Address: + type: string + description: Ethereum address (0x-prefixed, 40 hex chars) + pattern: ^0x[a-fA-F0-9]{40}$ + example: '0x6e0c80c90ea6c15917308F820Eac91Ce2724B5b5' + DeployedResponse: + type: object + properties: + deployed: + type: boolean + description: Whether the wallet is deployed + example: true + ErrorResponse: + type: object + properties: + error: + type: string + required: + - error + +```` \ No newline at end of file diff --git a/PolymarketDocumentation-main/docs/api-reference/relayer/get-a-transaction-by-id.md b/PolymarketDocumentation-main/docs/api-reference/relayer/get-a-transaction-by-id.md new file mode 100644 index 00000000..4ab74876 --- /dev/null +++ b/PolymarketDocumentation-main/docs/api-reference/relayer/get-a-transaction-by-id.md @@ -0,0 +1,208 @@ +> ## Documentation Index +> Fetch the complete documentation index at: https://docs.polymarket.com/llms.txt +> Use this file to discover all available pages before exploring further. + +# Get a transaction by ID + +> Gets a transaction submitted to the Relayer. Takes in a required transaction ID as a query parameter. + +Poll this endpoint with the `transactionID` returned from `POST /submit` to retrieve the onchain `transactionHash` once the transaction has been broadcast. + + + + +## OpenAPI + +````yaml /api-spec/relayer-openapi.yaml get /transaction +openapi: 3.0.3 +info: + title: Polymarket Relayer API + version: 1.0.0 + description: HTTP API for the Polymarket Relayer. Submit and track gasless transactions. +servers: + - url: https://relayer-v2.polymarket.com + description: Polymarket Relayer API +security: [] +tags: + - name: Relayer + description: Relayer transaction operations + - name: Relayer API Keys + description: > + Relayer API keys let a user authenticate requests to relayer endpoints + without Gamma auth. + + However, Relayer API keys can only be created using Gamma auth. Every + address can create a maximum of 100 keys. + + + The API key auth headers are: + + - `RELAYER_API_KEY` + + - `RELAYER_API_KEY_ADDRESS` + + + `RELAYER_API_KEY_ADDRESS` must match the address that owns the key. +paths: + /transaction: + get: + tags: + - Relayer + summary: Get a transaction by ID + description: > + Gets a transaction submitted to the Relayer. Takes in a required + transaction ID as a query parameter. + + + Poll this endpoint with the `transactionID` returned from `POST /submit` + to retrieve the onchain `transactionHash` once the transaction has been + broadcast. + parameters: + - name: id + in: query + required: true + description: Transaction ID + schema: + type: string + example: 0190b317-a1d3-7bec-9b91-eeb6dcd3a620 + responses: + '200': + description: Transaction retrieved successfully + content: + application/json: + schema: + type: array + items: + $ref: '#/components/schemas/RelayerTransaction' + example: + - transactionID: 0190b317-a1d3-7bec-9b91-eeb6dcd3a620 + transactionHash: >- + 0x38cbfbeae8fffa4e2b187ee5978d3ee9cafc53af0363ed90a35b7ea9016535d8 + from: '0x6e0c80c90ea6c15917308f820eac91ce2724b5b5' + to: '0x2791bca1f2de4661ed88a30c99a7a9449aa84174' + proxyAddress: '0x6d8c4e9adf5748af82dabe2c6225207770d6b4fa' + data: 0x... + nonce: '60' + value: '' + signature: >- + 0x01a060c734d7bdf4adde50c4a7e574036b1f8b12890911bdd1c1cfdcd77502381b89fa8a47c36f62a0b9f1cdfee7b260fd8108536db9f6b2089c02637e7de9fc20 + state: STATE_CONFIRMED + type: SAFE + owner: '0x6e0c80c90ea6c15917308f820eac91ce2724b5b5' + metadata: '' + createdAt: '2024-07-14T21:13:08.819782Z' + updatedAt: '2024-07-14T21:13:46.576639Z' + '400': + description: Bad Request - Missing or invalid transaction ID + content: + application/json: + schema: + $ref: '#/components/schemas/ErrorResponse' + example: + error: invalid id + '404': + description: Transaction not found + content: + application/json: + schema: + $ref: '#/components/schemas/ErrorResponse' + example: + error: transaction not found + '500': + description: Server Error + content: + application/json: + schema: + $ref: '#/components/schemas/ErrorResponse' +components: + schemas: + RelayerTransaction: + type: object + properties: + transactionID: + type: string + description: Unique identifier for the transaction + example: 0190b317-a1d3-7bec-9b91-eeb6dcd3a620 + transactionHash: + type: string + description: Onchain transaction hash (available once confirmed) + example: '0x38cbfbeae8fffa4e2b187ee5978d3ee9cafc53af0363ed90a35b7ea9016535d8' + from: + $ref: '#/components/schemas/Address' + description: Signer address + example: '0x6e0c80c90ea6c15917308f820eac91ce2724b5b5' + to: + $ref: '#/components/schemas/Address' + description: Target contract address + example: '0x2791bca1f2de4661ed88a30c99a7a9449aa84174' + proxyAddress: + $ref: '#/components/schemas/Address' + description: User's Polymarket proxy wallet address + example: '0x6d8c4e9adf5748af82dabe2c6225207770d6b4fa' + data: + type: string + description: Encoded transaction data (0x-prefixed hex string) + example: 0x... + nonce: + type: string + description: Transaction nonce + example: '60' + value: + type: string + description: Transaction value + example: '' + signature: + type: string + description: Transaction signature (0x-prefixed hex string) + example: >- + 0x01a060c734d7bdf4adde50c4a7e574036b1f8b12890911bdd1c1cfdcd77502381b89fa8a47c36f62a0b9f1cdfee7b260fd8108536db9f6b2089c02637e7de9fc20 + state: + type: string + description: Current state of the transaction + enum: + - STATE_NEW + - STATE_EXECUTED + - STATE_MINED + - STATE_CONFIRMED + - STATE_INVALID + - STATE_FAILED + example: STATE_CONFIRMED + type: + type: string + description: Transaction type + enum: + - SAFE + - PROXY + example: SAFE + owner: + $ref: '#/components/schemas/Address' + description: Owner address + example: '0x6e0c80c90ea6c15917308f820eac91ce2724b5b5' + metadata: + type: string + description: Transaction metadata + example: '' + createdAt: + type: string + format: date-time + description: Timestamp when the transaction was created + example: '2024-07-14T21:13:08.819782Z' + updatedAt: + type: string + format: date-time + description: Timestamp when the transaction was last updated + example: '2024-07-14T21:13:46.576639Z' + ErrorResponse: + type: object + properties: + error: + type: string + required: + - error + Address: + type: string + description: Ethereum address (0x-prefixed, 40 hex chars) + pattern: ^0x[a-fA-F0-9]{40}$ + example: '0x6e0c80c90ea6c15917308F820Eac91Ce2724B5b5' + +```` \ No newline at end of file diff --git a/PolymarketDocumentation-main/docs/api-reference/relayer/get-current-nonce-for-a-user.md b/PolymarketDocumentation-main/docs/api-reference/relayer/get-current-nonce-for-a-user.md new file mode 100644 index 00000000..f1de5455 --- /dev/null +++ b/PolymarketDocumentation-main/docs/api-reference/relayer/get-current-nonce-for-a-user.md @@ -0,0 +1,121 @@ +> ## Documentation Index +> Fetch the complete documentation index at: https://docs.polymarket.com/llms.txt +> Use this file to discover all available pages before exploring further. + +# Get current nonce for a user + +> Gets the current Proxy or Safe nonce for a user. Takes in the user's signer address and the type of nonce to retrieve. + + + + +## OpenAPI + +````yaml /api-spec/relayer-openapi.yaml get /nonce +openapi: 3.0.3 +info: + title: Polymarket Relayer API + version: 1.0.0 + description: HTTP API for the Polymarket Relayer. Submit and track gasless transactions. +servers: + - url: https://relayer-v2.polymarket.com + description: Polymarket Relayer API +security: [] +tags: + - name: Relayer + description: Relayer transaction operations + - name: Relayer API Keys + description: > + Relayer API keys let a user authenticate requests to relayer endpoints + without Gamma auth. + + However, Relayer API keys can only be created using Gamma auth. Every + address can create a maximum of 100 keys. + + + The API key auth headers are: + + - `RELAYER_API_KEY` + + - `RELAYER_API_KEY_ADDRESS` + + + `RELAYER_API_KEY_ADDRESS` must match the address that owns the key. +paths: + /nonce: + get: + tags: + - Relayer + summary: Get current nonce for a user + description: > + Gets the current Proxy or Safe nonce for a user. Takes in the user's + signer address and the type of nonce to retrieve. + parameters: + - name: address + in: query + required: true + description: User's signer address + schema: + $ref: '#/components/schemas/Address' + example: '0x77837466dd64fb52ECD00C737F060d0ff5CCB575' + - name: type + in: query + required: true + description: Type of nonce to retrieve + schema: + type: string + enum: + - PROXY + - SAFE + example: PROXY + responses: + '200': + description: Nonce retrieved successfully + content: + application/json: + schema: + $ref: '#/components/schemas/NonceResponse' + example: + nonce: '31' + '400': + description: Bad Request - Missing or invalid query parameters + content: + application/json: + schema: + $ref: '#/components/schemas/ErrorResponse' + examples: + invalidAddress: + value: + error: invalid address + invalidType: + value: + error: invalid type + '500': + description: Server Error + content: + application/json: + schema: + $ref: '#/components/schemas/ErrorResponse' +components: + schemas: + Address: + type: string + description: Ethereum address (0x-prefixed, 40 hex chars) + pattern: ^0x[a-fA-F0-9]{40}$ + example: '0x6e0c80c90ea6c15917308F820Eac91Ce2724B5b5' + NonceResponse: + type: object + properties: + nonce: + type: string + description: Current nonce value + example: '31' + ErrorResponse: + type: object + properties: + error: + type: string + required: + - error + +```` \ No newline at end of file diff --git a/PolymarketDocumentation-main/docs/api-reference/relayer/get-recent-transactions-for-a-user.md b/PolymarketDocumentation-main/docs/api-reference/relayer/get-recent-transactions-for-a-user.md new file mode 100644 index 00000000..1a0da102 --- /dev/null +++ b/PolymarketDocumentation-main/docs/api-reference/relayer/get-recent-transactions-for-a-user.md @@ -0,0 +1,269 @@ +> ## Documentation Index +> Fetch the complete documentation index at: https://docs.polymarket.com/llms.txt +> Use this file to discover all available pages before exploring further. + +# Get recent transactions for a user + +> Gets the most recent transactions submitted to the Relayer, owned by a specific user. Authenticated using Builder API Keys or Relayer API Keys. + +**Builder API Key auth headers:** +- `POLY_BUILDER_API_KEY` +- `POLY_BUILDER_TIMESTAMP` +- `POLY_BUILDER_PASSPHRASE` +- `POLY_BUILDER_SIGNATURE` + +**Relayer API Key auth headers:** +- `RELAYER_API_KEY` +- `RELAYER_API_KEY_ADDRESS` + + + + +## OpenAPI + +````yaml /api-spec/relayer-openapi.yaml get /transactions +openapi: 3.0.3 +info: + title: Polymarket Relayer API + version: 1.0.0 + description: HTTP API for the Polymarket Relayer. Submit and track gasless transactions. +servers: + - url: https://relayer-v2.polymarket.com + description: Polymarket Relayer API +security: [] +tags: + - name: Relayer + description: Relayer transaction operations + - name: Relayer API Keys + description: > + Relayer API keys let a user authenticate requests to relayer endpoints + without Gamma auth. + + However, Relayer API keys can only be created using Gamma auth. Every + address can create a maximum of 100 keys. + + + The API key auth headers are: + + - `RELAYER_API_KEY` + + - `RELAYER_API_KEY_ADDRESS` + + + `RELAYER_API_KEY_ADDRESS` must match the address that owns the key. +paths: + /transactions: + get: + tags: + - Relayer + summary: Get recent transactions for a user + description: > + Gets the most recent transactions submitted to the Relayer, owned by a + specific user. Authenticated using Builder API Keys or Relayer API Keys. + + + **Builder API Key auth headers:** + + - `POLY_BUILDER_API_KEY` + + - `POLY_BUILDER_TIMESTAMP` + + - `POLY_BUILDER_PASSPHRASE` + + - `POLY_BUILDER_SIGNATURE` + + + **Relayer API Key auth headers:** + + - `RELAYER_API_KEY` + + - `RELAYER_API_KEY_ADDRESS` + parameters: + - name: POLY_BUILDER_API_KEY + in: header + required: false + description: Builder API key (when using Builder API Key auth) + schema: + type: string + - name: POLY_BUILDER_TIMESTAMP + in: header + required: false + description: Unix timestamp (when using Builder API Key auth) + schema: + type: string + - name: POLY_BUILDER_PASSPHRASE + in: header + required: false + description: Builder passphrase (when using Builder API Key auth) + schema: + type: string + - name: POLY_BUILDER_SIGNATURE + in: header + required: false + description: HMAC-SHA256 signature (when using Builder API Key auth) + schema: + type: string + - name: RELAYER_API_KEY + in: header + required: false + description: Relayer API key (when using Relayer API Key auth) + schema: + type: string + - name: RELAYER_API_KEY_ADDRESS + in: header + required: false + description: Address that owns the key (when using Relayer API Key auth) + schema: + $ref: '#/components/schemas/Address' + responses: + '200': + description: Transactions retrieved successfully + content: + application/json: + schema: + type: array + items: + $ref: '#/components/schemas/RelayerTransaction' + example: + - transactionID: 0190b317-a1d3-7bec-9b91-eeb6dcd3a620 + transactionHash: >- + 0x38cbfbeae8fffa4e2b187ee5978d3ee9cafc53af0363ed90a35b7ea9016535d8 + from: '0x6e0c80c90ea6c15917308f820eac91ce2724b5b5' + to: '0x2791bca1f2de4661ed88a30c99a7a9449aa84174' + proxyAddress: '0x6d8c4e9adf5748af82dabe2c6225207770d6b4fa' + data: 0x... + nonce: '60' + value: '' + signature: >- + 0x01a060c734d7bdf4adde50c4a7e574036b1f8b12890911bdd1c1cfdcd77502381b89fa8a47c36f62a0b9f1cdfee7b260fd8108536db9f6b2089c02637e7de9fc20 + state: STATE_CONFIRMED + type: SAFE + owner: '0x6e0c80c90ea6c15917308f820eac91ce2724b5b5' + metadata: '' + createdAt: '2024-07-14T21:13:08.819782Z' + updatedAt: '2024-07-14T21:13:46.576639Z' + - transactionID: 0190a792-b5be-7cad-9eae-9941f2b47ebf + transactionHash: >- + 0x0b2ff276b65382fc5593cdd965168c878006684a7fc8d2d011eddeddccd87335 + from: '0x6e0c80c90ea6c15917308f820eac91ce2724b5b5' + to: '0x2791bca1f2de4661ed88a30c99a7a9449aa84174' + proxyAddress: '0x6d8c4e9adf5748af82dabe2c6225207770d6b4fa' + data: 0x... + nonce: '58' + value: '' + signature: >- + 0x9d99a48b6552183dc44018dbbab0e196fa59511e5661b961416e93138870814f3c474367362524ccc6865a8558f2543cc8e1b2e7336e39e6cdb4ad6f09d0db6a20 + state: STATE_CONFIRMED + type: SAFE + owner: '0x6e0c80c90ea6c15917308f820eac91ce2724b5b5' + metadata: '' + createdAt: '2024-07-12T15:32:08.254831Z' + updatedAt: '2024-07-12T15:32:45.265257Z' + '401': + description: Unauthorized - Invalid authentication + content: + application/json: + schema: + $ref: '#/components/schemas/ErrorResponse' + example: + error: invalid authorization + '500': + description: Server Error + content: + application/json: + schema: + $ref: '#/components/schemas/ErrorResponse' + example: + error: internal server error +components: + schemas: + Address: + type: string + description: Ethereum address (0x-prefixed, 40 hex chars) + pattern: ^0x[a-fA-F0-9]{40}$ + example: '0x6e0c80c90ea6c15917308F820Eac91Ce2724B5b5' + RelayerTransaction: + type: object + properties: + transactionID: + type: string + description: Unique identifier for the transaction + example: 0190b317-a1d3-7bec-9b91-eeb6dcd3a620 + transactionHash: + type: string + description: Onchain transaction hash (available once confirmed) + example: '0x38cbfbeae8fffa4e2b187ee5978d3ee9cafc53af0363ed90a35b7ea9016535d8' + from: + $ref: '#/components/schemas/Address' + description: Signer address + example: '0x6e0c80c90ea6c15917308f820eac91ce2724b5b5' + to: + $ref: '#/components/schemas/Address' + description: Target contract address + example: '0x2791bca1f2de4661ed88a30c99a7a9449aa84174' + proxyAddress: + $ref: '#/components/schemas/Address' + description: User's Polymarket proxy wallet address + example: '0x6d8c4e9adf5748af82dabe2c6225207770d6b4fa' + data: + type: string + description: Encoded transaction data (0x-prefixed hex string) + example: 0x... + nonce: + type: string + description: Transaction nonce + example: '60' + value: + type: string + description: Transaction value + example: '' + signature: + type: string + description: Transaction signature (0x-prefixed hex string) + example: >- + 0x01a060c734d7bdf4adde50c4a7e574036b1f8b12890911bdd1c1cfdcd77502381b89fa8a47c36f62a0b9f1cdfee7b260fd8108536db9f6b2089c02637e7de9fc20 + state: + type: string + description: Current state of the transaction + enum: + - STATE_NEW + - STATE_EXECUTED + - STATE_MINED + - STATE_CONFIRMED + - STATE_INVALID + - STATE_FAILED + example: STATE_CONFIRMED + type: + type: string + description: Transaction type + enum: + - SAFE + - PROXY + example: SAFE + owner: + $ref: '#/components/schemas/Address' + description: Owner address + example: '0x6e0c80c90ea6c15917308f820eac91ce2724b5b5' + metadata: + type: string + description: Transaction metadata + example: '' + createdAt: + type: string + format: date-time + description: Timestamp when the transaction was created + example: '2024-07-14T21:13:08.819782Z' + updatedAt: + type: string + format: date-time + description: Timestamp when the transaction was last updated + example: '2024-07-14T21:13:46.576639Z' + ErrorResponse: + type: object + properties: + error: + type: string + required: + - error + +```` \ No newline at end of file diff --git a/PolymarketDocumentation-main/docs/api-reference/relayer/get-relayer-address-and-nonce.md b/PolymarketDocumentation-main/docs/api-reference/relayer/get-relayer-address-and-nonce.md new file mode 100644 index 00000000..44b7e4b6 --- /dev/null +++ b/PolymarketDocumentation-main/docs/api-reference/relayer/get-relayer-address-and-nonce.md @@ -0,0 +1,126 @@ +> ## Documentation Index +> Fetch the complete documentation index at: https://docs.polymarket.com/llms.txt +> Use this file to discover all available pages before exploring further. + +# Get relayer address and nonce + +> Fetches the relayer address and nonce for a specific user. Takes in the user's signer address and the type of nonce to retrieve. + + + + +## OpenAPI + +````yaml /api-spec/relayer-openapi.yaml get /relay-payload +openapi: 3.0.3 +info: + title: Polymarket Relayer API + version: 1.0.0 + description: HTTP API for the Polymarket Relayer. Submit and track gasless transactions. +servers: + - url: https://relayer-v2.polymarket.com + description: Polymarket Relayer API +security: [] +tags: + - name: Relayer + description: Relayer transaction operations + - name: Relayer API Keys + description: > + Relayer API keys let a user authenticate requests to relayer endpoints + without Gamma auth. + + However, Relayer API keys can only be created using Gamma auth. Every + address can create a maximum of 100 keys. + + + The API key auth headers are: + + - `RELAYER_API_KEY` + + - `RELAYER_API_KEY_ADDRESS` + + + `RELAYER_API_KEY_ADDRESS` must match the address that owns the key. +paths: + /relay-payload: + get: + tags: + - Relayer + summary: Get relayer address and nonce + description: > + Fetches the relayer address and nonce for a specific user. Takes in the + user's signer address and the type of nonce to retrieve. + parameters: + - name: address + in: query + required: true + description: User's signer address + schema: + $ref: '#/components/schemas/Address' + example: '0x77837466dd64fb52ECD00C737F060d0ff5CCB575' + - name: type + in: query + required: true + description: Type of nonce to retrieve + schema: + type: string + enum: + - PROXY + - SAFE + example: PROXY + responses: + '200': + description: Relay payload retrieved successfully + content: + application/json: + schema: + $ref: '#/components/schemas/RelayPayloadResponse' + example: + address: '0x4da9395388791c22684e03779c3de10934eb9cfb' + nonce: '31' + '400': + description: Bad Request - Missing or invalid query parameters + content: + application/json: + schema: + $ref: '#/components/schemas/ErrorResponse' + examples: + invalidAddress: + value: + error: invalid address + invalidType: + value: + error: invalid type + '500': + description: Server Error + content: + application/json: + schema: + $ref: '#/components/schemas/ErrorResponse' +components: + schemas: + Address: + type: string + description: Ethereum address (0x-prefixed, 40 hex chars) + pattern: ^0x[a-fA-F0-9]{40}$ + example: '0x6e0c80c90ea6c15917308F820Eac91Ce2724B5b5' + RelayPayloadResponse: + type: object + properties: + address: + $ref: '#/components/schemas/Address' + description: Relayer address + example: '0x4da9395388791c22684e03779c3de10934eb9cfb' + nonce: + type: string + description: Current nonce value + example: '31' + ErrorResponse: + type: object + properties: + error: + type: string + required: + - error + +```` \ No newline at end of file diff --git a/PolymarketDocumentation-main/docs/api-reference/relayer/submit-a-transaction.md b/PolymarketDocumentation-main/docs/api-reference/relayer/submit-a-transaction.md new file mode 100644 index 00000000..a06a98dc --- /dev/null +++ b/PolymarketDocumentation-main/docs/api-reference/relayer/submit-a-transaction.md @@ -0,0 +1,296 @@ +> ## Documentation Index +> Fetch the complete documentation index at: https://docs.polymarket.com/llms.txt +> Use this file to discover all available pages before exploring further. + +# Submit a transaction + +> Submit a transaction request to the Relayer. Authenticated using Builder API Keys or Relayer API Keys. + +Returns immediately with the `transactionID` and a `state` of `STATE_NEW`. The onchain transaction hash is **not** included in this response — poll `GET /transaction` with the returned `transactionID` to retrieve the `transactionHash` once the transaction has been broadcast. + +**Builder API Key auth headers:** +- `POLY_BUILDER_API_KEY` +- `POLY_BUILDER_TIMESTAMP` +- `POLY_BUILDER_PASSPHRASE` +- `POLY_BUILDER_SIGNATURE` + +**Relayer API Key auth headers:** +- `RELAYER_API_KEY` +- `RELAYER_API_KEY_ADDRESS` + + + + +## OpenAPI + +````yaml /api-spec/relayer-openapi.yaml post /submit +openapi: 3.0.3 +info: + title: Polymarket Relayer API + version: 1.0.0 + description: HTTP API for the Polymarket Relayer. Submit and track gasless transactions. +servers: + - url: https://relayer-v2.polymarket.com + description: Polymarket Relayer API +security: [] +tags: + - name: Relayer + description: Relayer transaction operations + - name: Relayer API Keys + description: > + Relayer API keys let a user authenticate requests to relayer endpoints + without Gamma auth. + + However, Relayer API keys can only be created using Gamma auth. Every + address can create a maximum of 100 keys. + + + The API key auth headers are: + + - `RELAYER_API_KEY` + + - `RELAYER_API_KEY_ADDRESS` + + + `RELAYER_API_KEY_ADDRESS` must match the address that owns the key. +paths: + /submit: + post: + tags: + - Relayer + summary: Submit a transaction + description: > + Submit a transaction request to the Relayer. Authenticated using Builder + API Keys or Relayer API Keys. + + + Returns immediately with the `transactionID` and a `state` of + `STATE_NEW`. The onchain transaction hash is **not** included in this + response — poll `GET /transaction` with the returned `transactionID` to + retrieve the `transactionHash` once the transaction has been broadcast. + + + **Builder API Key auth headers:** + + - `POLY_BUILDER_API_KEY` + + - `POLY_BUILDER_TIMESTAMP` + + - `POLY_BUILDER_PASSPHRASE` + + - `POLY_BUILDER_SIGNATURE` + + + **Relayer API Key auth headers:** + + - `RELAYER_API_KEY` + + - `RELAYER_API_KEY_ADDRESS` + parameters: + - name: POLY_BUILDER_API_KEY + in: header + required: false + description: Builder API key (when using Builder API Key auth) + schema: + type: string + - name: POLY_BUILDER_TIMESTAMP + in: header + required: false + description: Unix timestamp (when using Builder API Key auth) + schema: + type: string + - name: POLY_BUILDER_PASSPHRASE + in: header + required: false + description: Builder passphrase (when using Builder API Key auth) + schema: + type: string + - name: POLY_BUILDER_SIGNATURE + in: header + required: false + description: HMAC-SHA256 signature (when using Builder API Key auth) + schema: + type: string + - name: RELAYER_API_KEY + in: header + required: false + description: Relayer API key (when using Relayer API Key auth) + schema: + type: string + - name: RELAYER_API_KEY_ADDRESS + in: header + required: false + description: Address that owns the key (when using Relayer API Key auth) + schema: + $ref: '#/components/schemas/Address' + requestBody: + required: true + content: + application/json: + schema: + $ref: '#/components/schemas/SubmitRequest' + example: + from: '0x6e0c80c90ea6c15917308F820Eac91Ce2724B5b5' + to: '0xC011a7E12a19f7B1f670d46F03B03f3342E82DFB' + proxyWallet: '0x6d8c4e9aDF5748Af82Dabe2C6225207770d6B4fa' + data: 0x... + nonce: '60' + signature: >- + 0x01a060c734d7bdf4adde50c4a7e574036b1f8b12890911bdd1c1cfdcd77502381b89fa8a47c36f62a0b9f1cdfee7b260fd8108536db9f6b2089c02637e7de9fc20 + signatureParams: + gasPrice: '0' + operation: '0' + safeTxnGas: '0' + baseGas: '0' + gasToken: '0x0000000000000000000000000000000000000000' + refundReceiver: '0x0000000000000000000000000000000000000000' + type: SAFE + responses: + '200': + description: Transaction submitted successfully + content: + application/json: + schema: + $ref: '#/components/schemas/SubmitResponse' + example: + transactionID: 0190b317-a1d3-7bec-9b91-eeb6dcd3a620 + state: STATE_NEW + '400': + description: Bad Request - Invalid transaction payload, fields, or signature + content: + application/json: + schema: + $ref: '#/components/schemas/ErrorResponse' + examples: + invalidPayload: + value: + error: invalid transaction request payload + validationError: + value: + error: bad request + '401': + description: Unauthorized - Invalid authentication + content: + application/json: + schema: + $ref: '#/components/schemas/ErrorResponse' + example: + error: invalid authorization + '429': + description: Too Many Requests - Quota exceeded + content: + application/json: + schema: + $ref: '#/components/schemas/ErrorResponse' + example: + error: quota exceeded + '500': + description: Server Error + content: + application/json: + schema: + $ref: '#/components/schemas/ErrorResponse' + examples: + internalError: + value: + error: internal error + serverError: + value: + error: internal server error +components: + schemas: + Address: + type: string + description: Ethereum address (0x-prefixed, 40 hex chars) + pattern: ^0x[a-fA-F0-9]{40}$ + example: '0x6e0c80c90ea6c15917308F820Eac91Ce2724B5b5' + SubmitRequest: + type: object + required: + - from + - to + - proxyWallet + - data + - nonce + - signature + - signatureParams + - type + properties: + from: + $ref: '#/components/schemas/Address' + description: Signer address + to: + $ref: '#/components/schemas/Address' + description: Target contract address + proxyWallet: + $ref: '#/components/schemas/Address' + description: User's Polymarket proxy wallet address + data: + type: string + description: Encoded transaction data (0x-prefixed hex string) + example: 0x... + nonce: + type: string + description: Transaction nonce + example: '60' + signature: + type: string + description: Transaction signature (0x-prefixed hex string) + example: >- + 0x01a060c734d7bdf4adde50c4a7e574036b1f8b12890911bdd1c1cfdcd77502381b89fa8a47c36f62a0b9f1cdfee7b260fd8108536db9f6b2089c02637e7de9fc20 + signatureParams: + $ref: '#/components/schemas/SignatureParams' + type: + type: string + description: Transaction type + enum: + - SAFE + - PROXY + example: SAFE + SubmitResponse: + type: object + properties: + transactionID: + type: string + description: Unique identifier for the submitted transaction + example: 0190b317-a1d3-7bec-9b91-eeb6dcd3a620 + state: + type: string + description: Current state of the transaction + example: STATE_NEW + ErrorResponse: + type: object + properties: + error: + type: string + required: + - error + SignatureParams: + type: object + properties: + gasPrice: + type: string + description: Gas price + example: '0' + operation: + type: string + description: Operation type + example: '0' + safeTxnGas: + type: string + description: Safe transaction gas + example: '0' + baseGas: + type: string + description: Base gas + example: '0' + gasToken: + $ref: '#/components/schemas/Address' + description: Gas token address + example: '0x0000000000000000000000000000000000000000' + refundReceiver: + $ref: '#/components/schemas/Address' + description: Refund receiver address + example: '0x0000000000000000000000000000000000000000' + +```` \ No newline at end of file diff --git a/PolymarketDocumentation-main/docs/api-reference/rewards/get-current-active-rewards-configurations.md b/PolymarketDocumentation-main/docs/api-reference/rewards/get-current-active-rewards-configurations.md new file mode 100644 index 00000000..3c9a315d --- /dev/null +++ b/PolymarketDocumentation-main/docs/api-reference/rewards/get-current-active-rewards-configurations.md @@ -0,0 +1,233 @@ +> ## Documentation Index +> Fetch the complete documentation index at: https://docs.polymarket.com/llms.txt +> Use this file to discover all available pages before exploring further. + +# Get current active rewards configurations + +> Returns all current active rewards configurations grouped by market. + +When `sponsored=true`, returns sponsored reward configurations instead. + +Results are paginated (500 items per page). Use next_cursor to fetch subsequent pages. +A next_cursor value of "LTE=" indicates the last page. + + + + +## OpenAPI + +````yaml /api-spec/clob-openapi.yaml get /rewards/markets/current +openapi: 3.1.0 +info: + title: Polymarket CLOB API + description: Polymarket CLOB API Reference + license: + name: MIT + identifier: MIT + version: 1.0.0 +servers: + - url: https://clob.polymarket.com + description: Production CLOB API + - url: https://clob-staging.polymarket.com + description: Staging CLOB API +security: [] +tags: + - name: Trade + description: Trade endpoints + - name: Markets + description: Market data endpoints + - name: Account + description: Account and authentication endpoints + - name: Notifications + description: User notification endpoints + - name: Rewards + description: Rewards and earnings endpoints + - name: Rebates + description: Maker rebate endpoints +paths: + /rewards/markets/current: + get: + tags: + - Rewards + summary: Get current active rewards configurations + description: > + Returns all current active rewards configurations grouped by market. + + + When `sponsored=true`, returns sponsored reward configurations instead. + + + Results are paginated (500 items per page). Use next_cursor to fetch + subsequent pages. + + A next_cursor value of "LTE=" indicates the last page. + operationId: getCurrentRewards + parameters: + - name: sponsored + in: query + description: >- + If true, returns sponsored reward configurations instead of standard + ones + required: false + schema: + type: boolean + default: false + - name: next_cursor + in: query + description: Pagination cursor from previous response + required: false + schema: + type: string + responses: + '200': + description: Successfully retrieved current rewards configurations + content: + application/json: + schema: + $ref: '#/components/schemas/PaginatedCurrentReward' + example: + limit: 500 + count: 1 + next_cursor: LTE= + data: + - condition_id: >- + 0xbd31dc8a20211944f6b70f31557f1001557b59905b7738480ca09bd4532f84af + rewards_max_spread: 99 + rewards_min_size: 10 + rewards_config: + - id: 0 + asset_address: '0x9c4E1703476E875070EE25b56A58B008CFb8FA78' + start_date: '2024-03-01' + end_date: '2500-12-31' + rate_per_day: 2 + total_rewards: 92 + - id: 0 + asset_address: '0x69308FB512518e39F9b16112fA8d994F4e2Bf8bB' + start_date: '2024-03-01' + end_date: '2500-12-31' + rate_per_day: 1 + total_rewards: 46 + sponsored_daily_rate: 0.5 + sponsors_count: 2 + native_daily_rate: 2.5 + total_daily_rate: 3 + '400': + description: Bad request - Invalid next_cursor + content: + application/json: + schema: + $ref: '#/components/schemas/ErrorResponse' + example: + error: Invalid next_cursor + '500': + description: Internal server error + content: + application/json: + schema: + $ref: '#/components/schemas/ErrorResponse' + example: + error: Internal server error +components: + schemas: + PaginatedCurrentReward: + type: object + description: Paginated list of current reward configurations + properties: + limit: + type: integer + description: Maximum number of items per page + count: + type: integer + description: Number of items in the current response + next_cursor: + type: string + description: Cursor for the next page. "LTE=" indicates the last page. + data: + type: array + items: + $ref: '#/components/schemas/CurrentReward' + required: + - limit + - count + - next_cursor + - data + ErrorResponse: + type: object + required: + - error + properties: + error: + type: string + description: Error message + code: + type: string + description: Machine-readable error code, when provided + retry_after_seconds: + type: integer + description: Number of seconds to wait before retrying, when provided + CurrentReward: + type: object + description: Current active reward configuration for a market + properties: + condition_id: + type: string + description: Condition ID of the market + rewards_max_spread: + type: number + description: Maximum spread for rewards eligibility + rewards_min_size: + type: number + description: Minimum order size for rewards eligibility + rewards_config: + type: array + items: + $ref: '#/components/schemas/CurrentRewardConfig' + sponsored_daily_rate: + type: number + format: double + description: Sponsored daily rate (omitted when zero) + sponsors_count: + type: integer + description: Number of sponsors (omitted when zero) + native_daily_rate: + type: number + format: double + description: Computed native daily rate excluding sponsors (omitted when zero) + total_daily_rate: + type: number + format: double + description: Computed total daily rate including sponsors (omitted when zero) + required: + - condition_id + CurrentRewardConfig: + type: object + description: Reward configuration entry for a current rewards market + properties: + id: + type: integer + description: Rewards config ID (always 0 on /rewards/markets/current) + asset_address: + type: string + description: Address of the reward asset + start_date: + type: string + format: date + description: Start date of the rewards period + end_date: + type: string + format: date + description: End date of the rewards period + rate_per_day: + type: number + format: double + description: Daily reward rate + total_rewards: + type: number + format: double + description: Total rewards amount + required: + - asset_address + - start_date + - rate_per_day + +```` \ No newline at end of file diff --git a/PolymarketDocumentation-main/docs/api-reference/rewards/get-earnings-for-user-by-date.md b/PolymarketDocumentation-main/docs/api-reference/rewards/get-earnings-for-user-by-date.md new file mode 100644 index 00000000..3c537504 --- /dev/null +++ b/PolymarketDocumentation-main/docs/api-reference/rewards/get-earnings-for-user-by-date.md @@ -0,0 +1,264 @@ +> ## Documentation Index +> Fetch the complete documentation index at: https://docs.polymarket.com/llms.txt +> Use this file to discover all available pages before exploring further. + +# Get earnings for user by date + +> Returns an array of user earnings per market for a provided day. + +Requires CLOB L2 Auth headers. + +Results are paginated (100 items per page). Use next_cursor to fetch subsequent pages. +A next_cursor value of "LTE=" indicates the last page. + + + + +## OpenAPI + +````yaml /api-spec/clob-openapi.yaml get /rewards/user +openapi: 3.1.0 +info: + title: Polymarket CLOB API + description: Polymarket CLOB API Reference + license: + name: MIT + identifier: MIT + version: 1.0.0 +servers: + - url: https://clob.polymarket.com + description: Production CLOB API + - url: https://clob-staging.polymarket.com + description: Staging CLOB API +security: [] +tags: + - name: Trade + description: Trade endpoints + - name: Markets + description: Market data endpoints + - name: Account + description: Account and authentication endpoints + - name: Notifications + description: User notification endpoints + - name: Rewards + description: Rewards and earnings endpoints + - name: Rebates + description: Maker rebate endpoints +paths: + /rewards/user: + get: + tags: + - Rewards + summary: Get earnings for user by date + description: > + Returns an array of user earnings per market for a provided day. + + + Requires CLOB L2 Auth headers. + + + Results are paginated (100 items per page). Use next_cursor to fetch + subsequent pages. + + A next_cursor value of "LTE=" indicates the last page. + operationId: getEarningsForUserForDay + parameters: + - name: date + in: query + description: Date in YYYY-MM-DD format + required: true + schema: + type: string + format: date + example: '2024-03-26' + - name: signature_type + in: query + description: | + Signature type for address derivation (required for API KEY auth): + - 0: EOA + - 1: POLY_PROXY + - 2: POLY_GNOSIS_SAFE + required: false + schema: + type: integer + enum: + - 0 + - 1 + - 2 + - name: maker_address + in: query + description: Maker address to query earnings for + required: false + schema: + type: string + example: '0xFeA4cB3dD4ca7CefD3368653B7D6FF9BcDFca604' + - name: sponsored + in: query + description: If true, returns sponsored-only earnings + required: false + schema: + type: boolean + default: false + - name: next_cursor + in: query + description: Pagination cursor from previous response + required: false + schema: + type: string + responses: + '200': + description: Successfully retrieved user earnings + content: + application/json: + schema: + $ref: '#/components/schemas/PaginatedUserEarnings' + example: + limit: 100 + count: 1 + next_cursor: LTE= + data: + - date: '2024-03-26T00:00:00Z' + condition_id: >- + 0xbd31dc8a20211944f6b70f31557f1001557b59905b7738480ca09bd4532f84af + asset_address: '0x9c4E1703476E875070EE25b56A58B008CFb8FA78' + maker_address: '0xFeA4cB3dD4ca7CefD3368653B7D6FF9BcDFca604' + earnings: 0.237519 + asset_rate: 1 + '400': + description: Bad request - Invalid parameters + content: + application/json: + schema: + $ref: '#/components/schemas/ErrorResponse' + examples: + invalid_date: + summary: Invalid date format + value: + error: 'Invalid date (format: YYYY-MM-DD)' + invalid_signature_type: + summary: Invalid signature type + value: + error: Invalid signature_type + invalid_maker_address: + summary: Invalid maker address + value: + error: Invalid maker_address + '401': + description: Unauthorized - Invalid API key or authentication failed + content: + application/json: + schema: + $ref: '#/components/schemas/ErrorResponse' + example: + error: Invalid API key + '500': + description: Internal server error + content: + application/json: + schema: + $ref: '#/components/schemas/ErrorResponse' + example: + error: Internal server error + security: + - polyApiKey: [] + polyAddress: [] + polySignature: [] + polyPassphrase: [] + polyTimestamp: [] +components: + schemas: + PaginatedUserEarnings: + type: object + description: Paginated list of user earnings + properties: + limit: + type: integer + description: Maximum number of items per page + count: + type: integer + description: Number of items in the current response + next_cursor: + type: string + description: Cursor for the next page. "LTE=" indicates the last page. + data: + type: array + items: + $ref: '#/components/schemas/UserEarning' + required: + - limit + - count + - next_cursor + - data + ErrorResponse: + type: object + required: + - error + properties: + error: + type: string + description: Error message + code: + type: string + description: Machine-readable error code, when provided + retry_after_seconds: + type: integer + description: Number of seconds to wait before retrying, when provided + UserEarning: + type: object + description: User earnings for a specific market on a given day + properties: + date: + type: string + format: date-time + description: Date of the earnings + condition_id: + type: string + description: Condition ID of the market + asset_address: + type: string + description: Address of the reward asset + maker_address: + type: string + description: Address of the maker + earnings: + type: number + format: double + description: Amount of earnings in the asset + asset_rate: + type: number + format: double + description: Exchange rate of the asset + required: + - date + - condition_id + - asset_address + - maker_address + - earnings + securitySchemes: + polyApiKey: + type: apiKey + in: header + name: POLY_API_KEY + description: Your API key + polyAddress: + type: apiKey + in: header + name: POLY_ADDRESS + description: Ethereum address associated with the API key + polySignature: + type: apiKey + in: header + name: POLY_SIGNATURE + description: HMAC signature of the request + polyPassphrase: + type: apiKey + in: header + name: POLY_PASSPHRASE + description: API key passphrase + polyTimestamp: + type: apiKey + in: header + name: POLY_TIMESTAMP + description: Unix timestamp of the request + +```` \ No newline at end of file diff --git a/PolymarketDocumentation-main/docs/api-reference/rewards/get-multiple-markets-with-rewards.md b/PolymarketDocumentation-main/docs/api-reference/rewards/get-multiple-markets-with-rewards.md new file mode 100644 index 00000000..572a0cea --- /dev/null +++ b/PolymarketDocumentation-main/docs/api-reference/rewards/get-multiple-markets-with-rewards.md @@ -0,0 +1,413 @@ +> ## Documentation Index +> Fetch the complete documentation index at: https://docs.polymarket.com/llms.txt +> Use this file to discover all available pages before exploring further. + +# Get multiple markets with rewards + +> Returns a list of active markets with their reward configurations. +Supports text search, tag filtering, numeric filters, and sorting. + +Results are paginated (100 items per page by default). Use next_cursor to fetch subsequent pages. +A next_cursor value of "LTE=" indicates the last page. + + + + +## OpenAPI + +````yaml /api-spec/clob-openapi.yaml get /rewards/markets/multi +openapi: 3.1.0 +info: + title: Polymarket CLOB API + description: Polymarket CLOB API Reference + license: + name: MIT + identifier: MIT + version: 1.0.0 +servers: + - url: https://clob.polymarket.com + description: Production CLOB API + - url: https://clob-staging.polymarket.com + description: Staging CLOB API +security: [] +tags: + - name: Trade + description: Trade endpoints + - name: Markets + description: Market data endpoints + - name: Account + description: Account and authentication endpoints + - name: Notifications + description: User notification endpoints + - name: Rewards + description: Rewards and earnings endpoints + - name: Rebates + description: Maker rebate endpoints +paths: + /rewards/markets/multi: + get: + tags: + - Rewards + summary: Get multiple markets with rewards + description: > + Returns a list of active markets with their reward configurations. + + Supports text search, tag filtering, numeric filters, and sorting. + + + Results are paginated (100 items per page by default). Use next_cursor + to fetch subsequent pages. + + A next_cursor value of "LTE=" indicates the last page. + operationId: getMultiMarkets + parameters: + - name: q + in: query + description: Text search on market question/description + required: false + schema: + type: string + - name: tag_slug + in: query + description: >- + Filter by tag slug. Can be repeated for OR logic (e.g., + ?tag_slug=sports&tag_slug=politics) + required: false + schema: + type: string + - name: event_id + in: query + description: >- + Filter by event ID. Can be repeated for multiple events (e.g., + ?event_id=100&event_id=200) + required: false + schema: + type: string + - name: event_title + in: query + description: Search event titles using case-insensitive pattern matching + required: false + schema: + type: string + - name: order_by + in: query + description: Field to sort results by + required: false + schema: + type: string + enum: + - market_id + - created_at + - volume_24hr + - spread + - competitiveness + - max_spread + - min_size + - question + - one_day_price_change + - rate_per_day + - price + - end_date + - start_date + - reward_end_date + - name: position + in: query + description: Sort direction + required: false + schema: + type: string + enum: + - ASC + - DESC + - name: min_volume_24hr + in: query + description: Minimum 24-hour volume filter + required: false + schema: + type: number + format: double + - name: max_volume_24hr + in: query + description: Maximum 24-hour volume filter + required: false + schema: + type: number + format: double + - name: min_spread + in: query + description: Minimum spread filter + required: false + schema: + type: number + format: double + - name: max_spread + in: query + description: Maximum spread filter + required: false + schema: + type: number + format: double + - name: min_price + in: query + description: Minimum first token price filter + required: false + schema: + type: number + format: double + - name: max_price + in: query + description: Maximum first token price filter + required: false + schema: + type: number + format: double + - name: next_cursor + in: query + description: Pagination cursor from previous response + required: false + schema: + type: string + - name: page_size + in: query + description: Number of items per page (max 500, values above are capped) + required: false + schema: + type: integer + default: 100 + maximum: 500 + responses: + '200': + description: Successfully retrieved markets with rewards + content: + application/json: + schema: + $ref: '#/components/schemas/PaginatedMultiMarketInfo' + example: + limit: 50 + count: 1 + next_cursor: NQ== + data: + - condition_id: >- + 0xbd31dc8a20211944f6b70f31557f1001557b59905b7738480ca09bd4532f84af + event_id: '12345' + event_slug: 2024-us-election + created_at: '2024-05-01T12:00:00Z' + group_item_title: '' + image: https://example.com/image.png + market_competitiveness: 0.42 + market_id: '248849' + market_slug: will-trump-win-the-2024-iowa-caucus + one_day_price_change: 0.03 + question: Will Trump win the 2024 Iowa Caucus? + rewards_max_spread: 99 + rewards_min_size: 10 + spread: 0.12 + end_date: '2024-08-10 00:00:00' + tokens: + - token_id: >- + 1343197538147866997676250008839231694243646439454152539053893078719042421992 + outcome: 'YES' + price: 0.8 + - token_id: >- + 16678291189211314787145083999015737376658799626183230671758641503291735614088 + outcome: 'NO' + price: 0.2 + volume_24hr: 12345.67 + rewards_config: + - id: 7 + asset_address: '0x9c4E1703476E875070EE25b56A58B008CFb8FA78' + start_date: '2024-03-01' + end_date: '2500-12-31' + rate_per_day: 2 + total_rewards: 92 + '400': + description: Bad request - Invalid parameters + content: + application/json: + schema: + $ref: '#/components/schemas/ErrorResponse' + examples: + invalid_order_by: + summary: Invalid order_by value + value: + error: Invalid order_by + invalid_position: + summary: Invalid position value + value: + error: Invalid position + invalid_cursor: + summary: Invalid pagination cursor + value: + error: Invalid next_cursor + '500': + description: Internal server error + content: + application/json: + schema: + $ref: '#/components/schemas/ErrorResponse' + example: + error: Internal server error +components: + schemas: + PaginatedMultiMarketInfo: + type: object + description: Paginated list of markets with rewards and trading metrics + properties: + limit: + type: integer + description: Maximum number of items per page + count: + type: integer + description: Number of items in the current response + next_cursor: + type: string + description: Cursor for the next page. "LTE=" indicates the last page. + data: + type: array + items: + $ref: '#/components/schemas/MultiMarketInfo' + required: + - limit + - count + - next_cursor + - data + ErrorResponse: + type: object + required: + - error + properties: + error: + type: string + description: Error message + code: + type: string + description: Machine-readable error code, when provided + retry_after_seconds: + type: integer + description: Number of seconds to wait before retrying, when provided + MultiMarketInfo: + type: object + description: Market with rewards configuration and trading metrics + properties: + condition_id: + type: string + description: Condition ID of the market + event_id: + type: string + description: Event ID + event_slug: + type: string + description: URL slug for the event + created_at: + type: string + format: date-time + description: Market creation timestamp + group_item_title: + type: string + description: Title within an event group + image: + type: string + description: URL to market image + market_competitiveness: + type: number + format: double + description: Competitiveness score of the market + market_id: + type: string + description: Market ID + market_slug: + type: string + description: URL slug for the market + one_day_price_change: + type: number + format: double + description: Price change over the last 24 hours + question: + type: string + description: Market question + rewards_max_spread: + type: number + description: Maximum spread for rewards eligibility + rewards_min_size: + type: number + description: Minimum order size for rewards eligibility + spread: + type: number + format: double + description: Current spread + end_date: + type: string + description: Market end date + tokens: + type: array + items: + $ref: '#/components/schemas/RewardsToken' + volume_24hr: + type: number + format: double + description: 24-hour trading volume + rewards_config: + type: array + items: + $ref: '#/components/schemas/RewardsConfig' + required: + - condition_id + - market_id + - question + - tokens + RewardsToken: + type: object + description: Token information for rewards markets + properties: + token_id: + type: string + description: Token ID + outcome: + type: string + description: Outcome name (e.g., "YES", "NO") + price: + type: number + format: double + description: Current price of the token + required: + - token_id + - outcome + RewardsConfig: + type: object + description: Rewards configuration for a market + properties: + id: + type: integer + description: Rewards config ID + asset_address: + type: string + description: Address of the reward asset + start_date: + type: string + format: date + description: Start date of the rewards period + end_date: + type: string + format: date + description: End date of the rewards period + rate_per_day: + type: number + format: double + description: Daily reward rate + total_rewards: + type: number + format: double + description: Total rewards amount + remaining_reward_amount: + type: number + format: double + description: Remaining reward amount + total_days: + type: integer + description: Total number of days in the rewards period + required: + - asset_address + - start_date + - rate_per_day + +```` \ No newline at end of file diff --git a/PolymarketDocumentation-main/docs/api-reference/rewards/get-raw-rewards-for-a-specific-market.md b/PolymarketDocumentation-main/docs/api-reference/rewards/get-raw-rewards-for-a-specific-market.md new file mode 100644 index 00000000..5b91a1aa --- /dev/null +++ b/PolymarketDocumentation-main/docs/api-reference/rewards/get-raw-rewards-for-a-specific-market.md @@ -0,0 +1,293 @@ +> ## Documentation Index +> Fetch the complete documentation index at: https://docs.polymarket.com/llms.txt +> Use this file to discover all available pages before exploring further. + +# Get raw rewards for a specific market + +> Returns an array of present and future rewards configured on a market. + +When `sponsored=true`, sponsored daily rates are folded into each config's +`rate_per_day` . + +Results are paginated (100 items per page). Use next_cursor to fetch subsequent pages. +A next_cursor value of "LTE=" indicates the last page. + + + + +## OpenAPI + +````yaml /api-spec/clob-openapi.yaml get /rewards/markets/{condition_id} +openapi: 3.1.0 +info: + title: Polymarket CLOB API + description: Polymarket CLOB API Reference + license: + name: MIT + identifier: MIT + version: 1.0.0 +servers: + - url: https://clob.polymarket.com + description: Production CLOB API + - url: https://clob-staging.polymarket.com + description: Staging CLOB API +security: [] +tags: + - name: Trade + description: Trade endpoints + - name: Markets + description: Market data endpoints + - name: Account + description: Account and authentication endpoints + - name: Notifications + description: User notification endpoints + - name: Rewards + description: Rewards and earnings endpoints + - name: Rebates + description: Maker rebate endpoints +paths: + /rewards/markets/{condition_id}: + get: + tags: + - Rewards + summary: Get raw rewards for a specific market + description: > + Returns an array of present and future rewards configured on a market. + + + When `sponsored=true`, sponsored daily rates are folded into each + config's + + `rate_per_day` . + + + Results are paginated (100 items per page). Use next_cursor to fetch + subsequent pages. + + A next_cursor value of "LTE=" indicates the last page. + operationId: getRawRewardsForMarket + parameters: + - name: condition_id + in: path + required: true + description: The condition ID of the market + schema: + type: string + example: '0xbd31dc8a20211944f6b70f31557f1001557b59905b7738480ca09bd4532f84af' + - name: sponsored + in: query + description: If true, folds sponsored daily rates into each config's rate_per_day + required: false + schema: + type: boolean + default: false + - name: next_cursor + in: query + description: Pagination cursor from previous response + required: false + schema: + type: string + responses: + '200': + description: Successfully retrieved rewards for market + content: + application/json: + schema: + $ref: '#/components/schemas/PaginatedMarketReward' + example: + limit: 100 + count: 1 + next_cursor: LTE= + data: + - condition_id: >- + 0xbd31dc8a20211944f6b70f31557f1001557b59905b7738480ca09bd4532f84af + question: Will Trump win the 2024 Iowa Caucus? + market_slug: will-trump-win-the-2024-iowa-caucus + event_slug: will-trump-win-the-2024-iowa-caucus + image: >- + https://polymarket-upload.s3.us-east-2.amazonaws.com/trump1+copy.png + rewards_max_spread: 99 + rewards_min_size: 10 + market_competitiveness: 0.42 + tokens: + - token_id: >- + 1343197538147866997676250008839231694243646439454152539053893078719042421992 + outcome: 'YES' + price: 0.8 + - token_id: >- + 16678291189211314787145083999015737376658799626183230671758641503291735614088 + outcome: 'NO' + price: 0.2 + rewards_config: + - id: 1 + asset_address: '0x9c4E1703476E875070EE25b56A58B008CFb8FA78' + start_date: '2024-03-01' + end_date: '2500-12-31' + rate_per_day: 0.25 + total_rewards: 0 + total_days: 174161 + - id: 2 + asset_address: '0x9c4E1703476E875070EE25b56A58B008CFb8FA78' + start_date: '2024-03-01' + end_date: '2024-05-31' + rate_per_day: 1 + total_rewards: 92 + total_days: 92 + '400': + description: Bad request - Invalid market or next_cursor + content: + application/json: + schema: + $ref: '#/components/schemas/ErrorResponse' + examples: + invalid_market: + summary: Empty condition ID + value: + error: Invalid market + invalid_cursor: + summary: Invalid pagination cursor + value: + error: Invalid next_cursor + '500': + description: Internal server error + content: + application/json: + schema: + $ref: '#/components/schemas/ErrorResponse' + example: + error: Internal server error +components: + schemas: + PaginatedMarketReward: + type: object + description: Paginated list of market reward configurations + properties: + limit: + type: integer + description: Maximum number of items per page + count: + type: integer + description: Number of items in the current response + next_cursor: + type: string + description: Cursor for the next page. "LTE=" indicates the last page. + data: + type: array + items: + $ref: '#/components/schemas/MarketReward' + required: + - limit + - count + - next_cursor + - data + ErrorResponse: + type: object + required: + - error + properties: + error: + type: string + description: Error message + code: + type: string + description: Machine-readable error code, when provided + retry_after_seconds: + type: integer + description: Number of seconds to wait before retrying, when provided + MarketReward: + type: object + description: Market with raw reward configurations + properties: + condition_id: + type: string + description: Condition ID of the market + question: + type: string + description: Market question + market_slug: + type: string + description: URL slug for the market + event_slug: + type: string + description: URL slug for the event + image: + type: string + description: URL to market image + rewards_max_spread: + type: number + description: Maximum spread for rewards eligibility + rewards_min_size: + type: number + description: Minimum order size for rewards eligibility + market_competitiveness: + type: number + format: double + description: Competitiveness score of the market + tokens: + type: array + items: + $ref: '#/components/schemas/RewardsToken' + rewards_config: + type: array + items: + $ref: '#/components/schemas/RewardsConfig' + required: + - condition_id + - question + - tokens + RewardsToken: + type: object + description: Token information for rewards markets + properties: + token_id: + type: string + description: Token ID + outcome: + type: string + description: Outcome name (e.g., "YES", "NO") + price: + type: number + format: double + description: Current price of the token + required: + - token_id + - outcome + RewardsConfig: + type: object + description: Rewards configuration for a market + properties: + id: + type: integer + description: Rewards config ID + asset_address: + type: string + description: Address of the reward asset + start_date: + type: string + format: date + description: Start date of the rewards period + end_date: + type: string + format: date + description: End date of the rewards period + rate_per_day: + type: number + format: double + description: Daily reward rate + total_rewards: + type: number + format: double + description: Total rewards amount + remaining_reward_amount: + type: number + format: double + description: Remaining reward amount + total_days: + type: integer + description: Total number of days in the rewards period + required: + - asset_address + - start_date + - rate_per_day + +```` \ No newline at end of file diff --git a/PolymarketDocumentation-main/docs/api-reference/rewards/get-reward-percentages-for-user.md b/PolymarketDocumentation-main/docs/api-reference/rewards/get-reward-percentages-for-user.md new file mode 100644 index 00000000..cfb688db --- /dev/null +++ b/PolymarketDocumentation-main/docs/api-reference/rewards/get-reward-percentages-for-user.md @@ -0,0 +1,181 @@ +> ## Documentation Index +> Fetch the complete documentation index at: https://docs.polymarket.com/llms.txt +> Use this file to discover all available pages before exploring further. + +# Get reward percentages for user + +> Returns the real-time percentages of rewards that a user is earning per market. + +The response is a map of condition_id to the percentage of total rewards +the user is currently earning in that market. + +Requires CLOB L2 Auth headers. + + + + +## OpenAPI + +````yaml /api-spec/clob-openapi.yaml get /rewards/user/percentages +openapi: 3.1.0 +info: + title: Polymarket CLOB API + description: Polymarket CLOB API Reference + license: + name: MIT + identifier: MIT + version: 1.0.0 +servers: + - url: https://clob.polymarket.com + description: Production CLOB API + - url: https://clob-staging.polymarket.com + description: Staging CLOB API +security: [] +tags: + - name: Trade + description: Trade endpoints + - name: Markets + description: Market data endpoints + - name: Account + description: Account and authentication endpoints + - name: Notifications + description: User notification endpoints + - name: Rewards + description: Rewards and earnings endpoints + - name: Rebates + description: Maker rebate endpoints +paths: + /rewards/user/percentages: + get: + tags: + - Rewards + summary: Get reward percentages for user + description: > + Returns the real-time percentages of rewards that a user is earning per + market. + + + The response is a map of condition_id to the percentage of total rewards + + the user is currently earning in that market. + + + Requires CLOB L2 Auth headers. + operationId: getRewardPercentagesForUser + parameters: + - name: signature_type + in: query + description: | + Signature type for address derivation (required for API KEY auth): + - 0: EOA + - 1: POLY_PROXY + - 2: POLY_GNOSIS_SAFE + required: false + schema: + type: integer + enum: + - 0 + - 1 + - 2 + - name: maker_address + in: query + description: Maker address to query percentages for + required: false + schema: + type: string + example: '0xFeA4cB3dD4ca7CefD3368653B7D6FF9BcDFca604' + responses: + '200': + description: Successfully retrieved reward percentages + content: + application/json: + schema: + type: object + additionalProperties: + type: number + format: double + description: Map of condition_id to reward percentage + example: + '0x296ea2f3ad438ce7ead77f40d0159bf3e5d8be146f6f615fa253b00e02243f5c': 20 + '0xbd31dc8a20211944f6b70f31557f1001557b59905b7738480ca09bd4532f84af': 20 + '400': + description: Bad request - Invalid parameters + content: + application/json: + schema: + $ref: '#/components/schemas/ErrorResponse' + examples: + invalid_signature_type: + summary: Invalid signature type + value: + error: Invalid signature_type + invalid_maker_address: + summary: Invalid maker address + value: + error: Invalid maker_address + '401': + description: Unauthorized - Invalid API key or authentication failed + content: + application/json: + schema: + $ref: '#/components/schemas/ErrorResponse' + example: + error: Invalid API key + '500': + description: Internal server error + content: + application/json: + schema: + $ref: '#/components/schemas/ErrorResponse' + example: + error: Internal server error + security: + - polyApiKey: [] + polyAddress: [] + polySignature: [] + polyPassphrase: [] + polyTimestamp: [] +components: + schemas: + ErrorResponse: + type: object + required: + - error + properties: + error: + type: string + description: Error message + code: + type: string + description: Machine-readable error code, when provided + retry_after_seconds: + type: integer + description: Number of seconds to wait before retrying, when provided + securitySchemes: + polyApiKey: + type: apiKey + in: header + name: POLY_API_KEY + description: Your API key + polyAddress: + type: apiKey + in: header + name: POLY_ADDRESS + description: Ethereum address associated with the API key + polySignature: + type: apiKey + in: header + name: POLY_SIGNATURE + description: HMAC signature of the request + polyPassphrase: + type: apiKey + in: header + name: POLY_PASSPHRASE + description: API key passphrase + polyTimestamp: + type: apiKey + in: header + name: POLY_TIMESTAMP + description: Unix timestamp of the request + +```` \ No newline at end of file diff --git a/PolymarketDocumentation-main/docs/api-reference/rewards/get-total-earnings-for-user-by-date.md b/PolymarketDocumentation-main/docs/api-reference/rewards/get-total-earnings-for-user-by-date.md new file mode 100644 index 00000000..85498e93 --- /dev/null +++ b/PolymarketDocumentation-main/docs/api-reference/rewards/get-total-earnings-for-user-by-date.md @@ -0,0 +1,226 @@ +> ## Documentation Index +> Fetch the complete documentation index at: https://docs.polymarket.com/llms.txt +> Use this file to discover all available pages before exploring further. + +# Get total earnings for user by date + +> Returns the summed total rewards earnings for a user on a provided day, +grouped by asset address. + +Requires CLOB L2 Auth headers. + + + + +## OpenAPI + +````yaml /api-spec/clob-openapi.yaml get /rewards/user/total +openapi: 3.1.0 +info: + title: Polymarket CLOB API + description: Polymarket CLOB API Reference + license: + name: MIT + identifier: MIT + version: 1.0.0 +servers: + - url: https://clob.polymarket.com + description: Production CLOB API + - url: https://clob-staging.polymarket.com + description: Staging CLOB API +security: [] +tags: + - name: Trade + description: Trade endpoints + - name: Markets + description: Market data endpoints + - name: Account + description: Account and authentication endpoints + - name: Notifications + description: User notification endpoints + - name: Rewards + description: Rewards and earnings endpoints + - name: Rebates + description: Maker rebate endpoints +paths: + /rewards/user/total: + get: + tags: + - Rewards + summary: Get total earnings for user by date + description: | + Returns the summed total rewards earnings for a user on a provided day, + grouped by asset address. + + Requires CLOB L2 Auth headers. + operationId: getTotalEarningsForUserForDay + parameters: + - name: date + in: query + description: Date in YYYY-MM-DD format + required: true + schema: + type: string + format: date + example: '2024-03-26' + - name: signature_type + in: query + description: | + Signature type for address derivation (required for API KEY auth): + - 0: EOA + - 1: POLY_PROXY + - 2: POLY_GNOSIS_SAFE + required: false + schema: + type: integer + enum: + - 0 + - 1 + - 2 + - name: maker_address + in: query + description: Maker address to query earnings for + required: false + schema: + type: string + example: '0xFeA4cB3dD4ca7CefD3368653B7D6FF9BcDFca604' + - name: sponsored + in: query + description: If true, aggregates both native and sponsored earnings + required: false + schema: + type: boolean + default: false + responses: + '200': + description: Successfully retrieved total user earnings + content: + application/json: + schema: + type: array + items: + $ref: '#/components/schemas/TotalUserEarning' + example: + - date: '2024-04-09T00:00:00Z' + asset_address: '0x9c4E1703476E875070EE25b56A58B008CFb8FA78' + maker_address: '0xD527CCdBEB6478488c848465F9947bDA3C2e6994' + earnings: 1.59984 + asset_rate: 0.999357 + - date: '2024-04-09T00:00:00Z' + asset_address: '0x69308FB512518e39F9b16112fA8d994F4e2Bf8bB' + maker_address: '0xD527CCdBEB6478488c848465F9947bDA3C2e6994' + earnings: 8.187219 + asset_rate: 3.51 + '400': + description: Bad request - Invalid parameters + content: + application/json: + schema: + $ref: '#/components/schemas/ErrorResponse' + examples: + invalid_date: + summary: Invalid date format + value: + error: 'Invalid date (format: YYYY-MM-DD)' + invalid_signature_type: + summary: Invalid signature type + value: + error: Invalid signature_type + invalid_maker_address: + summary: Invalid maker address + value: + error: Invalid maker_address + '401': + description: Unauthorized - Invalid API key or authentication failed + content: + application/json: + schema: + $ref: '#/components/schemas/ErrorResponse' + example: + error: Invalid API key + '500': + description: Internal server error + content: + application/json: + schema: + $ref: '#/components/schemas/ErrorResponse' + example: + error: Internal server error + security: + - polyApiKey: [] + polyAddress: [] + polySignature: [] + polyPassphrase: [] + polyTimestamp: [] +components: + schemas: + TotalUserEarning: + type: object + description: Total user earnings for a given day grouped by asset + properties: + date: + type: string + format: date-time + description: Date of the earnings + asset_address: + type: string + description: Address of the reward asset + maker_address: + type: string + description: Address of the maker + earnings: + type: number + format: double + description: Total amount of earnings in the asset + asset_rate: + type: number + format: double + description: Exchange rate of the asset + required: + - date + - asset_address + - maker_address + - earnings + - asset_rate + ErrorResponse: + type: object + required: + - error + properties: + error: + type: string + description: Error message + code: + type: string + description: Machine-readable error code, when provided + retry_after_seconds: + type: integer + description: Number of seconds to wait before retrying, when provided + securitySchemes: + polyApiKey: + type: apiKey + in: header + name: POLY_API_KEY + description: Your API key + polyAddress: + type: apiKey + in: header + name: POLY_ADDRESS + description: Ethereum address associated with the API key + polySignature: + type: apiKey + in: header + name: POLY_SIGNATURE + description: HMAC signature of the request + polyPassphrase: + type: apiKey + in: header + name: POLY_PASSPHRASE + description: API key passphrase + polyTimestamp: + type: apiKey + in: header + name: POLY_TIMESTAMP + description: Unix timestamp of the request + +```` \ No newline at end of file diff --git a/PolymarketDocumentation-main/docs/api-reference/rewards/get-user-earnings-and-markets-configuration.md b/PolymarketDocumentation-main/docs/api-reference/rewards/get-user-earnings-and-markets-configuration.md new file mode 100644 index 00000000..e1de660b --- /dev/null +++ b/PolymarketDocumentation-main/docs/api-reference/rewards/get-user-earnings-and-markets-configuration.md @@ -0,0 +1,503 @@ +> ## Documentation Index +> Fetch the complete documentation index at: https://docs.polymarket.com/llms.txt +> Use this file to discover all available pages before exploring further. + +# Get user earnings and markets configuration + +> Returns an array of current rewards including user earnings and live percentages +per market for a provided day. + +Results are paginated (100 items per page by default, max 500). Use next_cursor to fetch subsequent pages. +A next_cursor value of "LTE=" indicates the last page. + +Requires CLOB L2 Auth headers. + +Optional features: +- Search by question/description using the `q` parameter +- Filter by tag slugs using `tag_slug` parameter (multiple values are OR'ed) +- Filter by favorite markets using `favorite_markets=true` +- Sort by various fields using `order_by` and `position` parameters + + + + +## OpenAPI + +````yaml /api-spec/clob-openapi.yaml get /rewards/user/markets +openapi: 3.1.0 +info: + title: Polymarket CLOB API + description: Polymarket CLOB API Reference + license: + name: MIT + identifier: MIT + version: 1.0.0 +servers: + - url: https://clob.polymarket.com + description: Production CLOB API + - url: https://clob-staging.polymarket.com + description: Staging CLOB API +security: [] +tags: + - name: Trade + description: Trade endpoints + - name: Markets + description: Market data endpoints + - name: Account + description: Account and authentication endpoints + - name: Notifications + description: User notification endpoints + - name: Rewards + description: Rewards and earnings endpoints + - name: Rebates + description: Maker rebate endpoints +paths: + /rewards/user/markets: + get: + tags: + - Rewards + summary: Get user earnings and markets configuration + description: > + Returns an array of current rewards including user earnings and live + percentages + + per market for a provided day. + + + Results are paginated (100 items per page by default, max 500). Use + next_cursor to fetch subsequent pages. + + A next_cursor value of "LTE=" indicates the last page. + + + Requires CLOB L2 Auth headers. + + + Optional features: + + - Search by question/description using the `q` parameter + + - Filter by tag slugs using `tag_slug` parameter (multiple values are + OR'ed) + + - Filter by favorite markets using `favorite_markets=true` + + - Sort by various fields using `order_by` and `position` parameters + operationId: getUserEarningsAndMarketsConfig + parameters: + - name: date + in: query + description: Date in YYYY-MM-DD format. Defaults to current date if not provided. + required: false + schema: + type: string + format: date + example: '2024-03-26' + - name: signature_type + in: query + description: | + Signature type for address derivation (required for API KEY auth): + - 0: EOA + - 1: POLY_PROXY + - 2: POLY_GNOSIS_SAFE + required: false + schema: + type: integer + enum: + - 0 + - 1 + - 2 + - name: maker_address + in: query + description: Maker address to query data for + required: false + schema: + type: string + example: '0xFeA4cB3dD4ca7CefD3368653B7D6FF9BcDFca604' + - name: sponsored + in: query + description: If true, returns sponsored reward earnings + required: false + schema: + type: boolean + default: false + - name: next_cursor + in: query + description: Pagination cursor from previous response + required: false + schema: + type: string + - name: page_size + in: query + description: Number of items per page (max 500, values above are capped) + required: false + schema: + type: integer + default: 100 + maximum: 500 + - name: q + in: query + description: Search query to filter markets by question/description + required: false + schema: + type: string + - name: tag_slug + in: query + description: Filter by tag slug (can be repeated for OR logic) + required: false + schema: + type: string + - name: favorite_markets + in: query + description: If true, only show markets favorited by the user (requires auth) + required: false + schema: + type: boolean + default: false + - name: no_competition + in: query + description: Filter for markets with no competition + required: false + schema: + type: boolean + default: false + - name: only_mergeable + in: query + description: Filter for only mergeable markets + required: false + schema: + type: boolean + default: false + - name: only_open_orders + in: query + description: Filter for markets where user has open orders + required: false + schema: + type: boolean + default: false + - name: only_open_positions + in: query + description: Filter for markets where user has open positions + required: false + schema: + type: boolean + default: false + - name: order_by + in: query + description: Field to sort by + required: false + schema: + type: string + enum: + - max_spread + - min_size + - end_date + - earning_percentage + - rate_per_day + - earnings + - spread + - competitiveness + - question + - price + - market + - volume_24hr + - name: position + in: query + description: Sort direction + required: false + schema: + type: string + enum: + - ASC + - DESC + responses: + '200': + description: Successfully retrieved user earnings and market configurations + content: + application/json: + schema: + $ref: '#/components/schemas/PaginatedUserRewardsMarkets' + example: + limit: 100 + count: 1 + total_count: 42 + next_cursor: LTE= + data: + - condition_id: >- + 0xbd31dc8a20211944f6b70f31557f1001557b59905b7738480ca09bd4532f84af + market_id: '248849' + event_id: '12345' + question: Will Trump win the 2024 Iowa Caucus? + market_slug: will-trump-win-the-2024-iowa-caucus + event_slug: will-trump-win-the-2024-iowa-caucus + image: >- + https://polymarket-upload.s3.us-east-2.amazonaws.com/trump1+copy.png + rewards_max_spread: 99 + rewards_min_size: 10 + volume_24hr: 12345.67 + spread: 0.12 + market_competitiveness: 0.42 + tokens: + - token_id: >- + 1343197538147866997676250008839231694243646439454152539053893078719042421992 + outcome: 'YES' + price: 0.8 + - token_id: >- + 16678291189211314787145083999015737376658799626183230671758641503291735614088 + outcome: 'NO' + price: 0.2 + rewards_config: + - id: 0 + asset_address: '0x9c4E1703476E875070EE25b56A58B008CFb8FA78' + start_date: '2024-03-01' + end_date: '2500-12-31' + rate_per_day: 2 + total_rewards: 92 + maker_address: '0xD527CCdBEB6478488c848465F9947bDA3C2e6994' + earning_percentage: 30 + earnings: + - asset_address: '0x9c4E1703476E875070EE25b56A58B008CFb8FA78' + earnings: 0.585051 + asset_rate: 1.001 + '400': + description: Bad request - Invalid parameters + content: + application/json: + schema: + $ref: '#/components/schemas/ErrorResponse' + examples: + invalid_date: + summary: Invalid date format + value: + error: 'Invalid date (format: YYYY-MM-DD)' + invalid_signature_type: + summary: Invalid signature type + value: + error: Invalid signature_type + favorite_requires_auth: + summary: Favorite markets requires auth + value: + error: favorite_markets query argument requires authentication + '401': + description: Unauthorized - Invalid API key or authentication failed + content: + application/json: + schema: + $ref: '#/components/schemas/ErrorResponse' + example: + error: Invalid API key + '500': + description: Internal server error + content: + application/json: + schema: + $ref: '#/components/schemas/ErrorResponse' + example: + error: Internal server error + security: + - polyApiKey: [] + polyAddress: [] + polySignature: [] + polyPassphrase: [] + polyTimestamp: [] +components: + schemas: + PaginatedUserRewardsMarkets: + type: object + description: Paginated list of user rewards markets + properties: + limit: + type: integer + description: Maximum number of items per page + count: + type: integer + description: Number of items in the current response + total_count: + type: integer + description: Total number of items across all pages + next_cursor: + type: string + description: Cursor for the next page. "LTE=" indicates the last page. + data: + type: array + items: + $ref: '#/components/schemas/UserRewardsMarket' + required: + - limit + - count + - next_cursor + - data + ErrorResponse: + type: object + required: + - error + properties: + error: + type: string + description: Error message + code: + type: string + description: Machine-readable error code, when provided + retry_after_seconds: + type: integer + description: Number of seconds to wait before retrying, when provided + UserRewardsMarket: + type: object + description: Market with user rewards earnings and configuration + properties: + condition_id: + type: string + description: Condition ID of the market + market_id: + type: string + description: Market ID + event_id: + type: string + description: Event ID + question: + type: string + description: Market question + market_slug: + type: string + description: URL slug for the market + event_slug: + type: string + description: URL slug for the event + image: + type: string + description: URL to market image + rewards_max_spread: + type: number + description: Maximum spread for rewards eligibility + rewards_min_size: + type: number + description: Minimum order size for rewards eligibility + volume_24hr: + type: number + format: double + description: 24-hour trading volume + spread: + type: number + format: double + description: Current spread + market_competitiveness: + type: number + format: double + description: Competitiveness score of the market + tokens: + type: array + items: + $ref: '#/components/schemas/RewardsToken' + rewards_config: + type: array + items: + $ref: '#/components/schemas/CurrentRewardConfig' + maker_address: + type: string + description: Maker address + earning_percentage: + type: number + format: double + description: Percentage of total rewards the user is earning + earnings: + type: array + items: + $ref: '#/components/schemas/AssetEarning' + required: + - condition_id + - market_id + - question + - tokens + RewardsToken: + type: object + description: Token information for rewards markets + properties: + token_id: + type: string + description: Token ID + outcome: + type: string + description: Outcome name (e.g., "YES", "NO") + price: + type: number + format: double + description: Current price of the token + required: + - token_id + - outcome + CurrentRewardConfig: + type: object + description: Reward configuration entry for a current rewards market + properties: + id: + type: integer + description: Rewards config ID (always 0 on /rewards/markets/current) + asset_address: + type: string + description: Address of the reward asset + start_date: + type: string + format: date + description: Start date of the rewards period + end_date: + type: string + format: date + description: End date of the rewards period + rate_per_day: + type: number + format: double + description: Daily reward rate + total_rewards: + type: number + format: double + description: Total rewards amount + required: + - asset_address + - start_date + - rate_per_day + AssetEarning: + type: object + description: Earnings for a specific asset + properties: + asset_address: + type: string + description: Address of the reward asset + earnings: + type: number + format: double + description: Amount of earnings + asset_rate: + type: number + format: double + description: Exchange rate of the asset + required: + - asset_address + - earnings + securitySchemes: + polyApiKey: + type: apiKey + in: header + name: POLY_API_KEY + description: Your API key + polyAddress: + type: apiKey + in: header + name: POLY_ADDRESS + description: Ethereum address associated with the API key + polySignature: + type: apiKey + in: header + name: POLY_SIGNATURE + description: HMAC signature of the request + polyPassphrase: + type: apiKey + in: header + name: POLY_PASSPHRASE + description: API key passphrase + polyTimestamp: + type: apiKey + in: header + name: POLY_TIMESTAMP + description: Unix timestamp of the request + +```` \ No newline at end of file diff --git a/PolymarketDocumentation-main/docs/api-reference/search/search-markets-events-and-profiles.md b/PolymarketDocumentation-main/docs/api-reference/search/search-markets-events-and-profiles.md new file mode 100644 index 00000000..9089a2f2 --- /dev/null +++ b/PolymarketDocumentation-main/docs/api-reference/search/search-markets-events-and-profiles.md @@ -0,0 +1,1367 @@ +> ## Documentation Index +> Fetch the complete documentation index at: https://docs.polymarket.com/llms.txt +> Use this file to discover all available pages before exploring further. + +# Search markets, events, and profiles + + + +## OpenAPI + +````yaml /api-spec/gamma-openapi.yaml get /public-search +openapi: 3.0.3 +info: + title: Markets API + version: 1.0.0 + description: REST API specification for public endpoints used by the Markets service. +servers: + - url: https://gamma-api.polymarket.com + description: Polymarket Gamma API Production Server +security: [] +tags: + - name: Gamma Status + description: Gamma API status and health check + - name: Sports + description: Sports-related endpoints including teams and game data + - name: Tags + description: Tag management and related tag operations + - name: Events + description: Event management and event-related operations + - name: Markets + description: Market data and market-related operations + - name: Comments + description: Comment system and user interactions + - name: Series + description: Series management and related operations + - name: Profiles + description: User profile management + - name: Search + description: Search functionality across different entity types +paths: + /public-search: + get: + tags: + - Search + summary: Search markets, events, and profiles + operationId: publicSearch + parameters: + - name: q + in: query + required: true + schema: + type: string + - name: cache + in: query + schema: + type: boolean + - name: events_status + in: query + schema: + type: string + - name: limit_per_type + in: query + schema: + type: integer + - name: page + in: query + schema: + type: integer + - name: events_tag + in: query + schema: + type: array + items: + type: string + - name: keep_closed_markets + in: query + schema: + type: integer + - name: sort + in: query + schema: + type: string + - name: ascending + in: query + schema: + type: boolean + - name: search_tags + in: query + schema: + type: boolean + - name: search_profiles + in: query + schema: + type: boolean + - name: recurrence + in: query + schema: + type: string + - name: exclude_tag_id + in: query + schema: + type: array + items: + type: integer + - name: optimized + in: query + schema: + type: boolean + responses: + '200': + description: Search results + content: + application/json: + schema: + $ref: '#/components/schemas/Search' +components: + schemas: + Search: + type: object + properties: + events: + type: array + items: + $ref: '#/components/schemas/Event' + nullable: true + tags: + type: array + items: + $ref: '#/components/schemas/SearchTag' + nullable: true + profiles: + type: array + items: + $ref: '#/components/schemas/Profile' + nullable: true + pagination: + $ref: '#/components/schemas/Pagination' + Event: + type: object + properties: + id: + type: string + ticker: + type: string + nullable: true + slug: + type: string + nullable: true + title: + type: string + nullable: true + subtitle: + type: string + nullable: true + description: + type: string + nullable: true + resolutionSource: + type: string + nullable: true + startDate: + type: string + format: date-time + nullable: true + creationDate: + type: string + format: date-time + nullable: true + endDate: + type: string + format: date-time + nullable: true + image: + type: string + nullable: true + icon: + type: string + nullable: true + active: + type: boolean + nullable: true + closed: + type: boolean + nullable: true + archived: + type: boolean + nullable: true + new: + type: boolean + nullable: true + featured: + type: boolean + nullable: true + restricted: + type: boolean + nullable: true + liquidity: + type: number + nullable: true + volume: + type: number + nullable: true + openInterest: + type: number + nullable: true + sortBy: + type: string + nullable: true + category: + type: string + nullable: true + subcategory: + type: string + nullable: true + isTemplate: + type: boolean + nullable: true + templateVariables: + type: string + nullable: true + published_at: + type: string + nullable: true + createdBy: + type: string + nullable: true + updatedBy: + type: string + nullable: true + createdAt: + type: string + format: date-time + nullable: true + updatedAt: + type: string + format: date-time + nullable: true + commentsEnabled: + type: boolean + nullable: true + competitive: + type: number + nullable: true + volume24hr: + type: number + nullable: true + volume1wk: + type: number + nullable: true + volume1mo: + type: number + nullable: true + volume1yr: + type: number + nullable: true + featuredImage: + type: string + nullable: true + disqusThread: + type: string + nullable: true + parentEvent: + type: string + nullable: true + enableOrderBook: + type: boolean + nullable: true + liquidityAmm: + type: number + nullable: true + liquidityClob: + type: number + nullable: true + negRisk: + type: boolean + nullable: true + negRiskMarketID: + type: string + nullable: true + negRiskFeeBips: + type: integer + nullable: true + commentCount: + type: integer + nullable: true + imageOptimized: + $ref: '#/components/schemas/ImageOptimization' + iconOptimized: + $ref: '#/components/schemas/ImageOptimization' + featuredImageOptimized: + $ref: '#/components/schemas/ImageOptimization' + subEvents: + type: array + items: + type: string + nullable: true + markets: + type: array + items: + $ref: '#/components/schemas/Market' + series: + type: array + items: + $ref: '#/components/schemas/Series' + categories: + type: array + items: + $ref: '#/components/schemas/Category' + collections: + type: array + items: + $ref: '#/components/schemas/Collection' + tags: + type: array + items: + $ref: '#/components/schemas/Tag' + cyom: + type: boolean + nullable: true + closedTime: + type: string + format: date-time + nullable: true + showAllOutcomes: + type: boolean + nullable: true + showMarketImages: + type: boolean + nullable: true + automaticallyResolved: + type: boolean + nullable: true + enableNegRisk: + type: boolean + nullable: true + automaticallyActive: + type: boolean + nullable: true + eventDate: + type: string + nullable: true + startTime: + type: string + format: date-time + nullable: true + eventWeek: + type: integer + nullable: true + seriesSlug: + type: string + nullable: true + score: + type: string + nullable: true + elapsed: + type: string + nullable: true + period: + type: string + nullable: true + live: + type: boolean + nullable: true + ended: + type: boolean + nullable: true + finishedTimestamp: + type: string + format: date-time + nullable: true + gmpChartMode: + type: string + nullable: true + eventCreators: + type: array + items: + $ref: '#/components/schemas/EventCreator' + tweetCount: + type: integer + nullable: true + chats: + type: array + items: + $ref: '#/components/schemas/Chat' + featuredOrder: + type: integer + nullable: true + estimateValue: + type: boolean + nullable: true + cantEstimate: + type: boolean + nullable: true + estimatedValue: + type: string + nullable: true + templates: + type: array + items: + $ref: '#/components/schemas/Template' + spreadsMainLine: + type: number + nullable: true + totalsMainLine: + type: number + nullable: true + carouselMap: + type: string + nullable: true + pendingDeployment: + type: boolean + nullable: true + deploying: + type: boolean + nullable: true + deployingTimestamp: + type: string + format: date-time + nullable: true + scheduledDeploymentTimestamp: + type: string + format: date-time + nullable: true + gameStatus: + type: string + nullable: true + SearchTag: + type: object + properties: + id: + type: string + label: + type: string + slug: + type: string + event_count: + type: integer + Profile: + type: object + properties: + id: + type: string + name: + type: string + nullable: true + user: + type: integer + nullable: true + referral: + type: string + nullable: true + createdBy: + type: integer + nullable: true + updatedBy: + type: integer + nullable: true + createdAt: + type: string + format: date-time + nullable: true + updatedAt: + type: string + format: date-time + nullable: true + utmSource: + type: string + nullable: true + utmMedium: + type: string + nullable: true + utmCampaign: + type: string + nullable: true + utmContent: + type: string + nullable: true + utmTerm: + type: string + nullable: true + walletActivated: + type: boolean + nullable: true + pseudonym: + type: string + nullable: true + displayUsernamePublic: + type: boolean + nullable: true + profileImage: + type: string + nullable: true + bio: + type: string + nullable: true + proxyWallet: + type: string + nullable: true + profileImageOptimized: + $ref: '#/components/schemas/ImageOptimization' + isCloseOnly: + type: boolean + nullable: true + isCertReq: + type: boolean + nullable: true + certReqDate: + type: string + format: date-time + nullable: true + Pagination: + type: object + properties: + hasMore: + type: boolean + totalResults: + type: integer + ImageOptimization: + type: object + properties: + id: + type: string + imageUrlSource: + type: string + nullable: true + imageUrlOptimized: + type: string + nullable: true + imageSizeKbSource: + type: number + nullable: true + imageSizeKbOptimized: + type: number + nullable: true + imageOptimizedComplete: + type: boolean + nullable: true + imageOptimizedLastUpdated: + type: string + nullable: true + relID: + type: integer + nullable: true + field: + type: string + nullable: true + relname: + type: string + nullable: true + Market: + type: object + properties: + id: + type: string + question: + type: string + nullable: true + conditionId: + type: string + slug: + type: string + nullable: true + twitterCardImage: + type: string + nullable: true + resolutionSource: + type: string + nullable: true + endDate: + type: string + format: date-time + nullable: true + category: + type: string + nullable: true + ammType: + type: string + nullable: true + liquidity: + type: string + nullable: true + sponsorName: + type: string + nullable: true + sponsorImage: + type: string + nullable: true + startDate: + type: string + format: date-time + nullable: true + xAxisValue: + type: string + nullable: true + yAxisValue: + type: string + nullable: true + denominationToken: + type: string + nullable: true + fee: + type: string + nullable: true + image: + type: string + nullable: true + icon: + type: string + nullable: true + lowerBound: + type: string + nullable: true + upperBound: + type: string + nullable: true + description: + type: string + nullable: true + outcomes: + type: string + nullable: true + outcomePrices: + type: string + nullable: true + volume: + type: string + nullable: true + active: + type: boolean + nullable: true + marketType: + type: string + nullable: true + formatType: + type: string + nullable: true + lowerBoundDate: + type: string + nullable: true + upperBoundDate: + type: string + nullable: true + closed: + type: boolean + nullable: true + marketMakerAddress: + type: string + createdBy: + type: integer + nullable: true + updatedBy: + type: integer + nullable: true + createdAt: + type: string + format: date-time + nullable: true + updatedAt: + type: string + format: date-time + nullable: true + closedTime: + type: string + nullable: true + wideFormat: + type: boolean + nullable: true + new: + type: boolean + nullable: true + mailchimpTag: + type: string + nullable: true + featured: + type: boolean + nullable: true + archived: + type: boolean + nullable: true + resolvedBy: + type: string + nullable: true + restricted: + type: boolean + nullable: true + marketGroup: + type: integer + nullable: true + groupItemTitle: + type: string + nullable: true + groupItemThreshold: + type: string + nullable: true + questionID: + type: string + nullable: true + umaEndDate: + type: string + nullable: true + enableOrderBook: + type: boolean + nullable: true + orderPriceMinTickSize: + type: number + nullable: true + orderMinSize: + type: number + nullable: true + umaResolutionStatus: + type: string + nullable: true + curationOrder: + type: integer + nullable: true + volumeNum: + type: number + nullable: true + liquidityNum: + type: number + nullable: true + endDateIso: + type: string + nullable: true + startDateIso: + type: string + nullable: true + umaEndDateIso: + type: string + nullable: true + hasReviewedDates: + type: boolean + nullable: true + readyForCron: + type: boolean + nullable: true + commentsEnabled: + type: boolean + nullable: true + volume24hr: + type: number + nullable: true + volume1wk: + type: number + nullable: true + volume1mo: + type: number + nullable: true + volume1yr: + type: number + nullable: true + gameStartTime: + type: string + nullable: true + secondsDelay: + type: integer + nullable: true + clobTokenIds: + type: string + nullable: true + disqusThread: + type: string + nullable: true + shortOutcomes: + type: string + nullable: true + teamAID: + type: string + nullable: true + teamBID: + type: string + nullable: true + umaBond: + type: string + nullable: true + umaReward: + type: string + nullable: true + fpmmLive: + type: boolean + nullable: true + volume24hrAmm: + type: number + nullable: true + volume1wkAmm: + type: number + nullable: true + volume1moAmm: + type: number + nullable: true + volume1yrAmm: + type: number + nullable: true + volume24hrClob: + type: number + nullable: true + volume1wkClob: + type: number + nullable: true + volume1moClob: + type: number + nullable: true + volume1yrClob: + type: number + nullable: true + volumeAmm: + type: number + nullable: true + volumeClob: + type: number + nullable: true + liquidityAmm: + type: number + nullable: true + liquidityClob: + type: number + nullable: true + makerBaseFee: + type: integer + nullable: true + takerBaseFee: + type: integer + nullable: true + customLiveness: + type: integer + nullable: true + acceptingOrders: + type: boolean + nullable: true + notificationsEnabled: + type: boolean + nullable: true + score: + type: integer + nullable: true + imageOptimized: + $ref: '#/components/schemas/ImageOptimization' + iconOptimized: + $ref: '#/components/schemas/ImageOptimization' + events: + type: array + items: + $ref: '#/components/schemas/Event' + categories: + type: array + items: + $ref: '#/components/schemas/Category' + tags: + type: array + items: + $ref: '#/components/schemas/Tag' + creator: + type: string + nullable: true + ready: + type: boolean + nullable: true + funded: + type: boolean + nullable: true + pastSlugs: + type: string + nullable: true + readyTimestamp: + type: string + format: date-time + nullable: true + fundedTimestamp: + type: string + format: date-time + nullable: true + acceptingOrdersTimestamp: + type: string + format: date-time + nullable: true + competitive: + type: number + nullable: true + rewardsMinSize: + type: number + nullable: true + rewardsMaxSpread: + type: number + nullable: true + spread: + type: number + nullable: true + automaticallyResolved: + type: boolean + nullable: true + oneDayPriceChange: + type: number + nullable: true + oneHourPriceChange: + type: number + nullable: true + oneWeekPriceChange: + type: number + nullable: true + oneMonthPriceChange: + type: number + nullable: true + oneYearPriceChange: + type: number + nullable: true + lastTradePrice: + type: number + nullable: true + bestBid: + type: number + nullable: true + bestAsk: + type: number + nullable: true + automaticallyActive: + type: boolean + nullable: true + clearBookOnStart: + type: boolean + nullable: true + chartColor: + type: string + nullable: true + seriesColor: + type: string + nullable: true + showGmpSeries: + type: boolean + nullable: true + showGmpOutcome: + type: boolean + nullable: true + manualActivation: + type: boolean + nullable: true + negRiskOther: + type: boolean + nullable: true + gameId: + type: string + nullable: true + groupItemRange: + type: string + nullable: true + sportsMarketType: + type: string + nullable: true + line: + type: number + nullable: true + umaResolutionStatuses: + type: string + nullable: true + pendingDeployment: + type: boolean + nullable: true + deploying: + type: boolean + nullable: true + deployingTimestamp: + type: string + format: date-time + nullable: true + scheduledDeploymentTimestamp: + type: string + format: date-time + nullable: true + rfqEnabled: + type: boolean + nullable: true + eventStartTime: + type: string + format: date-time + nullable: true + feesEnabled: + type: boolean + nullable: true + feeSchedule: + $ref: '#/components/schemas/FeeSchedule' + Series: + type: object + properties: + id: + type: string + ticker: + type: string + nullable: true + slug: + type: string + nullable: true + title: + type: string + nullable: true + subtitle: + type: string + nullable: true + seriesType: + type: string + nullable: true + recurrence: + type: string + nullable: true + description: + type: string + nullable: true + image: + type: string + nullable: true + icon: + type: string + nullable: true + layout: + type: string + nullable: true + active: + type: boolean + nullable: true + closed: + type: boolean + nullable: true + archived: + type: boolean + nullable: true + new: + type: boolean + nullable: true + featured: + type: boolean + nullable: true + restricted: + type: boolean + nullable: true + isTemplate: + type: boolean + nullable: true + templateVariables: + type: boolean + nullable: true + publishedAt: + type: string + nullable: true + createdBy: + type: string + nullable: true + updatedBy: + type: string + nullable: true + createdAt: + type: string + format: date-time + nullable: true + updatedAt: + type: string + format: date-time + nullable: true + commentsEnabled: + type: boolean + nullable: true + competitive: + type: string + nullable: true + volume24hr: + type: number + nullable: true + volume: + type: number + nullable: true + liquidity: + type: number + nullable: true + startDate: + type: string + format: date-time + nullable: true + pythTokenID: + type: string + nullable: true + cgAssetName: + type: string + nullable: true + score: + type: integer + nullable: true + events: + type: array + items: + $ref: '#/components/schemas/Event' + collections: + type: array + items: + $ref: '#/components/schemas/Collection' + categories: + type: array + items: + $ref: '#/components/schemas/Category' + tags: + type: array + items: + $ref: '#/components/schemas/Tag' + commentCount: + type: integer + nullable: true + chats: + type: array + items: + $ref: '#/components/schemas/Chat' + Category: + type: object + properties: + id: + type: string + label: + type: string + nullable: true + parentCategory: + type: string + nullable: true + slug: + type: string + nullable: true + publishedAt: + type: string + nullable: true + createdBy: + type: string + nullable: true + updatedBy: + type: string + nullable: true + createdAt: + type: string + format: date-time + nullable: true + updatedAt: + type: string + format: date-time + nullable: true + Collection: + type: object + properties: + id: + type: string + ticker: + type: string + nullable: true + slug: + type: string + nullable: true + title: + type: string + nullable: true + subtitle: + type: string + nullable: true + collectionType: + type: string + nullable: true + description: + type: string + nullable: true + tags: + type: string + nullable: true + image: + type: string + nullable: true + icon: + type: string + nullable: true + headerImage: + type: string + nullable: true + layout: + type: string + nullable: true + active: + type: boolean + nullable: true + closed: + type: boolean + nullable: true + archived: + type: boolean + nullable: true + new: + type: boolean + nullable: true + featured: + type: boolean + nullable: true + restricted: + type: boolean + nullable: true + isTemplate: + type: boolean + nullable: true + templateVariables: + type: string + nullable: true + publishedAt: + type: string + nullable: true + createdBy: + type: string + nullable: true + updatedBy: + type: string + nullable: true + createdAt: + type: string + format: date-time + nullable: true + updatedAt: + type: string + format: date-time + nullable: true + commentsEnabled: + type: boolean + nullable: true + imageOptimized: + $ref: '#/components/schemas/ImageOptimization' + iconOptimized: + $ref: '#/components/schemas/ImageOptimization' + headerImageOptimized: + $ref: '#/components/schemas/ImageOptimization' + Tag: + type: object + properties: + id: + type: string + label: + type: string + nullable: true + slug: + type: string + nullable: true + forceShow: + type: boolean + nullable: true + publishedAt: + type: string + nullable: true + createdBy: + type: integer + nullable: true + updatedBy: + type: integer + nullable: true + createdAt: + type: string + format: date-time + nullable: true + updatedAt: + type: string + format: date-time + nullable: true + forceHide: + type: boolean + nullable: true + isCarousel: + type: boolean + nullable: true + EventCreator: + type: object + properties: + id: + type: string + creatorName: + type: string + nullable: true + creatorHandle: + type: string + nullable: true + creatorUrl: + type: string + nullable: true + creatorImage: + type: string + nullable: true + createdAt: + type: string + format: date-time + nullable: true + updatedAt: + type: string + format: date-time + nullable: true + Chat: + type: object + properties: + id: + type: string + channelId: + type: string + nullable: true + channelName: + type: string + nullable: true + channelImage: + type: string + nullable: true + live: + type: boolean + nullable: true + startTime: + type: string + format: date-time + nullable: true + endTime: + type: string + format: date-time + nullable: true + Template: + type: object + properties: + id: + type: string + eventTitle: + type: string + nullable: true + eventSlug: + type: string + nullable: true + eventImage: + type: string + nullable: true + marketTitle: + type: string + nullable: true + description: + type: string + nullable: true + resolutionSource: + type: string + nullable: true + negRisk: + type: boolean + nullable: true + sortBy: + type: string + nullable: true + showMarketImages: + type: boolean + nullable: true + seriesSlug: + type: string + nullable: true + outcomes: + type: string + nullable: true + FeeSchedule: + type: object + properties: + exponent: + type: number + nullable: true + rate: + type: number + nullable: true + takerOnly: + type: boolean + nullable: true + rebateRate: + type: number + nullable: true + +```` \ No newline at end of file diff --git a/PolymarketDocumentation-main/docs/api-reference/series/get-series-by-id.md b/PolymarketDocumentation-main/docs/api-reference/series/get-series-by-id.md new file mode 100644 index 00000000..850b731b --- /dev/null +++ b/PolymarketDocumentation-main/docs/api-reference/series/get-series-by-id.md @@ -0,0 +1,1209 @@ +> ## Documentation Index +> Fetch the complete documentation index at: https://docs.polymarket.com/llms.txt +> Use this file to discover all available pages before exploring further. + +# Get series by id + + + +## OpenAPI + +````yaml /api-spec/gamma-openapi.yaml get /series/{id} +openapi: 3.0.3 +info: + title: Markets API + version: 1.0.0 + description: REST API specification for public endpoints used by the Markets service. +servers: + - url: https://gamma-api.polymarket.com + description: Polymarket Gamma API Production Server +security: [] +tags: + - name: Gamma Status + description: Gamma API status and health check + - name: Sports + description: Sports-related endpoints including teams and game data + - name: Tags + description: Tag management and related tag operations + - name: Events + description: Event management and event-related operations + - name: Markets + description: Market data and market-related operations + - name: Comments + description: Comment system and user interactions + - name: Series + description: Series management and related operations + - name: Profiles + description: User profile management + - name: Search + description: Search functionality across different entity types +paths: + /series/{id}: + get: + tags: + - Series + summary: Get series by id + operationId: getSeries + parameters: + - $ref: '#/components/parameters/pathId' + - name: include_chat + in: query + schema: + type: boolean + responses: + '200': + description: Series + content: + application/json: + schema: + $ref: '#/components/schemas/Series' + '404': + description: Not found +components: + parameters: + pathId: + name: id + in: path + required: true + schema: + type: integer + schemas: + Series: + type: object + properties: + id: + type: string + ticker: + type: string + nullable: true + slug: + type: string + nullable: true + title: + type: string + nullable: true + subtitle: + type: string + nullable: true + seriesType: + type: string + nullable: true + recurrence: + type: string + nullable: true + description: + type: string + nullable: true + image: + type: string + nullable: true + icon: + type: string + nullable: true + layout: + type: string + nullable: true + active: + type: boolean + nullable: true + closed: + type: boolean + nullable: true + archived: + type: boolean + nullable: true + new: + type: boolean + nullable: true + featured: + type: boolean + nullable: true + restricted: + type: boolean + nullable: true + isTemplate: + type: boolean + nullable: true + templateVariables: + type: boolean + nullable: true + publishedAt: + type: string + nullable: true + createdBy: + type: string + nullable: true + updatedBy: + type: string + nullable: true + createdAt: + type: string + format: date-time + nullable: true + updatedAt: + type: string + format: date-time + nullable: true + commentsEnabled: + type: boolean + nullable: true + competitive: + type: string + nullable: true + volume24hr: + type: number + nullable: true + volume: + type: number + nullable: true + liquidity: + type: number + nullable: true + startDate: + type: string + format: date-time + nullable: true + pythTokenID: + type: string + nullable: true + cgAssetName: + type: string + nullable: true + score: + type: integer + nullable: true + events: + type: array + items: + $ref: '#/components/schemas/Event' + collections: + type: array + items: + $ref: '#/components/schemas/Collection' + categories: + type: array + items: + $ref: '#/components/schemas/Category' + tags: + type: array + items: + $ref: '#/components/schemas/Tag' + commentCount: + type: integer + nullable: true + chats: + type: array + items: + $ref: '#/components/schemas/Chat' + Event: + type: object + properties: + id: + type: string + ticker: + type: string + nullable: true + slug: + type: string + nullable: true + title: + type: string + nullable: true + subtitle: + type: string + nullable: true + description: + type: string + nullable: true + resolutionSource: + type: string + nullable: true + startDate: + type: string + format: date-time + nullable: true + creationDate: + type: string + format: date-time + nullable: true + endDate: + type: string + format: date-time + nullable: true + image: + type: string + nullable: true + icon: + type: string + nullable: true + active: + type: boolean + nullable: true + closed: + type: boolean + nullable: true + archived: + type: boolean + nullable: true + new: + type: boolean + nullable: true + featured: + type: boolean + nullable: true + restricted: + type: boolean + nullable: true + liquidity: + type: number + nullable: true + volume: + type: number + nullable: true + openInterest: + type: number + nullable: true + sortBy: + type: string + nullable: true + category: + type: string + nullable: true + subcategory: + type: string + nullable: true + isTemplate: + type: boolean + nullable: true + templateVariables: + type: string + nullable: true + published_at: + type: string + nullable: true + createdBy: + type: string + nullable: true + updatedBy: + type: string + nullable: true + createdAt: + type: string + format: date-time + nullable: true + updatedAt: + type: string + format: date-time + nullable: true + commentsEnabled: + type: boolean + nullable: true + competitive: + type: number + nullable: true + volume24hr: + type: number + nullable: true + volume1wk: + type: number + nullable: true + volume1mo: + type: number + nullable: true + volume1yr: + type: number + nullable: true + featuredImage: + type: string + nullable: true + disqusThread: + type: string + nullable: true + parentEvent: + type: string + nullable: true + enableOrderBook: + type: boolean + nullable: true + liquidityAmm: + type: number + nullable: true + liquidityClob: + type: number + nullable: true + negRisk: + type: boolean + nullable: true + negRiskMarketID: + type: string + nullable: true + negRiskFeeBips: + type: integer + nullable: true + commentCount: + type: integer + nullable: true + imageOptimized: + $ref: '#/components/schemas/ImageOptimization' + iconOptimized: + $ref: '#/components/schemas/ImageOptimization' + featuredImageOptimized: + $ref: '#/components/schemas/ImageOptimization' + subEvents: + type: array + items: + type: string + nullable: true + markets: + type: array + items: + $ref: '#/components/schemas/Market' + series: + type: array + items: + $ref: '#/components/schemas/Series' + categories: + type: array + items: + $ref: '#/components/schemas/Category' + collections: + type: array + items: + $ref: '#/components/schemas/Collection' + tags: + type: array + items: + $ref: '#/components/schemas/Tag' + cyom: + type: boolean + nullable: true + closedTime: + type: string + format: date-time + nullable: true + showAllOutcomes: + type: boolean + nullable: true + showMarketImages: + type: boolean + nullable: true + automaticallyResolved: + type: boolean + nullable: true + enableNegRisk: + type: boolean + nullable: true + automaticallyActive: + type: boolean + nullable: true + eventDate: + type: string + nullable: true + startTime: + type: string + format: date-time + nullable: true + eventWeek: + type: integer + nullable: true + seriesSlug: + type: string + nullable: true + score: + type: string + nullable: true + elapsed: + type: string + nullable: true + period: + type: string + nullable: true + live: + type: boolean + nullable: true + ended: + type: boolean + nullable: true + finishedTimestamp: + type: string + format: date-time + nullable: true + gmpChartMode: + type: string + nullable: true + eventCreators: + type: array + items: + $ref: '#/components/schemas/EventCreator' + tweetCount: + type: integer + nullable: true + chats: + type: array + items: + $ref: '#/components/schemas/Chat' + featuredOrder: + type: integer + nullable: true + estimateValue: + type: boolean + nullable: true + cantEstimate: + type: boolean + nullable: true + estimatedValue: + type: string + nullable: true + templates: + type: array + items: + $ref: '#/components/schemas/Template' + spreadsMainLine: + type: number + nullable: true + totalsMainLine: + type: number + nullable: true + carouselMap: + type: string + nullable: true + pendingDeployment: + type: boolean + nullable: true + deploying: + type: boolean + nullable: true + deployingTimestamp: + type: string + format: date-time + nullable: true + scheduledDeploymentTimestamp: + type: string + format: date-time + nullable: true + gameStatus: + type: string + nullable: true + Collection: + type: object + properties: + id: + type: string + ticker: + type: string + nullable: true + slug: + type: string + nullable: true + title: + type: string + nullable: true + subtitle: + type: string + nullable: true + collectionType: + type: string + nullable: true + description: + type: string + nullable: true + tags: + type: string + nullable: true + image: + type: string + nullable: true + icon: + type: string + nullable: true + headerImage: + type: string + nullable: true + layout: + type: string + nullable: true + active: + type: boolean + nullable: true + closed: + type: boolean + nullable: true + archived: + type: boolean + nullable: true + new: + type: boolean + nullable: true + featured: + type: boolean + nullable: true + restricted: + type: boolean + nullable: true + isTemplate: + type: boolean + nullable: true + templateVariables: + type: string + nullable: true + publishedAt: + type: string + nullable: true + createdBy: + type: string + nullable: true + updatedBy: + type: string + nullable: true + createdAt: + type: string + format: date-time + nullable: true + updatedAt: + type: string + format: date-time + nullable: true + commentsEnabled: + type: boolean + nullable: true + imageOptimized: + $ref: '#/components/schemas/ImageOptimization' + iconOptimized: + $ref: '#/components/schemas/ImageOptimization' + headerImageOptimized: + $ref: '#/components/schemas/ImageOptimization' + Category: + type: object + properties: + id: + type: string + label: + type: string + nullable: true + parentCategory: + type: string + nullable: true + slug: + type: string + nullable: true + publishedAt: + type: string + nullable: true + createdBy: + type: string + nullable: true + updatedBy: + type: string + nullable: true + createdAt: + type: string + format: date-time + nullable: true + updatedAt: + type: string + format: date-time + nullable: true + Tag: + type: object + properties: + id: + type: string + label: + type: string + nullable: true + slug: + type: string + nullable: true + forceShow: + type: boolean + nullable: true + publishedAt: + type: string + nullable: true + createdBy: + type: integer + nullable: true + updatedBy: + type: integer + nullable: true + createdAt: + type: string + format: date-time + nullable: true + updatedAt: + type: string + format: date-time + nullable: true + forceHide: + type: boolean + nullable: true + isCarousel: + type: boolean + nullable: true + Chat: + type: object + properties: + id: + type: string + channelId: + type: string + nullable: true + channelName: + type: string + nullable: true + channelImage: + type: string + nullable: true + live: + type: boolean + nullable: true + startTime: + type: string + format: date-time + nullable: true + endTime: + type: string + format: date-time + nullable: true + ImageOptimization: + type: object + properties: + id: + type: string + imageUrlSource: + type: string + nullable: true + imageUrlOptimized: + type: string + nullable: true + imageSizeKbSource: + type: number + nullable: true + imageSizeKbOptimized: + type: number + nullable: true + imageOptimizedComplete: + type: boolean + nullable: true + imageOptimizedLastUpdated: + type: string + nullable: true + relID: + type: integer + nullable: true + field: + type: string + nullable: true + relname: + type: string + nullable: true + Market: + type: object + properties: + id: + type: string + question: + type: string + nullable: true + conditionId: + type: string + slug: + type: string + nullable: true + twitterCardImage: + type: string + nullable: true + resolutionSource: + type: string + nullable: true + endDate: + type: string + format: date-time + nullable: true + category: + type: string + nullable: true + ammType: + type: string + nullable: true + liquidity: + type: string + nullable: true + sponsorName: + type: string + nullable: true + sponsorImage: + type: string + nullable: true + startDate: + type: string + format: date-time + nullable: true + xAxisValue: + type: string + nullable: true + yAxisValue: + type: string + nullable: true + denominationToken: + type: string + nullable: true + fee: + type: string + nullable: true + image: + type: string + nullable: true + icon: + type: string + nullable: true + lowerBound: + type: string + nullable: true + upperBound: + type: string + nullable: true + description: + type: string + nullable: true + outcomes: + type: string + nullable: true + outcomePrices: + type: string + nullable: true + volume: + type: string + nullable: true + active: + type: boolean + nullable: true + marketType: + type: string + nullable: true + formatType: + type: string + nullable: true + lowerBoundDate: + type: string + nullable: true + upperBoundDate: + type: string + nullable: true + closed: + type: boolean + nullable: true + marketMakerAddress: + type: string + createdBy: + type: integer + nullable: true + updatedBy: + type: integer + nullable: true + createdAt: + type: string + format: date-time + nullable: true + updatedAt: + type: string + format: date-time + nullable: true + closedTime: + type: string + nullable: true + wideFormat: + type: boolean + nullable: true + new: + type: boolean + nullable: true + mailchimpTag: + type: string + nullable: true + featured: + type: boolean + nullable: true + archived: + type: boolean + nullable: true + resolvedBy: + type: string + nullable: true + restricted: + type: boolean + nullable: true + marketGroup: + type: integer + nullable: true + groupItemTitle: + type: string + nullable: true + groupItemThreshold: + type: string + nullable: true + questionID: + type: string + nullable: true + umaEndDate: + type: string + nullable: true + enableOrderBook: + type: boolean + nullable: true + orderPriceMinTickSize: + type: number + nullable: true + orderMinSize: + type: number + nullable: true + umaResolutionStatus: + type: string + nullable: true + curationOrder: + type: integer + nullable: true + volumeNum: + type: number + nullable: true + liquidityNum: + type: number + nullable: true + endDateIso: + type: string + nullable: true + startDateIso: + type: string + nullable: true + umaEndDateIso: + type: string + nullable: true + hasReviewedDates: + type: boolean + nullable: true + readyForCron: + type: boolean + nullable: true + commentsEnabled: + type: boolean + nullable: true + volume24hr: + type: number + nullable: true + volume1wk: + type: number + nullable: true + volume1mo: + type: number + nullable: true + volume1yr: + type: number + nullable: true + gameStartTime: + type: string + nullable: true + secondsDelay: + type: integer + nullable: true + clobTokenIds: + type: string + nullable: true + disqusThread: + type: string + nullable: true + shortOutcomes: + type: string + nullable: true + teamAID: + type: string + nullable: true + teamBID: + type: string + nullable: true + umaBond: + type: string + nullable: true + umaReward: + type: string + nullable: true + fpmmLive: + type: boolean + nullable: true + volume24hrAmm: + type: number + nullable: true + volume1wkAmm: + type: number + nullable: true + volume1moAmm: + type: number + nullable: true + volume1yrAmm: + type: number + nullable: true + volume24hrClob: + type: number + nullable: true + volume1wkClob: + type: number + nullable: true + volume1moClob: + type: number + nullable: true + volume1yrClob: + type: number + nullable: true + volumeAmm: + type: number + nullable: true + volumeClob: + type: number + nullable: true + liquidityAmm: + type: number + nullable: true + liquidityClob: + type: number + nullable: true + makerBaseFee: + type: integer + nullable: true + takerBaseFee: + type: integer + nullable: true + customLiveness: + type: integer + nullable: true + acceptingOrders: + type: boolean + nullable: true + notificationsEnabled: + type: boolean + nullable: true + score: + type: integer + nullable: true + imageOptimized: + $ref: '#/components/schemas/ImageOptimization' + iconOptimized: + $ref: '#/components/schemas/ImageOptimization' + events: + type: array + items: + $ref: '#/components/schemas/Event' + categories: + type: array + items: + $ref: '#/components/schemas/Category' + tags: + type: array + items: + $ref: '#/components/schemas/Tag' + creator: + type: string + nullable: true + ready: + type: boolean + nullable: true + funded: + type: boolean + nullable: true + pastSlugs: + type: string + nullable: true + readyTimestamp: + type: string + format: date-time + nullable: true + fundedTimestamp: + type: string + format: date-time + nullable: true + acceptingOrdersTimestamp: + type: string + format: date-time + nullable: true + competitive: + type: number + nullable: true + rewardsMinSize: + type: number + nullable: true + rewardsMaxSpread: + type: number + nullable: true + spread: + type: number + nullable: true + automaticallyResolved: + type: boolean + nullable: true + oneDayPriceChange: + type: number + nullable: true + oneHourPriceChange: + type: number + nullable: true + oneWeekPriceChange: + type: number + nullable: true + oneMonthPriceChange: + type: number + nullable: true + oneYearPriceChange: + type: number + nullable: true + lastTradePrice: + type: number + nullable: true + bestBid: + type: number + nullable: true + bestAsk: + type: number + nullable: true + automaticallyActive: + type: boolean + nullable: true + clearBookOnStart: + type: boolean + nullable: true + chartColor: + type: string + nullable: true + seriesColor: + type: string + nullable: true + showGmpSeries: + type: boolean + nullable: true + showGmpOutcome: + type: boolean + nullable: true + manualActivation: + type: boolean + nullable: true + negRiskOther: + type: boolean + nullable: true + gameId: + type: string + nullable: true + groupItemRange: + type: string + nullable: true + sportsMarketType: + type: string + nullable: true + line: + type: number + nullable: true + umaResolutionStatuses: + type: string + nullable: true + pendingDeployment: + type: boolean + nullable: true + deploying: + type: boolean + nullable: true + deployingTimestamp: + type: string + format: date-time + nullable: true + scheduledDeploymentTimestamp: + type: string + format: date-time + nullable: true + rfqEnabled: + type: boolean + nullable: true + eventStartTime: + type: string + format: date-time + nullable: true + feesEnabled: + type: boolean + nullable: true + feeSchedule: + $ref: '#/components/schemas/FeeSchedule' + EventCreator: + type: object + properties: + id: + type: string + creatorName: + type: string + nullable: true + creatorHandle: + type: string + nullable: true + creatorUrl: + type: string + nullable: true + creatorImage: + type: string + nullable: true + createdAt: + type: string + format: date-time + nullable: true + updatedAt: + type: string + format: date-time + nullable: true + Template: + type: object + properties: + id: + type: string + eventTitle: + type: string + nullable: true + eventSlug: + type: string + nullable: true + eventImage: + type: string + nullable: true + marketTitle: + type: string + nullable: true + description: + type: string + nullable: true + resolutionSource: + type: string + nullable: true + negRisk: + type: boolean + nullable: true + sortBy: + type: string + nullable: true + showMarketImages: + type: boolean + nullable: true + seriesSlug: + type: string + nullable: true + outcomes: + type: string + nullable: true + FeeSchedule: + type: object + properties: + exponent: + type: number + nullable: true + rate: + type: number + nullable: true + takerOnly: + type: boolean + nullable: true + rebateRate: + type: number + nullable: true + +```` \ No newline at end of file diff --git a/PolymarketDocumentation-main/docs/api-reference/series/list-series.md b/PolymarketDocumentation-main/docs/api-reference/series/list-series.md new file mode 100644 index 00000000..10b9f879 --- /dev/null +++ b/PolymarketDocumentation-main/docs/api-reference/series/list-series.md @@ -0,0 +1,1259 @@ +> ## Documentation Index +> Fetch the complete documentation index at: https://docs.polymarket.com/llms.txt +> Use this file to discover all available pages before exploring further. + +# List series + + + +## OpenAPI + +````yaml /api-spec/gamma-openapi.yaml get /series +openapi: 3.0.3 +info: + title: Markets API + version: 1.0.0 + description: REST API specification for public endpoints used by the Markets service. +servers: + - url: https://gamma-api.polymarket.com + description: Polymarket Gamma API Production Server +security: [] +tags: + - name: Gamma Status + description: Gamma API status and health check + - name: Sports + description: Sports-related endpoints including teams and game data + - name: Tags + description: Tag management and related tag operations + - name: Events + description: Event management and event-related operations + - name: Markets + description: Market data and market-related operations + - name: Comments + description: Comment system and user interactions + - name: Series + description: Series management and related operations + - name: Profiles + description: User profile management + - name: Search + description: Search functionality across different entity types +paths: + /series: + get: + tags: + - Series + summary: List series + operationId: listSeries + parameters: + - $ref: '#/components/parameters/limit' + - $ref: '#/components/parameters/offset' + - $ref: '#/components/parameters/order' + - $ref: '#/components/parameters/ascending' + - name: slug + in: query + schema: + type: array + items: + type: string + - name: categories_ids + in: query + schema: + type: array + items: + type: integer + - name: categories_labels + in: query + schema: + type: array + items: + type: string + - name: closed + in: query + schema: + type: boolean + - name: include_chat + in: query + schema: + type: boolean + - name: recurrence + in: query + schema: + type: string + - name: exclude_events + in: query + schema: + type: boolean + responses: + '200': + description: List of series + content: + application/json: + schema: + type: array + items: + $ref: '#/components/schemas/Series' +components: + parameters: + limit: + name: limit + in: query + schema: + type: integer + minimum: 0 + offset: + name: offset + in: query + schema: + type: integer + minimum: 0 + order: + name: order + in: query + schema: + type: string + description: Comma-separated list of fields to order by + ascending: + name: ascending + in: query + schema: + type: boolean + schemas: + Series: + type: object + properties: + id: + type: string + ticker: + type: string + nullable: true + slug: + type: string + nullable: true + title: + type: string + nullable: true + subtitle: + type: string + nullable: true + seriesType: + type: string + nullable: true + recurrence: + type: string + nullable: true + description: + type: string + nullable: true + image: + type: string + nullable: true + icon: + type: string + nullable: true + layout: + type: string + nullable: true + active: + type: boolean + nullable: true + closed: + type: boolean + nullable: true + archived: + type: boolean + nullable: true + new: + type: boolean + nullable: true + featured: + type: boolean + nullable: true + restricted: + type: boolean + nullable: true + isTemplate: + type: boolean + nullable: true + templateVariables: + type: boolean + nullable: true + publishedAt: + type: string + nullable: true + createdBy: + type: string + nullable: true + updatedBy: + type: string + nullable: true + createdAt: + type: string + format: date-time + nullable: true + updatedAt: + type: string + format: date-time + nullable: true + commentsEnabled: + type: boolean + nullable: true + competitive: + type: string + nullable: true + volume24hr: + type: number + nullable: true + volume: + type: number + nullable: true + liquidity: + type: number + nullable: true + startDate: + type: string + format: date-time + nullable: true + pythTokenID: + type: string + nullable: true + cgAssetName: + type: string + nullable: true + score: + type: integer + nullable: true + events: + type: array + items: + $ref: '#/components/schemas/Event' + collections: + type: array + items: + $ref: '#/components/schemas/Collection' + categories: + type: array + items: + $ref: '#/components/schemas/Category' + tags: + type: array + items: + $ref: '#/components/schemas/Tag' + commentCount: + type: integer + nullable: true + chats: + type: array + items: + $ref: '#/components/schemas/Chat' + Event: + type: object + properties: + id: + type: string + ticker: + type: string + nullable: true + slug: + type: string + nullable: true + title: + type: string + nullable: true + subtitle: + type: string + nullable: true + description: + type: string + nullable: true + resolutionSource: + type: string + nullable: true + startDate: + type: string + format: date-time + nullable: true + creationDate: + type: string + format: date-time + nullable: true + endDate: + type: string + format: date-time + nullable: true + image: + type: string + nullable: true + icon: + type: string + nullable: true + active: + type: boolean + nullable: true + closed: + type: boolean + nullable: true + archived: + type: boolean + nullable: true + new: + type: boolean + nullable: true + featured: + type: boolean + nullable: true + restricted: + type: boolean + nullable: true + liquidity: + type: number + nullable: true + volume: + type: number + nullable: true + openInterest: + type: number + nullable: true + sortBy: + type: string + nullable: true + category: + type: string + nullable: true + subcategory: + type: string + nullable: true + isTemplate: + type: boolean + nullable: true + templateVariables: + type: string + nullable: true + published_at: + type: string + nullable: true + createdBy: + type: string + nullable: true + updatedBy: + type: string + nullable: true + createdAt: + type: string + format: date-time + nullable: true + updatedAt: + type: string + format: date-time + nullable: true + commentsEnabled: + type: boolean + nullable: true + competitive: + type: number + nullable: true + volume24hr: + type: number + nullable: true + volume1wk: + type: number + nullable: true + volume1mo: + type: number + nullable: true + volume1yr: + type: number + nullable: true + featuredImage: + type: string + nullable: true + disqusThread: + type: string + nullable: true + parentEvent: + type: string + nullable: true + enableOrderBook: + type: boolean + nullable: true + liquidityAmm: + type: number + nullable: true + liquidityClob: + type: number + nullable: true + negRisk: + type: boolean + nullable: true + negRiskMarketID: + type: string + nullable: true + negRiskFeeBips: + type: integer + nullable: true + commentCount: + type: integer + nullable: true + imageOptimized: + $ref: '#/components/schemas/ImageOptimization' + iconOptimized: + $ref: '#/components/schemas/ImageOptimization' + featuredImageOptimized: + $ref: '#/components/schemas/ImageOptimization' + subEvents: + type: array + items: + type: string + nullable: true + markets: + type: array + items: + $ref: '#/components/schemas/Market' + series: + type: array + items: + $ref: '#/components/schemas/Series' + categories: + type: array + items: + $ref: '#/components/schemas/Category' + collections: + type: array + items: + $ref: '#/components/schemas/Collection' + tags: + type: array + items: + $ref: '#/components/schemas/Tag' + cyom: + type: boolean + nullable: true + closedTime: + type: string + format: date-time + nullable: true + showAllOutcomes: + type: boolean + nullable: true + showMarketImages: + type: boolean + nullable: true + automaticallyResolved: + type: boolean + nullable: true + enableNegRisk: + type: boolean + nullable: true + automaticallyActive: + type: boolean + nullable: true + eventDate: + type: string + nullable: true + startTime: + type: string + format: date-time + nullable: true + eventWeek: + type: integer + nullable: true + seriesSlug: + type: string + nullable: true + score: + type: string + nullable: true + elapsed: + type: string + nullable: true + period: + type: string + nullable: true + live: + type: boolean + nullable: true + ended: + type: boolean + nullable: true + finishedTimestamp: + type: string + format: date-time + nullable: true + gmpChartMode: + type: string + nullable: true + eventCreators: + type: array + items: + $ref: '#/components/schemas/EventCreator' + tweetCount: + type: integer + nullable: true + chats: + type: array + items: + $ref: '#/components/schemas/Chat' + featuredOrder: + type: integer + nullable: true + estimateValue: + type: boolean + nullable: true + cantEstimate: + type: boolean + nullable: true + estimatedValue: + type: string + nullable: true + templates: + type: array + items: + $ref: '#/components/schemas/Template' + spreadsMainLine: + type: number + nullable: true + totalsMainLine: + type: number + nullable: true + carouselMap: + type: string + nullable: true + pendingDeployment: + type: boolean + nullable: true + deploying: + type: boolean + nullable: true + deployingTimestamp: + type: string + format: date-time + nullable: true + scheduledDeploymentTimestamp: + type: string + format: date-time + nullable: true + gameStatus: + type: string + nullable: true + Collection: + type: object + properties: + id: + type: string + ticker: + type: string + nullable: true + slug: + type: string + nullable: true + title: + type: string + nullable: true + subtitle: + type: string + nullable: true + collectionType: + type: string + nullable: true + description: + type: string + nullable: true + tags: + type: string + nullable: true + image: + type: string + nullable: true + icon: + type: string + nullable: true + headerImage: + type: string + nullable: true + layout: + type: string + nullable: true + active: + type: boolean + nullable: true + closed: + type: boolean + nullable: true + archived: + type: boolean + nullable: true + new: + type: boolean + nullable: true + featured: + type: boolean + nullable: true + restricted: + type: boolean + nullable: true + isTemplate: + type: boolean + nullable: true + templateVariables: + type: string + nullable: true + publishedAt: + type: string + nullable: true + createdBy: + type: string + nullable: true + updatedBy: + type: string + nullable: true + createdAt: + type: string + format: date-time + nullable: true + updatedAt: + type: string + format: date-time + nullable: true + commentsEnabled: + type: boolean + nullable: true + imageOptimized: + $ref: '#/components/schemas/ImageOptimization' + iconOptimized: + $ref: '#/components/schemas/ImageOptimization' + headerImageOptimized: + $ref: '#/components/schemas/ImageOptimization' + Category: + type: object + properties: + id: + type: string + label: + type: string + nullable: true + parentCategory: + type: string + nullable: true + slug: + type: string + nullable: true + publishedAt: + type: string + nullable: true + createdBy: + type: string + nullable: true + updatedBy: + type: string + nullable: true + createdAt: + type: string + format: date-time + nullable: true + updatedAt: + type: string + format: date-time + nullable: true + Tag: + type: object + properties: + id: + type: string + label: + type: string + nullable: true + slug: + type: string + nullable: true + forceShow: + type: boolean + nullable: true + publishedAt: + type: string + nullable: true + createdBy: + type: integer + nullable: true + updatedBy: + type: integer + nullable: true + createdAt: + type: string + format: date-time + nullable: true + updatedAt: + type: string + format: date-time + nullable: true + forceHide: + type: boolean + nullable: true + isCarousel: + type: boolean + nullable: true + Chat: + type: object + properties: + id: + type: string + channelId: + type: string + nullable: true + channelName: + type: string + nullable: true + channelImage: + type: string + nullable: true + live: + type: boolean + nullable: true + startTime: + type: string + format: date-time + nullable: true + endTime: + type: string + format: date-time + nullable: true + ImageOptimization: + type: object + properties: + id: + type: string + imageUrlSource: + type: string + nullable: true + imageUrlOptimized: + type: string + nullable: true + imageSizeKbSource: + type: number + nullable: true + imageSizeKbOptimized: + type: number + nullable: true + imageOptimizedComplete: + type: boolean + nullable: true + imageOptimizedLastUpdated: + type: string + nullable: true + relID: + type: integer + nullable: true + field: + type: string + nullable: true + relname: + type: string + nullable: true + Market: + type: object + properties: + id: + type: string + question: + type: string + nullable: true + conditionId: + type: string + slug: + type: string + nullable: true + twitterCardImage: + type: string + nullable: true + resolutionSource: + type: string + nullable: true + endDate: + type: string + format: date-time + nullable: true + category: + type: string + nullable: true + ammType: + type: string + nullable: true + liquidity: + type: string + nullable: true + sponsorName: + type: string + nullable: true + sponsorImage: + type: string + nullable: true + startDate: + type: string + format: date-time + nullable: true + xAxisValue: + type: string + nullable: true + yAxisValue: + type: string + nullable: true + denominationToken: + type: string + nullable: true + fee: + type: string + nullable: true + image: + type: string + nullable: true + icon: + type: string + nullable: true + lowerBound: + type: string + nullable: true + upperBound: + type: string + nullable: true + description: + type: string + nullable: true + outcomes: + type: string + nullable: true + outcomePrices: + type: string + nullable: true + volume: + type: string + nullable: true + active: + type: boolean + nullable: true + marketType: + type: string + nullable: true + formatType: + type: string + nullable: true + lowerBoundDate: + type: string + nullable: true + upperBoundDate: + type: string + nullable: true + closed: + type: boolean + nullable: true + marketMakerAddress: + type: string + createdBy: + type: integer + nullable: true + updatedBy: + type: integer + nullable: true + createdAt: + type: string + format: date-time + nullable: true + updatedAt: + type: string + format: date-time + nullable: true + closedTime: + type: string + nullable: true + wideFormat: + type: boolean + nullable: true + new: + type: boolean + nullable: true + mailchimpTag: + type: string + nullable: true + featured: + type: boolean + nullable: true + archived: + type: boolean + nullable: true + resolvedBy: + type: string + nullable: true + restricted: + type: boolean + nullable: true + marketGroup: + type: integer + nullable: true + groupItemTitle: + type: string + nullable: true + groupItemThreshold: + type: string + nullable: true + questionID: + type: string + nullable: true + umaEndDate: + type: string + nullable: true + enableOrderBook: + type: boolean + nullable: true + orderPriceMinTickSize: + type: number + nullable: true + orderMinSize: + type: number + nullable: true + umaResolutionStatus: + type: string + nullable: true + curationOrder: + type: integer + nullable: true + volumeNum: + type: number + nullable: true + liquidityNum: + type: number + nullable: true + endDateIso: + type: string + nullable: true + startDateIso: + type: string + nullable: true + umaEndDateIso: + type: string + nullable: true + hasReviewedDates: + type: boolean + nullable: true + readyForCron: + type: boolean + nullable: true + commentsEnabled: + type: boolean + nullable: true + volume24hr: + type: number + nullable: true + volume1wk: + type: number + nullable: true + volume1mo: + type: number + nullable: true + volume1yr: + type: number + nullable: true + gameStartTime: + type: string + nullable: true + secondsDelay: + type: integer + nullable: true + clobTokenIds: + type: string + nullable: true + disqusThread: + type: string + nullable: true + shortOutcomes: + type: string + nullable: true + teamAID: + type: string + nullable: true + teamBID: + type: string + nullable: true + umaBond: + type: string + nullable: true + umaReward: + type: string + nullable: true + fpmmLive: + type: boolean + nullable: true + volume24hrAmm: + type: number + nullable: true + volume1wkAmm: + type: number + nullable: true + volume1moAmm: + type: number + nullable: true + volume1yrAmm: + type: number + nullable: true + volume24hrClob: + type: number + nullable: true + volume1wkClob: + type: number + nullable: true + volume1moClob: + type: number + nullable: true + volume1yrClob: + type: number + nullable: true + volumeAmm: + type: number + nullable: true + volumeClob: + type: number + nullable: true + liquidityAmm: + type: number + nullable: true + liquidityClob: + type: number + nullable: true + makerBaseFee: + type: integer + nullable: true + takerBaseFee: + type: integer + nullable: true + customLiveness: + type: integer + nullable: true + acceptingOrders: + type: boolean + nullable: true + notificationsEnabled: + type: boolean + nullable: true + score: + type: integer + nullable: true + imageOptimized: + $ref: '#/components/schemas/ImageOptimization' + iconOptimized: + $ref: '#/components/schemas/ImageOptimization' + events: + type: array + items: + $ref: '#/components/schemas/Event' + categories: + type: array + items: + $ref: '#/components/schemas/Category' + tags: + type: array + items: + $ref: '#/components/schemas/Tag' + creator: + type: string + nullable: true + ready: + type: boolean + nullable: true + funded: + type: boolean + nullable: true + pastSlugs: + type: string + nullable: true + readyTimestamp: + type: string + format: date-time + nullable: true + fundedTimestamp: + type: string + format: date-time + nullable: true + acceptingOrdersTimestamp: + type: string + format: date-time + nullable: true + competitive: + type: number + nullable: true + rewardsMinSize: + type: number + nullable: true + rewardsMaxSpread: + type: number + nullable: true + spread: + type: number + nullable: true + automaticallyResolved: + type: boolean + nullable: true + oneDayPriceChange: + type: number + nullable: true + oneHourPriceChange: + type: number + nullable: true + oneWeekPriceChange: + type: number + nullable: true + oneMonthPriceChange: + type: number + nullable: true + oneYearPriceChange: + type: number + nullable: true + lastTradePrice: + type: number + nullable: true + bestBid: + type: number + nullable: true + bestAsk: + type: number + nullable: true + automaticallyActive: + type: boolean + nullable: true + clearBookOnStart: + type: boolean + nullable: true + chartColor: + type: string + nullable: true + seriesColor: + type: string + nullable: true + showGmpSeries: + type: boolean + nullable: true + showGmpOutcome: + type: boolean + nullable: true + manualActivation: + type: boolean + nullable: true + negRiskOther: + type: boolean + nullable: true + gameId: + type: string + nullable: true + groupItemRange: + type: string + nullable: true + sportsMarketType: + type: string + nullable: true + line: + type: number + nullable: true + umaResolutionStatuses: + type: string + nullable: true + pendingDeployment: + type: boolean + nullable: true + deploying: + type: boolean + nullable: true + deployingTimestamp: + type: string + format: date-time + nullable: true + scheduledDeploymentTimestamp: + type: string + format: date-time + nullable: true + rfqEnabled: + type: boolean + nullable: true + eventStartTime: + type: string + format: date-time + nullable: true + feesEnabled: + type: boolean + nullable: true + feeSchedule: + $ref: '#/components/schemas/FeeSchedule' + EventCreator: + type: object + properties: + id: + type: string + creatorName: + type: string + nullable: true + creatorHandle: + type: string + nullable: true + creatorUrl: + type: string + nullable: true + creatorImage: + type: string + nullable: true + createdAt: + type: string + format: date-time + nullable: true + updatedAt: + type: string + format: date-time + nullable: true + Template: + type: object + properties: + id: + type: string + eventTitle: + type: string + nullable: true + eventSlug: + type: string + nullable: true + eventImage: + type: string + nullable: true + marketTitle: + type: string + nullable: true + description: + type: string + nullable: true + resolutionSource: + type: string + nullable: true + negRisk: + type: boolean + nullable: true + sortBy: + type: string + nullable: true + showMarketImages: + type: boolean + nullable: true + seriesSlug: + type: string + nullable: true + outcomes: + type: string + nullable: true + FeeSchedule: + type: object + properties: + exponent: + type: number + nullable: true + rate: + type: number + nullable: true + takerOnly: + type: boolean + nullable: true + rebateRate: + type: number + nullable: true + +```` \ No newline at end of file diff --git a/PolymarketDocumentation-main/docs/api-reference/set-auto-cancel.md b/PolymarketDocumentation-main/docs/api-reference/set-auto-cancel.md new file mode 100644 index 00000000..b6f08b22 --- /dev/null +++ b/PolymarketDocumentation-main/docs/api-reference/set-auto-cancel.md @@ -0,0 +1,364 @@ +> ## Documentation Index +> Fetch the complete documentation index at: https://docs.polymarket.com/llms.txt +> Use this file to discover all available pages before exploring further. + +# Set Auto-Cancel + +> Set a dead man switch that will cancel all open orders at the specified time. +Time must be at least 5 seconds in the future, or `0` to clear an active +schedule without triggering it. Posting a new auto-cancel replaces the +previous one. + +The switch is one-shot: once the deadline elapses and your open orders are +cancelled, the schedule clears automatically. Orders you place after the +fire are not affected by the expired deadline — re-arm to extend +protection. + +Each account may trigger auto-cancel at most 10 times per UTC day. Once +that limit is reached, further attempts to arm a schedule are rejected with +`auto_cancel_daily_limit_reached` until the next UTC day; clearing an +existing schedule (`time: 0`) is always allowed. + +Use `GET /v1/account/auto-cancel` to check the current deadline, today's +trigger count, and when the daily counter resets. + +Requires proxy signature, see [proxy signing](/http/signing#2-proxy-signing). + + +Request Weight: **1** Action Weight: **10** + + +## OpenAPI + +````yaml /api-spec/perps-openapi.json patch /v1/trade/auto-cancel +openapi: 3.0.3 +info: + title: Polymarket Perps HTTP API + version: 1.0.0 + description: HTTP API for Polymarket perpetual trading system. + license: + name: Apache 2.0 + url: https://www.apache.org/licenses/LICENSE-2.0.html +servers: + - url: https://api.perpetuals.polymarket.com + description: Production Perps HTTP API +security: [] +paths: + /v1/trade/auto-cancel: + patch: + summary: Set Auto-Cancel + description: > + Set a dead man switch that will cancel all open orders at the specified + time. + + Time must be at least 5 seconds in the future, or `0` to clear an active + + schedule without triggering it. Posting a new auto-cancel replaces the + + previous one. + + + The switch is one-shot: once the deadline elapses and your open orders + are + + cancelled, the schedule clears automatically. Orders you place after the + + fire are not affected by the expired deadline — re-arm to extend + + protection. + + + Each account may trigger auto-cancel at most 10 times per UTC day. Once + + that limit is reached, further attempts to arm a schedule are rejected + with + + `auto_cancel_daily_limit_reached` until the next UTC day; clearing an + + existing schedule (`time: 0`) is always allowed. + + + Use `GET /v1/account/auto-cancel` to check the current deadline, today's + + trigger count, and when the daily counter resets. + + + Requires proxy signature, see [proxy + signing](/http/signing#2-proxy-signing). + operationId: setAutoCancel + requestBody: + description: Auto-cancel request. + content: + application/json: + schema: + $ref: '#/components/schemas/AutoCancelRequest' + examples: + enable: + summary: Enable auto-cancel + value: + op: + type: autoCancel + args: + time: 1767000045000 + sig: >- + 0x2b3c4d5e6f7a8b9c0d1e2f3a4b5c6d7e8f9a0b1c2d3e4f5a6b7c8d9e0f1a2b3c4d5e6f7a8b9c0d1e2f3a4b5c6d7e8f9a0b1c2d3e4f5a6b7c8d9e0f1a2b1c + salt: 666666666 + ts: 1767000015000 + disable: + summary: Disable auto-cancel + value: + op: + type: autoCancel + args: + time: 0 + sig: >- + 0x8f9a0b1c2d3e4f5a6b7c8d9e0f1a2b3c4d5e6f7a8b9c0d1e2f3a4b5c6d7e8f9a0b1c2d3e4f5a6b7c8d9e0f1a2b3c4d5e6f7a8b9c0d1e2f3a4b5c6d7e8f1c + salt: 666666667 + ts: 1767000016000 + responses: + '200': + description: The effective auto-cancel schedule after the update. + content: + application/json: + schema: + $ref: '#/components/schemas/AutoCancelResponse' + '400': + $ref: '#/components/responses/Error400Response' + '404': + $ref: '#/components/responses/Error404Response' + '422': + $ref: '#/components/responses/Error422Response' + '429': + $ref: '#/components/responses/Error429Response' + '500': + $ref: '#/components/responses/Error500Response' + security: [] +components: + schemas: + AutoCancelRequest: + allOf: + - type: object + required: + - op + properties: + op: + $ref: '#/components/schemas/OpAutoCancel' + - $ref: '#/components/schemas/BaseOp' + AutoCancelResponse: + description: > + The effective auto-cancel schedule after the update. `deadline` echoes + the + + armed Unix-ms time, or `0` when the schedule was cleared (`time: 0`). + type: object + required: + - status + - deadline + properties: + status: + type: string + enum: + - ok + deadline: + $ref: '#/components/schemas/auto_cancel_deadline' + OpAutoCancel: + type: object + required: + - type + - args + properties: + type: + type: string + enum: + - autoCancel + args: + type: object + required: + - time + properties: + time: + $ref: '#/components/schemas/time' + BaseOp: + type: object + required: + - sig + - salt + - ts + properties: + sig: + $ref: '#/components/schemas/sig' + salt: + $ref: '#/components/schemas/salt' + ts: + $ref: '#/components/schemas/ts' + auto_cancel_deadline: + type: integer + description: | + Unix-ms deadline for the per-account auto-cancel dead-man-switch. + Zero means no schedule is armed. When the deadline elapses, every + open order on the account is cancelled and the schedule clears. + example: 1767000045000 + Error400: + title: Error400 + type: object + required: + - status + - error + properties: + status: + type: string + enum: + - err + error: + $ref: '#/components/schemas/error' + Error404: + title: Error404 + type: object + required: + - status + - error + properties: + status: + type: string + enum: + - err + error: + $ref: '#/components/schemas/error' + GenericRejected: + type: object + required: + - status + - error + properties: + status: + type: string + enum: + - err + error: + $ref: '#/components/schemas/error' + Error429: + title: Error429 + type: object + required: + - status + - error + properties: + status: + type: string + enum: + - err + error: + $ref: '#/components/schemas/error' + Error500: + title: Error500 + type: object + required: + - status + - error + properties: + status: + type: string + enum: + - err + error: + $ref: '#/components/schemas/error' + time: + type: integer + description: Timestamp in milliseconds + example: 1767225600000 + sig: + type: string + description: Signature in hex format + example: 0x1234567890... + salt: + type: integer + description: Salt + example: 1234567890 + ts: + type: integer + description: >- + Request timestamp. Unix milliseconds for most operations; Unix seconds + for withdrawals (must match the on-chain EIP-712 struct verified against + block.timestamp). + example: 1767225600000 + error: + type: string + description: >- + Error identifier. For domain rejections and transport errors + (`401`/`404`/`429`/`500`) this is a stable, machine-readable snake_case + identifier that is part of the API contract and safe to branch on, e.g. + `insufficient_margin`, `insufficient_balance`, `order_not_found`, + `reduce_only_invalid`, `unauthorized`, `not_found`. For `400` it is a + human-readable validation detail whose wording may change. See the Error + handling guide for the domain identifiers. (Post-only / Fill-or-Kill + outcomes are order statuses such as `post_only_rejected`, not + rejections.) + example: insufficient_margin + responses: + Error400Response: + description: | + Bad request — the request was malformed or failed validation (bad query + parameters, unparseable body, invalid signature, or a domain pre-check). + The `error` field is a human-readable validation detail. + content: + application/json: + schema: + $ref: '#/components/schemas/Error400' + Error404Response: + description: | + Not found — the endpoint is disabled on this venue (e.g. auto-cancel) or + the route does not exist. `error` is `not_found`. + content: + application/json: + schema: + $ref: '#/components/schemas/Error404' + Error422Response: + description: | + Unprocessable Entity — the request was well-formed but a domain rule + rejected it on its merits (insufficient balance, invalid leverage, + proxy already exists, …). The body is the discriminated rejection + (`status: err`) with the engine error identifier in `error`. + content: + application/json: + schema: + $ref: '#/components/schemas/GenericRejected' + Error429Response: + description: > + Too Many Requests. `error` distinguishes the limit that was hit: + + `ip_rate_limited` (per-IP token bucket), `action_rate_limited` + (per-account + + action rate), or `open_orders_limit` (resting open-order cap). + headers: + Retry-After: + description: > + Whole seconds to wait before retrying. Present only on token-bucket + + rate-limit rejections (`ip_rate_limited` and `action_rate_limited`); + a + + conservative estimate of when enough capacity will have refilled to + + admit the request. Absent on `open_orders_limit`, which is a + capacity + + limit, not a rate limit — waiting does not free order slots; cancel + + resting orders or wait for fills instead. + schema: + type: integer + example: 2 + content: + application/json: + schema: + $ref: '#/components/schemas/Error429' + Error500Response: + description: | + Internal server error. `error` is `internal_error`. + content: + application/json: + schema: + $ref: '#/components/schemas/Error500' + +```` \ No newline at end of file diff --git a/PolymarketDocumentation-main/docs/api-reference/sports/get-sports-metadata-information.md b/PolymarketDocumentation-main/docs/api-reference/sports/get-sports-metadata-information.md new file mode 100644 index 00000000..006518d4 --- /dev/null +++ b/PolymarketDocumentation-main/docs/api-reference/sports/get-sports-metadata-information.md @@ -0,0 +1,90 @@ +> ## Documentation Index +> Fetch the complete documentation index at: https://docs.polymarket.com/llms.txt +> Use this file to discover all available pages before exploring further. + +# Get sports metadata information + + + +## OpenAPI + +````yaml /api-spec/gamma-openapi.yaml get /sports +openapi: 3.0.3 +info: + title: Markets API + version: 1.0.0 + description: REST API specification for public endpoints used by the Markets service. +servers: + - url: https://gamma-api.polymarket.com + description: Polymarket Gamma API Production Server +security: [] +tags: + - name: Gamma Status + description: Gamma API status and health check + - name: Sports + description: Sports-related endpoints including teams and game data + - name: Tags + description: Tag management and related tag operations + - name: Events + description: Event management and event-related operations + - name: Markets + description: Market data and market-related operations + - name: Comments + description: Comment system and user interactions + - name: Series + description: Series management and related operations + - name: Profiles + description: User profile management + - name: Search + description: Search functionality across different entity types +paths: + /sports: + get: + tags: + - Sports + summary: Get sports metadata information + operationId: getSportsMetadata + responses: + '200': + description: >- + List of sports metadata objects containing sport configuration + details, visual assets, and related identifiers + content: + application/json: + schema: + type: array + items: + $ref: '#/components/schemas/SportsMetadata' +components: + schemas: + SportsMetadata: + type: object + properties: + sport: + type: string + description: The sport identifier or abbreviation + image: + type: string + format: uri + description: URL to the sport's logo or image asset + resolution: + type: string + format: uri + description: >- + URL to the official resolution source for the sport (e.g., league + website) + ordering: + type: string + description: Preferred ordering for sport display, typically "home" or "away" + tags: + type: string + description: >- + Comma-separated list of tag IDs associated with the sport for + categorization and filtering + series: + type: string + description: >- + Series identifier linking the sport to a specific tournament or + season series + +```` \ No newline at end of file diff --git a/PolymarketDocumentation-main/docs/api-reference/sports/get-valid-sports-market-types.md b/PolymarketDocumentation-main/docs/api-reference/sports/get-valid-sports-market-types.md new file mode 100644 index 00000000..b8fe38d1 --- /dev/null +++ b/PolymarketDocumentation-main/docs/api-reference/sports/get-valid-sports-market-types.md @@ -0,0 +1,65 @@ +> ## Documentation Index +> Fetch the complete documentation index at: https://docs.polymarket.com/llms.txt +> Use this file to discover all available pages before exploring further. + +# Get valid sports market types + + + +## OpenAPI + +````yaml /api-spec/gamma-openapi.yaml get /sports/market-types +openapi: 3.0.3 +info: + title: Markets API + version: 1.0.0 + description: REST API specification for public endpoints used by the Markets service. +servers: + - url: https://gamma-api.polymarket.com + description: Polymarket Gamma API Production Server +security: [] +tags: + - name: Gamma Status + description: Gamma API status and health check + - name: Sports + description: Sports-related endpoints including teams and game data + - name: Tags + description: Tag management and related tag operations + - name: Events + description: Event management and event-related operations + - name: Markets + description: Market data and market-related operations + - name: Comments + description: Comment system and user interactions + - name: Series + description: Series management and related operations + - name: Profiles + description: User profile management + - name: Search + description: Search functionality across different entity types +paths: + /sports/market-types: + get: + tags: + - Sports + summary: Get valid sports market types + operationId: getSportsMarketTypes + responses: + '200': + description: List of valid sports market types + content: + application/json: + schema: + $ref: '#/components/schemas/SportsMarketTypesResponse' +components: + schemas: + SportsMarketTypesResponse: + type: object + properties: + marketTypes: + type: array + description: List of all valid sports market types + items: + type: string + +```` \ No newline at end of file diff --git a/PolymarketDocumentation-main/docs/api-reference/sports/list-teams.md b/PolymarketDocumentation-main/docs/api-reference/sports/list-teams.md new file mode 100644 index 00000000..5bc69f6a --- /dev/null +++ b/PolymarketDocumentation-main/docs/api-reference/sports/list-teams.md @@ -0,0 +1,137 @@ +> ## Documentation Index +> Fetch the complete documentation index at: https://docs.polymarket.com/llms.txt +> Use this file to discover all available pages before exploring further. + +# List teams + + + +## OpenAPI + +````yaml /api-spec/gamma-openapi.yaml get /teams +openapi: 3.0.3 +info: + title: Markets API + version: 1.0.0 + description: REST API specification for public endpoints used by the Markets service. +servers: + - url: https://gamma-api.polymarket.com + description: Polymarket Gamma API Production Server +security: [] +tags: + - name: Gamma Status + description: Gamma API status and health check + - name: Sports + description: Sports-related endpoints including teams and game data + - name: Tags + description: Tag management and related tag operations + - name: Events + description: Event management and event-related operations + - name: Markets + description: Market data and market-related operations + - name: Comments + description: Comment system and user interactions + - name: Series + description: Series management and related operations + - name: Profiles + description: User profile management + - name: Search + description: Search functionality across different entity types +paths: + /teams: + get: + tags: + - Sports + summary: List teams + operationId: listTeams + parameters: + - $ref: '#/components/parameters/limit' + - $ref: '#/components/parameters/offset' + - $ref: '#/components/parameters/order' + - $ref: '#/components/parameters/ascending' + - name: league + in: query + schema: + type: array + items: + type: string + - name: name + in: query + schema: + type: array + items: + type: string + - name: abbreviation + in: query + schema: + type: array + items: + type: string + responses: + '200': + description: List of teams + content: + application/json: + schema: + type: array + items: + $ref: '#/components/schemas/Team' +components: + parameters: + limit: + name: limit + in: query + schema: + type: integer + minimum: 0 + offset: + name: offset + in: query + schema: + type: integer + minimum: 0 + order: + name: order + in: query + schema: + type: string + description: Comma-separated list of fields to order by + ascending: + name: ascending + in: query + schema: + type: boolean + schemas: + Team: + type: object + properties: + id: + type: integer + name: + type: string + nullable: true + league: + type: string + nullable: true + record: + type: string + nullable: true + logo: + type: string + nullable: true + abbreviation: + type: string + nullable: true + alias: + type: string + nullable: true + createdAt: + type: string + format: date-time + nullable: true + updatedAt: + type: string + format: date-time + nullable: true + +```` \ No newline at end of file diff --git a/PolymarketDocumentation-main/docs/api-reference/tags/get-related-tags-relationships-by-tag-id.md b/PolymarketDocumentation-main/docs/api-reference/tags/get-related-tags-relationships-by-tag-id.md new file mode 100644 index 00000000..5b900ce4 --- /dev/null +++ b/PolymarketDocumentation-main/docs/api-reference/tags/get-related-tags-relationships-by-tag-id.md @@ -0,0 +1,94 @@ +> ## Documentation Index +> Fetch the complete documentation index at: https://docs.polymarket.com/llms.txt +> Use this file to discover all available pages before exploring further. + +# Get related tags (relationships) by tag id + + + +## OpenAPI + +````yaml /api-spec/gamma-openapi.yaml get /tags/{id}/related-tags +openapi: 3.0.3 +info: + title: Markets API + version: 1.0.0 + description: REST API specification for public endpoints used by the Markets service. +servers: + - url: https://gamma-api.polymarket.com + description: Polymarket Gamma API Production Server +security: [] +tags: + - name: Gamma Status + description: Gamma API status and health check + - name: Sports + description: Sports-related endpoints including teams and game data + - name: Tags + description: Tag management and related tag operations + - name: Events + description: Event management and event-related operations + - name: Markets + description: Market data and market-related operations + - name: Comments + description: Comment system and user interactions + - name: Series + description: Series management and related operations + - name: Profiles + description: User profile management + - name: Search + description: Search functionality across different entity types +paths: + /tags/{id}/related-tags: + get: + tags: + - Tags + summary: Get related tags (relationships) by tag id + operationId: getRelatedTagsById + parameters: + - $ref: '#/components/parameters/pathId' + - name: omit_empty + in: query + schema: + type: boolean + - name: status + in: query + schema: + type: string + enum: + - active + - closed + - all + responses: + '200': + description: Related tag relationships + content: + application/json: + schema: + type: array + items: + $ref: '#/components/schemas/RelatedTag' +components: + parameters: + pathId: + name: id + in: path + required: true + schema: + type: integer + schemas: + RelatedTag: + type: object + properties: + id: + type: string + tagID: + type: integer + nullable: true + relatedTagID: + type: integer + nullable: true + rank: + type: integer + nullable: true + +```` \ No newline at end of file diff --git a/PolymarketDocumentation-main/docs/api-reference/tags/get-related-tags-relationships-by-tag-slug.md b/PolymarketDocumentation-main/docs/api-reference/tags/get-related-tags-relationships-by-tag-slug.md new file mode 100644 index 00000000..861a1d86 --- /dev/null +++ b/PolymarketDocumentation-main/docs/api-reference/tags/get-related-tags-relationships-by-tag-slug.md @@ -0,0 +1,94 @@ +> ## Documentation Index +> Fetch the complete documentation index at: https://docs.polymarket.com/llms.txt +> Use this file to discover all available pages before exploring further. + +# Get related tags (relationships) by tag slug + + + +## OpenAPI + +````yaml /api-spec/gamma-openapi.yaml get /tags/slug/{slug}/related-tags +openapi: 3.0.3 +info: + title: Markets API + version: 1.0.0 + description: REST API specification for public endpoints used by the Markets service. +servers: + - url: https://gamma-api.polymarket.com + description: Polymarket Gamma API Production Server +security: [] +tags: + - name: Gamma Status + description: Gamma API status and health check + - name: Sports + description: Sports-related endpoints including teams and game data + - name: Tags + description: Tag management and related tag operations + - name: Events + description: Event management and event-related operations + - name: Markets + description: Market data and market-related operations + - name: Comments + description: Comment system and user interactions + - name: Series + description: Series management and related operations + - name: Profiles + description: User profile management + - name: Search + description: Search functionality across different entity types +paths: + /tags/slug/{slug}/related-tags: + get: + tags: + - Tags + summary: Get related tags (relationships) by tag slug + operationId: getRelatedTagsBySlug + parameters: + - $ref: '#/components/parameters/pathSlug' + - name: omit_empty + in: query + schema: + type: boolean + - name: status + in: query + schema: + type: string + enum: + - active + - closed + - all + responses: + '200': + description: Related tag relationships + content: + application/json: + schema: + type: array + items: + $ref: '#/components/schemas/RelatedTag' +components: + parameters: + pathSlug: + name: slug + in: path + required: true + schema: + type: string + schemas: + RelatedTag: + type: object + properties: + id: + type: string + tagID: + type: integer + nullable: true + relatedTagID: + type: integer + nullable: true + rank: + type: integer + nullable: true + +```` \ No newline at end of file diff --git a/PolymarketDocumentation-main/docs/api-reference/tags/get-tag-by-id.md b/PolymarketDocumentation-main/docs/api-reference/tags/get-tag-by-id.md new file mode 100644 index 00000000..f9c23ed5 --- /dev/null +++ b/PolymarketDocumentation-main/docs/api-reference/tags/get-tag-by-id.md @@ -0,0 +1,109 @@ +> ## Documentation Index +> Fetch the complete documentation index at: https://docs.polymarket.com/llms.txt +> Use this file to discover all available pages before exploring further. + +# Get tag by id + + + +## OpenAPI + +````yaml /api-spec/gamma-openapi.yaml get /tags/{id} +openapi: 3.0.3 +info: + title: Markets API + version: 1.0.0 + description: REST API specification for public endpoints used by the Markets service. +servers: + - url: https://gamma-api.polymarket.com + description: Polymarket Gamma API Production Server +security: [] +tags: + - name: Gamma Status + description: Gamma API status and health check + - name: Sports + description: Sports-related endpoints including teams and game data + - name: Tags + description: Tag management and related tag operations + - name: Events + description: Event management and event-related operations + - name: Markets + description: Market data and market-related operations + - name: Comments + description: Comment system and user interactions + - name: Series + description: Series management and related operations + - name: Profiles + description: User profile management + - name: Search + description: Search functionality across different entity types +paths: + /tags/{id}: + get: + tags: + - Tags + summary: Get tag by id + operationId: getTag + parameters: + - $ref: '#/components/parameters/pathId' + - name: include_template + in: query + schema: + type: boolean + responses: + '200': + description: Tag + content: + application/json: + schema: + $ref: '#/components/schemas/Tag' + '404': + description: Not found +components: + parameters: + pathId: + name: id + in: path + required: true + schema: + type: integer + schemas: + Tag: + type: object + properties: + id: + type: string + label: + type: string + nullable: true + slug: + type: string + nullable: true + forceShow: + type: boolean + nullable: true + publishedAt: + type: string + nullable: true + createdBy: + type: integer + nullable: true + updatedBy: + type: integer + nullable: true + createdAt: + type: string + format: date-time + nullable: true + updatedAt: + type: string + format: date-time + nullable: true + forceHide: + type: boolean + nullable: true + isCarousel: + type: boolean + nullable: true + +```` \ No newline at end of file diff --git a/PolymarketDocumentation-main/docs/api-reference/tags/get-tag-by-slug.md b/PolymarketDocumentation-main/docs/api-reference/tags/get-tag-by-slug.md new file mode 100644 index 00000000..71ba1429 --- /dev/null +++ b/PolymarketDocumentation-main/docs/api-reference/tags/get-tag-by-slug.md @@ -0,0 +1,109 @@ +> ## Documentation Index +> Fetch the complete documentation index at: https://docs.polymarket.com/llms.txt +> Use this file to discover all available pages before exploring further. + +# Get tag by slug + + + +## OpenAPI + +````yaml /api-spec/gamma-openapi.yaml get /tags/slug/{slug} +openapi: 3.0.3 +info: + title: Markets API + version: 1.0.0 + description: REST API specification for public endpoints used by the Markets service. +servers: + - url: https://gamma-api.polymarket.com + description: Polymarket Gamma API Production Server +security: [] +tags: + - name: Gamma Status + description: Gamma API status and health check + - name: Sports + description: Sports-related endpoints including teams and game data + - name: Tags + description: Tag management and related tag operations + - name: Events + description: Event management and event-related operations + - name: Markets + description: Market data and market-related operations + - name: Comments + description: Comment system and user interactions + - name: Series + description: Series management and related operations + - name: Profiles + description: User profile management + - name: Search + description: Search functionality across different entity types +paths: + /tags/slug/{slug}: + get: + tags: + - Tags + summary: Get tag by slug + operationId: getTagBySlug + parameters: + - $ref: '#/components/parameters/pathSlug' + - name: include_template + in: query + schema: + type: boolean + responses: + '200': + description: Tag + content: + application/json: + schema: + $ref: '#/components/schemas/Tag' + '404': + description: Not found +components: + parameters: + pathSlug: + name: slug + in: path + required: true + schema: + type: string + schemas: + Tag: + type: object + properties: + id: + type: string + label: + type: string + nullable: true + slug: + type: string + nullable: true + forceShow: + type: boolean + nullable: true + publishedAt: + type: string + nullable: true + createdBy: + type: integer + nullable: true + updatedBy: + type: integer + nullable: true + createdAt: + type: string + format: date-time + nullable: true + updatedAt: + type: string + format: date-time + nullable: true + forceHide: + type: boolean + nullable: true + isCarousel: + type: boolean + nullable: true + +```` \ No newline at end of file diff --git a/PolymarketDocumentation-main/docs/api-reference/tags/get-tags-related-to-a-tag-id.md b/PolymarketDocumentation-main/docs/api-reference/tags/get-tags-related-to-a-tag-id.md new file mode 100644 index 00000000..152a3e19 --- /dev/null +++ b/PolymarketDocumentation-main/docs/api-reference/tags/get-tags-related-to-a-tag-id.md @@ -0,0 +1,117 @@ +> ## Documentation Index +> Fetch the complete documentation index at: https://docs.polymarket.com/llms.txt +> Use this file to discover all available pages before exploring further. + +# Get tags related to a tag id + + + +## OpenAPI + +````yaml /api-spec/gamma-openapi.yaml get /tags/{id}/related-tags/tags +openapi: 3.0.3 +info: + title: Markets API + version: 1.0.0 + description: REST API specification for public endpoints used by the Markets service. +servers: + - url: https://gamma-api.polymarket.com + description: Polymarket Gamma API Production Server +security: [] +tags: + - name: Gamma Status + description: Gamma API status and health check + - name: Sports + description: Sports-related endpoints including teams and game data + - name: Tags + description: Tag management and related tag operations + - name: Events + description: Event management and event-related operations + - name: Markets + description: Market data and market-related operations + - name: Comments + description: Comment system and user interactions + - name: Series + description: Series management and related operations + - name: Profiles + description: User profile management + - name: Search + description: Search functionality across different entity types +paths: + /tags/{id}/related-tags/tags: + get: + tags: + - Tags + summary: Get tags related to a tag id + operationId: getTagsRelatedToATagById + parameters: + - $ref: '#/components/parameters/pathId' + - name: omit_empty + in: query + schema: + type: boolean + - name: status + in: query + schema: + type: string + enum: + - active + - closed + - all + responses: + '200': + description: Related tags + content: + application/json: + schema: + type: array + items: + $ref: '#/components/schemas/Tag' +components: + parameters: + pathId: + name: id + in: path + required: true + schema: + type: integer + schemas: + Tag: + type: object + properties: + id: + type: string + label: + type: string + nullable: true + slug: + type: string + nullable: true + forceShow: + type: boolean + nullable: true + publishedAt: + type: string + nullable: true + createdBy: + type: integer + nullable: true + updatedBy: + type: integer + nullable: true + createdAt: + type: string + format: date-time + nullable: true + updatedAt: + type: string + format: date-time + nullable: true + forceHide: + type: boolean + nullable: true + isCarousel: + type: boolean + nullable: true + +```` \ No newline at end of file diff --git a/PolymarketDocumentation-main/docs/api-reference/tags/get-tags-related-to-a-tag-slug.md b/PolymarketDocumentation-main/docs/api-reference/tags/get-tags-related-to-a-tag-slug.md new file mode 100644 index 00000000..29336690 --- /dev/null +++ b/PolymarketDocumentation-main/docs/api-reference/tags/get-tags-related-to-a-tag-slug.md @@ -0,0 +1,117 @@ +> ## Documentation Index +> Fetch the complete documentation index at: https://docs.polymarket.com/llms.txt +> Use this file to discover all available pages before exploring further. + +# Get tags related to a tag slug + + + +## OpenAPI + +````yaml /api-spec/gamma-openapi.yaml get /tags/slug/{slug}/related-tags/tags +openapi: 3.0.3 +info: + title: Markets API + version: 1.0.0 + description: REST API specification for public endpoints used by the Markets service. +servers: + - url: https://gamma-api.polymarket.com + description: Polymarket Gamma API Production Server +security: [] +tags: + - name: Gamma Status + description: Gamma API status and health check + - name: Sports + description: Sports-related endpoints including teams and game data + - name: Tags + description: Tag management and related tag operations + - name: Events + description: Event management and event-related operations + - name: Markets + description: Market data and market-related operations + - name: Comments + description: Comment system and user interactions + - name: Series + description: Series management and related operations + - name: Profiles + description: User profile management + - name: Search + description: Search functionality across different entity types +paths: + /tags/slug/{slug}/related-tags/tags: + get: + tags: + - Tags + summary: Get tags related to a tag slug + operationId: getTagsRelatedToATagBySlug + parameters: + - $ref: '#/components/parameters/pathSlug' + - name: omit_empty + in: query + schema: + type: boolean + - name: status + in: query + schema: + type: string + enum: + - active + - closed + - all + responses: + '200': + description: Related tags + content: + application/json: + schema: + type: array + items: + $ref: '#/components/schemas/Tag' +components: + parameters: + pathSlug: + name: slug + in: path + required: true + schema: + type: string + schemas: + Tag: + type: object + properties: + id: + type: string + label: + type: string + nullable: true + slug: + type: string + nullable: true + forceShow: + type: boolean + nullable: true + publishedAt: + type: string + nullable: true + createdBy: + type: integer + nullable: true + updatedBy: + type: integer + nullable: true + createdAt: + type: string + format: date-time + nullable: true + updatedAt: + type: string + format: date-time + nullable: true + forceHide: + type: boolean + nullable: true + isCarousel: + type: boolean + nullable: true + +```` \ No newline at end of file diff --git a/PolymarketDocumentation-main/docs/api-reference/tags/list-tags.md b/PolymarketDocumentation-main/docs/api-reference/tags/list-tags.md new file mode 100644 index 00000000..126f8b40 --- /dev/null +++ b/PolymarketDocumentation-main/docs/api-reference/tags/list-tags.md @@ -0,0 +1,133 @@ +> ## Documentation Index +> Fetch the complete documentation index at: https://docs.polymarket.com/llms.txt +> Use this file to discover all available pages before exploring further. + +# List tags + + + +## OpenAPI + +````yaml /api-spec/gamma-openapi.yaml get /tags +openapi: 3.0.3 +info: + title: Markets API + version: 1.0.0 + description: REST API specification for public endpoints used by the Markets service. +servers: + - url: https://gamma-api.polymarket.com + description: Polymarket Gamma API Production Server +security: [] +tags: + - name: Gamma Status + description: Gamma API status and health check + - name: Sports + description: Sports-related endpoints including teams and game data + - name: Tags + description: Tag management and related tag operations + - name: Events + description: Event management and event-related operations + - name: Markets + description: Market data and market-related operations + - name: Comments + description: Comment system and user interactions + - name: Series + description: Series management and related operations + - name: Profiles + description: User profile management + - name: Search + description: Search functionality across different entity types +paths: + /tags: + get: + tags: + - Tags + summary: List tags + operationId: listTags + parameters: + - $ref: '#/components/parameters/limit' + - $ref: '#/components/parameters/offset' + - $ref: '#/components/parameters/order' + - $ref: '#/components/parameters/ascending' + - name: include_template + in: query + schema: + type: boolean + - name: is_carousel + in: query + schema: + type: boolean + responses: + '200': + description: List of tags + content: + application/json: + schema: + type: array + items: + $ref: '#/components/schemas/Tag' +components: + parameters: + limit: + name: limit + in: query + schema: + type: integer + minimum: 0 + offset: + name: offset + in: query + schema: + type: integer + minimum: 0 + order: + name: order + in: query + schema: + type: string + description: Comma-separated list of fields to order by + ascending: + name: ascending + in: query + schema: + type: boolean + schemas: + Tag: + type: object + properties: + id: + type: string + label: + type: string + nullable: true + slug: + type: string + nullable: true + forceShow: + type: boolean + nullable: true + publishedAt: + type: string + nullable: true + createdBy: + type: integer + nullable: true + updatedBy: + type: integer + nullable: true + createdAt: + type: string + format: date-time + nullable: true + updatedAt: + type: string + format: date-time + nullable: true + forceHide: + type: boolean + nullable: true + isCarousel: + type: boolean + nullable: true + +```` \ No newline at end of file diff --git a/PolymarketDocumentation-main/docs/api-reference/test-connection.md b/PolymarketDocumentation-main/docs/api-reference/test-connection.md new file mode 100644 index 00000000..a94604f0 --- /dev/null +++ b/PolymarketDocumentation-main/docs/api-reference/test-connection.md @@ -0,0 +1,134 @@ +> ## Documentation Index +> Fetch the complete documentation index at: https://docs.polymarket.com/llms.txt +> Use this file to discover all available pages before exploring further. + +# Test Connection + +> Test connection to the server. + + +Request Weight: **1** + + +## OpenAPI + +````yaml /api-spec/perps-openapi.json get /v1/info/ping +openapi: 3.0.3 +info: + title: Polymarket Perps HTTP API + version: 1.0.0 + description: HTTP API for Polymarket perpetual trading system. + license: + name: Apache 2.0 + url: https://www.apache.org/licenses/LICENSE-2.0.html +servers: + - url: https://api.perpetuals.polymarket.com + description: Production Perps HTTP API +security: [] +paths: + /v1/info/ping: + get: + summary: Test Connection + description: | + Test connection to the server. + operationId: getPing + responses: + '200': + description: Successful ping response. + content: + application/json: + schema: + type: object + required: + - status + properties: + status: + type: string + example: ok + '429': + $ref: '#/components/responses/Error429Response' + '500': + $ref: '#/components/responses/Error500Response' + security: [] +components: + responses: + Error429Response: + description: > + Too Many Requests. `error` distinguishes the limit that was hit: + + `ip_rate_limited` (per-IP token bucket), `action_rate_limited` + (per-account + + action rate), or `open_orders_limit` (resting open-order cap). + headers: + Retry-After: + description: > + Whole seconds to wait before retrying. Present only on token-bucket + + rate-limit rejections (`ip_rate_limited` and `action_rate_limited`); + a + + conservative estimate of when enough capacity will have refilled to + + admit the request. Absent on `open_orders_limit`, which is a + capacity + + limit, not a rate limit — waiting does not free order slots; cancel + + resting orders or wait for fills instead. + schema: + type: integer + example: 2 + content: + application/json: + schema: + $ref: '#/components/schemas/Error429' + Error500Response: + description: | + Internal server error. `error` is `internal_error`. + content: + application/json: + schema: + $ref: '#/components/schemas/Error500' + schemas: + Error429: + title: Error429 + type: object + required: + - status + - error + properties: + status: + type: string + enum: + - err + error: + $ref: '#/components/schemas/error' + Error500: + title: Error500 + type: object + required: + - status + - error + properties: + status: + type: string + enum: + - err + error: + $ref: '#/components/schemas/error' + error: + type: string + description: >- + Error identifier. For domain rejections and transport errors + (`401`/`404`/`429`/`500`) this is a stable, machine-readable snake_case + identifier that is part of the API contract and safe to branch on, e.g. + `insufficient_margin`, `insufficient_balance`, `order_not_found`, + `reduce_only_invalid`, `unauthorized`, `not_found`. For `400` it is a + human-readable validation detail whose wording may change. See the Error + handling guide for the domain identifiers. (Post-only / Fill-or-Kill + outcomes are order statuses such as `post_only_rejected`, not + rejections.) + example: insufficient_margin + +```` \ No newline at end of file diff --git a/PolymarketDocumentation-main/docs/api-reference/trade/cancel-all-orders.md b/PolymarketDocumentation-main/docs/api-reference/trade/cancel-all-orders.md new file mode 100644 index 00000000..4d15004a --- /dev/null +++ b/PolymarketDocumentation-main/docs/api-reference/trade/cancel-all-orders.md @@ -0,0 +1,176 @@ +> ## Documentation Index +> Fetch the complete documentation index at: https://docs.polymarket.com/llms.txt +> Use this file to discover all available pages before exploring further. + +# Cancel all orders + +> Cancels all open orders for the authenticated user. Works even in cancel-only mode. + + + + +## OpenAPI + +````yaml /api-spec/clob-openapi.yaml delete /cancel-all +openapi: 3.1.0 +info: + title: Polymarket CLOB API + description: Polymarket CLOB API Reference + license: + name: MIT + identifier: MIT + version: 1.0.0 +servers: + - url: https://clob.polymarket.com + description: Production CLOB API + - url: https://clob-staging.polymarket.com + description: Staging CLOB API +security: [] +tags: + - name: Trade + description: Trade endpoints + - name: Markets + description: Market data endpoints + - name: Account + description: Account and authentication endpoints + - name: Notifications + description: User notification endpoints + - name: Rewards + description: Rewards and earnings endpoints + - name: Rebates + description: Maker rebate endpoints +paths: + /cancel-all: + delete: + tags: + - Trade + summary: Cancel all orders + description: > + Cancels all open orders for the authenticated user. Works even in + cancel-only mode. + operationId: cancelAllOrders + responses: + '200': + description: Cancellation results for all orders + content: + application/json: + schema: + $ref: '#/components/schemas/CancelOrdersResponse' + examples: + canceled: + summary: All orders canceled + value: + canceled: + - '0xabcdef1234567890abcdef1234567890abcdef12' + - '0xfedcba0987654321fedcba0987654321fedcba09' + not_canceled: {} + mixed: + summary: Some orders canceled, some not + value: + canceled: + - '0xabcdef1234567890abcdef1234567890abcdef12' + not_canceled: + '0xfedcba0987654321fedcba0987654321fedcba09': Order already matched + no_orders: + summary: No orders to cancel + value: + canceled: [] + not_canceled: {} + '401': + description: Unauthorized - Invalid API key or authentication failed + content: + application/json: + schema: + $ref: '#/components/schemas/ErrorResponse' + example: + error: Invalid API key + '500': + description: Internal server error + content: + application/json: + schema: + $ref: '#/components/schemas/ErrorResponse' + example: + error: Internal server error + '503': + description: >- + Service unavailable - Trading disabled (cancels still work in + cancel-only mode) + content: + application/json: + schema: + $ref: '#/components/schemas/ErrorResponse' + example: + error: >- + Trading is currently disabled. Check polymarket.com for + updates + security: + - polyApiKey: [] + polyAddress: [] + polySignature: [] + polyPassphrase: [] + polyTimestamp: [] +components: + schemas: + CancelOrdersResponse: + type: object + required: + - canceled + - not_canceled + properties: + canceled: + type: array + description: Array of order IDs that were successfully canceled + items: + type: string + example: + - '0xabcdef1234567890abcdef1234567890abcdef12' + not_canceled: + type: object + description: Map of order IDs that could not be canceled with error messages + additionalProperties: + type: string + example: + '0xabcdef1234567890abcdef1234567890abcdef12': Order not found or already canceled + ErrorResponse: + type: object + required: + - error + properties: + error: + type: string + description: Error message + code: + type: string + description: Machine-readable error code, when provided + retry_after_seconds: + type: integer + description: Number of seconds to wait before retrying, when provided + securitySchemes: + polyApiKey: + type: apiKey + in: header + name: POLY_API_KEY + description: Your API key + polyAddress: + type: apiKey + in: header + name: POLY_ADDRESS + description: Ethereum address associated with the API key + polySignature: + type: apiKey + in: header + name: POLY_SIGNATURE + description: HMAC signature of the request + polyPassphrase: + type: apiKey + in: header + name: POLY_PASSPHRASE + description: API key passphrase + polyTimestamp: + type: apiKey + in: header + name: POLY_TIMESTAMP + description: Unix timestamp of the request + +```` \ No newline at end of file diff --git a/PolymarketDocumentation-main/docs/api-reference/trade/cancel-multiple-orders.md b/PolymarketDocumentation-main/docs/api-reference/trade/cancel-multiple-orders.md new file mode 100644 index 00000000..b52b3552 --- /dev/null +++ b/PolymarketDocumentation-main/docs/api-reference/trade/cancel-multiple-orders.md @@ -0,0 +1,216 @@ +> ## Documentation Index +> Fetch the complete documentation index at: https://docs.polymarket.com/llms.txt +> Use this file to discover all available pages before exploring further. + +# Cancel multiple orders + +> Cancels multiple orders by their IDs. Maximum 1000 orders per request. +Duplicate order IDs in the request are automatically ignored. +Works even in cancel-only mode. + + + + +## OpenAPI + +````yaml /api-spec/clob-openapi.yaml delete /orders +openapi: 3.1.0 +info: + title: Polymarket CLOB API + description: Polymarket CLOB API Reference + license: + name: MIT + identifier: MIT + version: 1.0.0 +servers: + - url: https://clob.polymarket.com + description: Production CLOB API + - url: https://clob-staging.polymarket.com + description: Staging CLOB API +security: [] +tags: + - name: Trade + description: Trade endpoints + - name: Markets + description: Market data endpoints + - name: Account + description: Account and authentication endpoints + - name: Notifications + description: User notification endpoints + - name: Rewards + description: Rewards and earnings endpoints + - name: Rebates + description: Maker rebate endpoints +paths: + /orders: + delete: + tags: + - Trade + summary: Cancel multiple orders + description: | + Cancels multiple orders by their IDs. Maximum 1000 orders per request. + Duplicate order IDs in the request are automatically ignored. + Works even in cancel-only mode. + operationId: cancelOrders + requestBody: + required: true + content: + application/json: + schema: + type: array + items: + type: string + maxItems: 1000 + example: + - '0xabcdef1234567890abcdef1234567890abcdef12' + - '0xfedcba0987654321fedcba0987654321fedcba09' + - '0x1234567890abcdef1234567890abcdef12345678' + responses: + '200': + description: Cancellation results for all orders + content: + application/json: + schema: + $ref: '#/components/schemas/CancelOrdersResponse' + examples: + all_canceled: + summary: All orders canceled + value: + canceled: + - '0xabcdef1234567890abcdef1234567890abcdef12' + - '0xfedcba0987654321fedcba0987654321fedcba09' + - '0x1234567890abcdef1234567890abcdef12345678' + not_canceled: {} + mixed: + summary: Some orders canceled, some not + value: + canceled: + - '0xabcdef1234567890abcdef1234567890abcdef12' + - '0xfedcba0987654321fedcba0987654321fedcba09' + not_canceled: + '0x1234567890abcdef1234567890abcdef12345678': Order already matched + partial: + summary: Partial cancellation + value: + canceled: + - '0xabcdef1234567890abcdef1234567890abcdef12' + not_canceled: + '0xfedcba0987654321fedcba0987654321fedcba09': Order not found + '0x1234567890abcdef1234567890abcdef12345678': Order already canceled + '400': + description: Bad request - Invalid order IDs or payload + content: + application/json: + schema: + $ref: '#/components/schemas/ErrorResponse' + examples: + invalid_order_id: + summary: Invalid order ID + value: + error: Invalid orderID + invalid_payload: + summary: Invalid payload + value: + error: Invalid order payload + too_many_orders: + summary: Too many orders + value: + error: 'Too many orders in payload, max allowed: 1000' + '401': + description: Unauthorized - Invalid API key or authentication failed + content: + application/json: + schema: + $ref: '#/components/schemas/ErrorResponse' + example: + error: Invalid API key + '500': + description: Internal server error + content: + application/json: + schema: + $ref: '#/components/schemas/ErrorResponse' + example: + error: Internal server error + '503': + description: >- + Service unavailable - Trading disabled (cancels still work in + cancel-only mode) + content: + application/json: + schema: + $ref: '#/components/schemas/ErrorResponse' + example: + error: >- + Trading is currently disabled. Check polymarket.com for + updates + security: + - polyApiKey: [] + polyAddress: [] + polySignature: [] + polyPassphrase: [] + polyTimestamp: [] +components: + schemas: + CancelOrdersResponse: + type: object + required: + - canceled + - not_canceled + properties: + canceled: + type: array + description: Array of order IDs that were successfully canceled + items: + type: string + example: + - '0xabcdef1234567890abcdef1234567890abcdef12' + not_canceled: + type: object + description: Map of order IDs that could not be canceled with error messages + additionalProperties: + type: string + example: + '0xabcdef1234567890abcdef1234567890abcdef12': Order not found or already canceled + ErrorResponse: + type: object + required: + - error + properties: + error: + type: string + description: Error message + code: + type: string + description: Machine-readable error code, when provided + retry_after_seconds: + type: integer + description: Number of seconds to wait before retrying, when provided + securitySchemes: + polyApiKey: + type: apiKey + in: header + name: POLY_API_KEY + description: Your API key + polyAddress: + type: apiKey + in: header + name: POLY_ADDRESS + description: Ethereum address associated with the API key + polySignature: + type: apiKey + in: header + name: POLY_SIGNATURE + description: HMAC signature of the request + polyPassphrase: + type: apiKey + in: header + name: POLY_PASSPHRASE + description: API key passphrase + polyTimestamp: + type: apiKey + in: header + name: POLY_TIMESTAMP + description: Unix timestamp of the request + +```` \ No newline at end of file diff --git a/PolymarketDocumentation-main/docs/api-reference/trade/cancel-orders-for-a-market.md b/PolymarketDocumentation-main/docs/api-reference/trade/cancel-orders-for-a-market.md new file mode 100644 index 00000000..b8e5e19d --- /dev/null +++ b/PolymarketDocumentation-main/docs/api-reference/trade/cancel-orders-for-a-market.md @@ -0,0 +1,211 @@ +> ## Documentation Index +> Fetch the complete documentation index at: https://docs.polymarket.com/llms.txt +> Use this file to discover all available pages before exploring further. + +# Cancel orders for a market + +> Cancels all open orders for the authenticated user in a specific market (condition) and asset. +Works even in cancel-only mode. + + + + +## OpenAPI + +````yaml /api-spec/clob-openapi.yaml delete /cancel-market-orders +openapi: 3.1.0 +info: + title: Polymarket CLOB API + description: Polymarket CLOB API Reference + license: + name: MIT + identifier: MIT + version: 1.0.0 +servers: + - url: https://clob.polymarket.com + description: Production CLOB API + - url: https://clob-staging.polymarket.com + description: Staging CLOB API +security: [] +tags: + - name: Trade + description: Trade endpoints + - name: Markets + description: Market data endpoints + - name: Account + description: Account and authentication endpoints + - name: Notifications + description: User notification endpoints + - name: Rewards + description: Rewards and earnings endpoints + - name: Rebates + description: Maker rebate endpoints +paths: + /cancel-market-orders: + delete: + tags: + - Trade + summary: Cancel orders for a market + description: > + Cancels all open orders for the authenticated user in a specific market + (condition) and asset. + + Works even in cancel-only mode. + operationId: cancelMarketOrders + requestBody: + required: true + content: + application/json: + schema: + $ref: '#/components/schemas/OrderMarketCancelParams' + example: + market: >- + 0x0000000000000000000000000000000000000000000000000000000000000001 + asset_id: 0xabc123def456... + responses: + '200': + description: Cancellation results for market orders + content: + application/json: + schema: + $ref: '#/components/schemas/CancelOrdersResponse' + examples: + canceled: + summary: All market orders canceled + value: + canceled: + - '0xabcdef1234567890abcdef1234567890abcdef12' + - '0xfedcba0987654321fedcba0987654321fedcba09' + not_canceled: {} + mixed: + summary: Some orders canceled, some not + value: + canceled: + - '0xabcdef1234567890abcdef1234567890abcdef12' + not_canceled: + '0xfedcba0987654321fedcba0987654321fedcba09': Order already matched + no_orders: + summary: No orders found for this market + value: + canceled: [] + not_canceled: {} + '400': + description: Bad request - Invalid payload + content: + application/json: + schema: + $ref: '#/components/schemas/ErrorResponse' + example: + error: Invalid order payload + '401': + description: Unauthorized - Invalid API key or authentication failed + content: + application/json: + schema: + $ref: '#/components/schemas/ErrorResponse' + example: + error: Invalid API key + '500': + description: Internal server error + content: + application/json: + schema: + $ref: '#/components/schemas/ErrorResponse' + example: + error: Internal server error + '503': + description: >- + Service unavailable - Trading disabled (cancels still work in + cancel-only mode) + content: + application/json: + schema: + $ref: '#/components/schemas/ErrorResponse' + example: + error: >- + Trading is currently disabled. Check polymarket.com for + updates + security: + - polyApiKey: [] + polyAddress: [] + polySignature: [] + polyPassphrase: [] + polyTimestamp: [] +components: + schemas: + OrderMarketCancelParams: + type: object + required: + - market + - asset_id + properties: + market: + type: string + description: Market (condition ID) + example: '0x0000000000000000000000000000000000000000000000000000000000000001' + asset_id: + type: string + description: Asset ID (token ID) + example: 0xabc123def456... + CancelOrdersResponse: + type: object + required: + - canceled + - not_canceled + properties: + canceled: + type: array + description: Array of order IDs that were successfully canceled + items: + type: string + example: + - '0xabcdef1234567890abcdef1234567890abcdef12' + not_canceled: + type: object + description: Map of order IDs that could not be canceled with error messages + additionalProperties: + type: string + example: + '0xabcdef1234567890abcdef1234567890abcdef12': Order not found or already canceled + ErrorResponse: + type: object + required: + - error + properties: + error: + type: string + description: Error message + code: + type: string + description: Machine-readable error code, when provided + retry_after_seconds: + type: integer + description: Number of seconds to wait before retrying, when provided + securitySchemes: + polyApiKey: + type: apiKey + in: header + name: POLY_API_KEY + description: Your API key + polyAddress: + type: apiKey + in: header + name: POLY_ADDRESS + description: Ethereum address associated with the API key + polySignature: + type: apiKey + in: header + name: POLY_SIGNATURE + description: HMAC signature of the request + polyPassphrase: + type: apiKey + in: header + name: POLY_PASSPHRASE + description: API key passphrase + polyTimestamp: + type: apiKey + in: header + name: POLY_TIMESTAMP + description: Unix timestamp of the request + +```` \ No newline at end of file diff --git a/PolymarketDocumentation-main/docs/api-reference/trade/cancel-single-order.md b/PolymarketDocumentation-main/docs/api-reference/trade/cancel-single-order.md new file mode 100644 index 00000000..6f1b4570 --- /dev/null +++ b/PolymarketDocumentation-main/docs/api-reference/trade/cancel-single-order.md @@ -0,0 +1,200 @@ +> ## Documentation Index +> Fetch the complete documentation index at: https://docs.polymarket.com/llms.txt +> Use this file to discover all available pages before exploring further. + +# Cancel single order + +> Cancels a single order by its ID. Works even in cancel-only mode. + + + + +## OpenAPI + +````yaml /api-spec/clob-openapi.yaml delete /order +openapi: 3.1.0 +info: + title: Polymarket CLOB API + description: Polymarket CLOB API Reference + license: + name: MIT + identifier: MIT + version: 1.0.0 +servers: + - url: https://clob.polymarket.com + description: Production CLOB API + - url: https://clob-staging.polymarket.com + description: Staging CLOB API +security: [] +tags: + - name: Trade + description: Trade endpoints + - name: Markets + description: Market data endpoints + - name: Account + description: Account and authentication endpoints + - name: Notifications + description: User notification endpoints + - name: Rewards + description: Rewards and earnings endpoints + - name: Rebates + description: Maker rebate endpoints +paths: + /order: + delete: + tags: + - Trade + summary: Cancel single order + description: | + Cancels a single order by its ID. Works even in cancel-only mode. + operationId: cancelOrder + requestBody: + required: true + content: + application/json: + schema: + $ref: '#/components/schemas/CancelOrderPayload' + example: + orderID: '0xabcdef1234567890abcdef1234567890abcdef12' + responses: + '200': + description: Order cancellation result + content: + application/json: + schema: + $ref: '#/components/schemas/CancelOrdersResponse' + examples: + canceled: + summary: Order successfully canceled + value: + canceled: + - '0xabcdef1234567890abcdef1234567890abcdef12' + not_canceled: {} + not_canceled: + summary: Order could not be canceled + value: + canceled: [] + not_canceled: + '0xabcdef1234567890abcdef1234567890abcdef12': Order not found or already canceled + '400': + description: Bad request - Invalid order ID or payload + content: + application/json: + schema: + $ref: '#/components/schemas/ErrorResponse' + examples: + invalid_order_id: + summary: Invalid order ID + value: + error: Invalid orderID + invalid_payload: + summary: Invalid payload + value: + error: Invalid order payload + '401': + description: Unauthorized - Invalid API key or authentication failed + content: + application/json: + schema: + $ref: '#/components/schemas/ErrorResponse' + example: + error: Invalid API key + '500': + description: Internal server error + content: + application/json: + schema: + $ref: '#/components/schemas/ErrorResponse' + example: + error: Internal server error + '503': + description: >- + Service unavailable - Trading disabled (cancels still work in + cancel-only mode) + content: + application/json: + schema: + $ref: '#/components/schemas/ErrorResponse' + example: + error: >- + Trading is currently disabled. Check polymarket.com for + updates + security: + - polyApiKey: [] + polyAddress: [] + polySignature: [] + polyPassphrase: [] + polyTimestamp: [] +components: + schemas: + CancelOrderPayload: + type: object + required: + - orderID + properties: + orderID: + type: string + description: Order ID (order hash) to cancel + example: '0xabcdef1234567890abcdef1234567890abcdef12' + CancelOrdersResponse: + type: object + required: + - canceled + - not_canceled + properties: + canceled: + type: array + description: Array of order IDs that were successfully canceled + items: + type: string + example: + - '0xabcdef1234567890abcdef1234567890abcdef12' + not_canceled: + type: object + description: Map of order IDs that could not be canceled with error messages + additionalProperties: + type: string + example: + '0xabcdef1234567890abcdef1234567890abcdef12': Order not found or already canceled + ErrorResponse: + type: object + required: + - error + properties: + error: + type: string + description: Error message + code: + type: string + description: Machine-readable error code, when provided + retry_after_seconds: + type: integer + description: Number of seconds to wait before retrying, when provided + securitySchemes: + polyApiKey: + type: apiKey + in: header + name: POLY_API_KEY + description: Your API key + polyAddress: + type: apiKey + in: header + name: POLY_ADDRESS + description: Ethereum address associated with the API key + polySignature: + type: apiKey + in: header + name: POLY_SIGNATURE + description: HMAC signature of the request + polyPassphrase: + type: apiKey + in: header + name: POLY_PASSPHRASE + description: API key passphrase + polyTimestamp: + type: apiKey + in: header + name: POLY_TIMESTAMP + description: Unix timestamp of the request + +```` \ No newline at end of file diff --git a/PolymarketDocumentation-main/docs/api-reference/trade/get-builder-trades.md b/PolymarketDocumentation-main/docs/api-reference/trade/get-builder-trades.md new file mode 100644 index 00000000..c3e8c55c --- /dev/null +++ b/PolymarketDocumentation-main/docs/api-reference/trade/get-builder-trades.md @@ -0,0 +1,337 @@ +> ## Documentation Index +> Fetch the complete documentation index at: https://docs.polymarket.com/llms.txt +> Use this file to discover all available pages before exploring further. + +# Get builder trades + +> Retrieves trades attributed to a builder code. + + + + +## OpenAPI + +````yaml /api-spec/clob-openapi.yaml get /builder/trades +openapi: 3.1.0 +info: + title: Polymarket CLOB API + description: Polymarket CLOB API Reference + license: + name: MIT + identifier: MIT + version: 1.0.0 +servers: + - url: https://clob.polymarket.com + description: Production CLOB API + - url: https://clob-staging.polymarket.com + description: Staging CLOB API +security: [] +tags: + - name: Trade + description: Trade endpoints + - name: Markets + description: Market data endpoints + - name: Account + description: Account and authentication endpoints + - name: Notifications + description: User notification endpoints + - name: Rewards + description: Rewards and earnings endpoints + - name: Rebates + description: Maker rebate endpoints +paths: + /builder/trades: + get: + tags: + - Trade + summary: Get builder trades + description: | + Retrieves trades attributed to a builder code. + operationId: getBuilderTrades + parameters: + - name: builder_code + in: query + description: Builder code to fetch attributed trades for + required: true + schema: + type: string + pattern: ^0x[a-fA-F0-9]{64}$ + example: '0x0000000000000000000000000000000000000000000000000000000000000001' + - name: id + in: query + description: Trade ID to filter by specific trade + required: false + schema: + type: string + example: trade-123 + - name: market + in: query + description: Market (condition ID) to filter trades + required: false + schema: + type: string + pattern: ^0x[a-fA-F0-9]{64}$ + example: '0x0000000000000000000000000000000000000000000000000000000000000001' + - name: asset_id + in: query + description: Asset ID (token ID) to filter trades + required: false + schema: + type: string + example: >- + 15871154585880608648532107628464183779895785213830018178010423617714102767076 + - name: before + in: query + description: Filter trades before this Unix timestamp + required: false + schema: + type: string + pattern: ^\d+$ + example: '1700000000' + - name: after + in: query + description: Filter trades after this Unix timestamp + required: false + schema: + type: string + pattern: ^\d+$ + example: '1600000000' + - name: next_cursor + in: query + description: Cursor for pagination (base64 encoded offset) + required: false + schema: + type: string + example: MA== + responses: + '200': + description: Successfully retrieved builder trades + content: + application/json: + schema: + $ref: '#/components/schemas/BuilderTradesResponse' + examples: + example: + summary: Builder trades response + value: + limit: 300 + next_cursor: MzAw + count: 2 + data: + - id: trade-123 + tradeType: TAKER + takerOrderHash: '0xabcdef1234567890abcdef1234567890abcdef12' + builder: >- + 0x0000000000000000000000000000000000000000000000000000000000000001 + market: >- + 0x0000000000000000000000000000000000000000000000000000000000000001 + assetId: >- + 15871154585880608648532107628464183779895785213830018178010423617714102767076 + side: BUY + size: '100000000' + sizeUsdc: '50000000' + price: '0.5' + status: TRADE_STATUS_CONFIRMED + outcome: 'YES' + outcomeIndex: 0 + owner: f4f247b7-4ac7-ff29-a152-04fda0a8755a + maker: '0x1234567890123456789012345678901234567890' + transactionHash: >- + 0x1234567890abcdef1234567890abcdef1234567890abcdef1234567890abcdef + matchTime: '1700000000' + bucketIndex: 0 + fee: '300000' + feeUsdc: '150000' + createdAt: '2024-01-01T00:00:00Z' + updatedAt: '2024-01-01T00:00:00Z' + '400': + description: Bad request - Invalid parameters + content: + application/json: + schema: + $ref: '#/components/schemas/ErrorResponse' + example: + error: invalid builder trade params + '500': + description: Internal server error + content: + application/json: + schema: + $ref: '#/components/schemas/ErrorResponse' + example: + error: could not fetch builder trades +components: + schemas: + BuilderTradesResponse: + type: object + description: Paginated builder trades response + required: + - limit + - next_cursor + - count + - data + properties: + limit: + type: integer + description: Maximum number of items per page + example: 300 + next_cursor: + type: string + description: >- + Cursor for next page (base64 encoded offset). "LTE=" indicates no + more pages + example: MzAw + count: + type: integer + description: Number of items in current response + example: 2 + data: + type: array + description: Array of builder trades + items: + $ref: '#/components/schemas/BuilderTrade' + ErrorResponse: + type: object + required: + - error + properties: + error: + type: string + description: Error message + code: + type: string + description: Machine-readable error code, when provided + retry_after_seconds: + type: integer + description: Number of seconds to wait before retrying, when provided + BuilderTrade: + type: object + description: Builder trade information + required: + - id + - tradeType + - takerOrderHash + - builder + - market + - assetId + - side + - size + - sizeUsdc + - price + - status + - outcome + - outcomeIndex + - owner + - maker + - transactionHash + - matchTime + - bucketIndex + - fee + - feeUsdc + properties: + id: + type: string + description: Trade ID + example: trade-123 + tradeType: + type: string + description: Trade type + example: TAKER + takerOrderHash: + type: string + description: Taker order hash + example: '0xabcdef1234567890abcdef1234567890abcdef12' + builder: + type: string + description: Builder code attributed to the trade + pattern: ^0x[a-fA-F0-9]{64}$ + example: '0x0000000000000000000000000000000000000000000000000000000000000001' + market: + type: string + description: Market (condition ID) + pattern: ^0x[a-fA-F0-9]{64}$ + example: '0x0000000000000000000000000000000000000000000000000000000000000001' + assetId: + type: string + description: Asset ID (token ID) + example: >- + 15871154585880608648532107628464183779895785213830018178010423617714102767076 + side: + type: string + description: Trade side + enum: + - BUY + - SELL + example: BUY + size: + type: string + description: Trade size + example: '100000000' + sizeUsdc: + type: string + description: Trade size in USDC + example: '50000000' + price: + type: string + description: Trade price + example: '0.5' + status: + type: string + description: Trade status + example: TRADE_STATUS_CONFIRMED + outcome: + type: string + description: Market outcome + example: 'YES' + outcomeIndex: + type: integer + description: Outcome index + example: 0 + owner: + type: string + description: Owner UUID + example: f4f247b7-4ac7-ff29-a152-04fda0a8755a + maker: + type: string + description: Maker address + pattern: ^0x[a-fA-F0-9]{40}$ + example: '0x1234567890123456789012345678901234567890' + transactionHash: + type: string + description: Transaction hash + pattern: ^0x[a-fA-F0-9]{64}$ + example: '0x1234567890abcdef1234567890abcdef1234567890abcdef1234567890abcdef' + matchTime: + type: string + description: Match time (Unix timestamp) + example: '1700000000' + bucketIndex: + type: integer + description: Bucket index + example: 0 + fee: + type: string + description: Fee amount + example: '300000' + feeUsdc: + type: string + description: Fee amount in USDC + example: '150000' + err_msg: + type: + - string + - 'null' + description: Error message (if any) + example: null + createdAt: + type: string + format: date-time + description: Creation timestamp + example: '2024-01-01T00:00:00Z' + updatedAt: + type: string + format: date-time + description: Last update timestamp + example: '2024-01-01T00:00:00Z' + +```` \ No newline at end of file diff --git a/PolymarketDocumentation-main/docs/api-reference/trade/get-order-scoring-status.md b/PolymarketDocumentation-main/docs/api-reference/trade/get-order-scoring-status.md new file mode 100644 index 00000000..a61ceda0 --- /dev/null +++ b/PolymarketDocumentation-main/docs/api-reference/trade/get-order-scoring-status.md @@ -0,0 +1,194 @@ +> ## Documentation Index +> Fetch the complete documentation index at: https://docs.polymarket.com/llms.txt +> Use this file to discover all available pages before exploring further. + +# Get order scoring status + +> Checks if a specific order is currently scoring for rewards. + +An order is considered "scoring" if it meets all the criteria for earning maker rewards: +- The order is live on a rewards-eligible market +- The order meets the minimum size requirements +- The order is within the valid spread range +- The order has been live for the required duration + + + + +## OpenAPI + +````yaml /api-spec/clob-openapi.yaml get /order-scoring +openapi: 3.1.0 +info: + title: Polymarket CLOB API + description: Polymarket CLOB API Reference + license: + name: MIT + identifier: MIT + version: 1.0.0 +servers: + - url: https://clob.polymarket.com + description: Production CLOB API + - url: https://clob-staging.polymarket.com + description: Staging CLOB API +security: [] +tags: + - name: Trade + description: Trade endpoints + - name: Markets + description: Market data endpoints + - name: Account + description: Account and authentication endpoints + - name: Notifications + description: User notification endpoints + - name: Rewards + description: Rewards and earnings endpoints + - name: Rebates + description: Maker rebate endpoints +paths: + /order-scoring: + get: + tags: + - Trade + summary: Get order scoring status + description: > + Checks if a specific order is currently scoring for rewards. + + + An order is considered "scoring" if it meets all the criteria for + earning maker rewards: + + - The order is live on a rewards-eligible market + + - The order meets the minimum size requirements + + - The order is within the valid spread range + + - The order has been live for the required duration + operationId: getOrderScoring + parameters: + - name: order_id + in: query + description: The order ID (order hash) to check scoring status for + required: true + schema: + type: string + example: '0xabcdef1234567890abcdef1234567890abcdef1234567890abcdef1234567890' + responses: + '200': + description: Successfully retrieved order scoring status + content: + application/json: + schema: + $ref: '#/components/schemas/OrderScoringResponse' + examples: + scoring: + summary: Order is scoring + value: + scoring: true + not_scoring: + summary: Order is not scoring + value: + scoring: false + '400': + description: Bad request - Invalid order ID + content: + application/json: + schema: + $ref: '#/components/schemas/ErrorResponse' + example: + error: Invalid order_id + '401': + description: Unauthorized - Invalid API key or order doesn't belong to user + content: + application/json: + schema: + $ref: '#/components/schemas/ErrorResponse' + example: + error: Invalid API key + '404': + description: Market not found for the order + content: + application/json: + schema: + $ref: '#/components/schemas/ErrorResponse' + example: + error: market not found + '500': + description: Internal server error + content: + application/json: + schema: + $ref: '#/components/schemas/ErrorResponse' + example: + error: Internal server error + '503': + description: Service unavailable - Trading disabled + content: + application/json: + schema: + $ref: '#/components/schemas/ErrorResponse' + example: + error: >- + Trading is currently disabled. Check polymarket.com for + updates + security: + - polyApiKey: [] + polyAddress: [] + polySignature: [] + polyPassphrase: [] + polyTimestamp: [] +components: + schemas: + OrderScoringResponse: + type: object + description: Response indicating whether an order is currently scoring for rewards + required: + - scoring + properties: + scoring: + type: boolean + description: Whether the order is currently scoring for maker rewards + example: true + ErrorResponse: + type: object + required: + - error + properties: + error: + type: string + description: Error message + code: + type: string + description: Machine-readable error code, when provided + retry_after_seconds: + type: integer + description: Number of seconds to wait before retrying, when provided + securitySchemes: + polyApiKey: + type: apiKey + in: header + name: POLY_API_KEY + description: Your API key + polyAddress: + type: apiKey + in: header + name: POLY_ADDRESS + description: Ethereum address associated with the API key + polySignature: + type: apiKey + in: header + name: POLY_SIGNATURE + description: HMAC signature of the request + polyPassphrase: + type: apiKey + in: header + name: POLY_PASSPHRASE + description: API key passphrase + polyTimestamp: + type: apiKey + in: header + name: POLY_TIMESTAMP + description: Unix timestamp of the request + +```` \ No newline at end of file diff --git a/PolymarketDocumentation-main/docs/api-reference/trade/get-single-order-by-id.md b/PolymarketDocumentation-main/docs/api-reference/trade/get-single-order-by-id.md new file mode 100644 index 00000000..d0cc05a5 --- /dev/null +++ b/PolymarketDocumentation-main/docs/api-reference/trade/get-single-order-by-id.md @@ -0,0 +1,263 @@ +> ## Documentation Index +> Fetch the complete documentation index at: https://docs.polymarket.com/llms.txt +> Use this file to discover all available pages before exploring further. + +# Get single order by ID + +> Retrieves a specific order by its ID (order hash) for the authenticated user. +Builder-authenticated clients can also use this endpoint to retrieve orders attributed to their builder account. + + + + +## OpenAPI + +````yaml /api-spec/clob-openapi.yaml get /data/order/{orderID} +openapi: 3.1.0 +info: + title: Polymarket CLOB API + description: Polymarket CLOB API Reference + license: + name: MIT + identifier: MIT + version: 1.0.0 +servers: + - url: https://clob.polymarket.com + description: Production CLOB API + - url: https://clob-staging.polymarket.com + description: Staging CLOB API +security: [] +tags: + - name: Trade + description: Trade endpoints + - name: Markets + description: Market data endpoints + - name: Account + description: Account and authentication endpoints + - name: Notifications + description: User notification endpoints + - name: Rewards + description: Rewards and earnings endpoints + - name: Rebates + description: Maker rebate endpoints +paths: + /data/order/{orderID}: + get: + tags: + - Trade + summary: Get single order by ID + description: > + Retrieves a specific order by its ID (order hash) for the authenticated + user. + + Builder-authenticated clients can also use this endpoint to retrieve + orders attributed to their builder account. + operationId: getOrder + parameters: + - name: orderID + in: path + description: Order ID (order hash) + required: true + schema: + type: string + example: '0x0000000000000000000000000000000000000000000000000000000000000001' + responses: + '200': + description: Successfully retrieved order + content: + application/json: + schema: + $ref: '#/components/schemas/OpenOrder' + example: + id: '0xabcdef1234567890abcdef1234567890abcdef12' + status: ORDER_STATUS_LIVE + owner: f4f247b7-4ac7-ff29-a152-04fda0a8755a + maker_address: '0x1234567890123456789012345678901234567890' + market: >- + 0x0000000000000000000000000000000000000000000000000000000000000001 + asset_id: 0xabc123def456... + side: BUY + original_size: '100000000' + size_matched: '0' + price: '0.5' + outcome: 'YES' + expiration: '1735689600' + order_type: GTC + associate_trades: [] + created_at: 1700000000 + '400': + description: Bad request - Invalid order ID + content: + application/json: + schema: + $ref: '#/components/schemas/ErrorResponse' + example: + error: Invalid orderID + '401': + description: Unauthorized - Invalid API key or authentication failed + content: + application/json: + schema: + $ref: '#/components/schemas/ErrorResponse' + example: + error: Invalid API key + '404': + description: Order not found + content: + application/json: + schema: + $ref: '#/components/schemas/ErrorResponse' + example: + error: Order not found + '500': + description: Internal server error + content: + application/json: + schema: + $ref: '#/components/schemas/ErrorResponse' + example: + error: Internal server error + security: + - polyApiKey: [] + polyAddress: [] + polySignature: [] + polyPassphrase: [] + polyTimestamp: [] +components: + schemas: + OpenOrder: + type: object + required: + - id + - status + - owner + - maker_address + - market + - asset_id + - side + - original_size + - size_matched + - price + - expiration + - order_type + - created_at + - outcome + properties: + id: + type: string + description: Order ID (order hash) + example: '0xabcdef1234567890abcdef1234567890abcdef12' + status: + type: string + description: Order status + enum: + - ORDER_STATUS_LIVE + - ORDER_STATUS_INVALID + - ORDER_STATUS_CANCELED_MARKET_RESOLVED + - ORDER_STATUS_CANCELED + - ORDER_STATUS_MATCHED + owner: + type: string + description: UUID of the order owner + example: f4f247b7-4ac7-ff29-a152-04fda0a8755a + maker_address: + type: string + description: Ethereum address of the maker + example: '0x1234567890123456789012345678901234567890' + market: + type: string + description: Market (condition ID) + example: '0x0000000000000000000000000000000000000000000000000000000000000001' + asset_id: + type: string + description: Asset ID (token ID) + example: 0xabc123def456... + side: + type: string + description: Order side + enum: + - BUY + - SELL + example: BUY + original_size: + type: string + description: Original order size in fixed-math with 6 decimals + example: '100000000' + size_matched: + type: string + description: Size that has been matched in fixed-math with 6 decimals + example: '0' + price: + type: string + description: Order price + example: '0.5' + outcome: + type: string + description: Market outcome (YES/NO) + example: 'YES' + expiration: + type: string + description: Unix timestamp when the order expires + example: '1735689600' + order_type: + type: string + description: Order type + enum: + - GTC + - FOK + - GTD + - FAK + example: GTC + associate_trades: + type: array + description: Array of associated trade IDs + items: + type: string + example: + - trade-123 + created_at: + type: integer + description: Unix timestamp when the order was created + example: 1700000000 + ErrorResponse: + type: object + required: + - error + properties: + error: + type: string + description: Error message + code: + type: string + description: Machine-readable error code, when provided + retry_after_seconds: + type: integer + description: Number of seconds to wait before retrying, when provided + securitySchemes: + polyApiKey: + type: apiKey + in: header + name: POLY_API_KEY + description: Your API key + polyAddress: + type: apiKey + in: header + name: POLY_ADDRESS + description: Ethereum address associated with the API key + polySignature: + type: apiKey + in: header + name: POLY_SIGNATURE + description: HMAC signature of the request + polyPassphrase: + type: apiKey + in: header + name: POLY_PASSPHRASE + description: API key passphrase + polyTimestamp: + type: apiKey + in: header + name: POLY_TIMESTAMP + description: Unix timestamp of the request + +```` \ No newline at end of file diff --git a/PolymarketDocumentation-main/docs/api-reference/trade/get-trades.md b/PolymarketDocumentation-main/docs/api-reference/trade/get-trades.md new file mode 100644 index 00000000..28921541 --- /dev/null +++ b/PolymarketDocumentation-main/docs/api-reference/trade/get-trades.md @@ -0,0 +1,395 @@ +> ## Documentation Index +> Fetch the complete documentation index at: https://docs.polymarket.com/llms.txt +> Use this file to discover all available pages before exploring further. + +# Get trades + +> Retrieves trades for the authenticated user. Returns paginated results. +Requires readonly or level 2 API key authentication. + + + + +## OpenAPI + +````yaml /api-spec/clob-openapi.yaml get /data/trades +openapi: 3.1.0 +info: + title: Polymarket CLOB API + description: Polymarket CLOB API Reference + license: + name: MIT + identifier: MIT + version: 1.0.0 +servers: + - url: https://clob.polymarket.com + description: Production CLOB API + - url: https://clob-staging.polymarket.com + description: Staging CLOB API +security: [] +tags: + - name: Trade + description: Trade endpoints + - name: Markets + description: Market data endpoints + - name: Account + description: Account and authentication endpoints + - name: Notifications + description: User notification endpoints + - name: Rewards + description: Rewards and earnings endpoints + - name: Rebates + description: Maker rebate endpoints +paths: + /data/trades: + get: + tags: + - Trade + summary: Get trades + description: | + Retrieves trades for the authenticated user. Returns paginated results. + Requires readonly or level 2 API key authentication. + operationId: getTrades + parameters: + - name: id + in: query + description: Trade ID to filter by specific trade + required: false + schema: + type: string + example: trade-123 + - name: maker_address + in: query + description: Maker address to filter trades + required: true + schema: + type: string + pattern: ^0x[a-fA-F0-9]{40}$ + example: '0x1234567890123456789012345678901234567890' + - name: market + in: query + description: Market (condition ID) to filter trades + required: false + schema: + type: string + pattern: ^0x[a-fA-F0-9]{64}$ + example: '0x0000000000000000000000000000000000000000000000000000000000000001' + - name: asset_id + in: query + description: Asset ID (token ID) to filter trades + required: false + schema: + type: string + example: >- + 15871154585880608648532107628464183779895785213830018178010423617714102767076 + - name: before + in: query + description: Filter trades before this Unix timestamp + required: false + schema: + type: string + pattern: ^\d+$ + example: '1700000000' + - name: after + in: query + description: Filter trades after this Unix timestamp + required: false + schema: + type: string + pattern: ^\d+$ + example: '1600000000' + - name: next_cursor + in: query + description: Cursor for pagination (base64 encoded offset) + required: false + schema: + type: string + example: MA== + responses: + '200': + description: Successfully retrieved trades + content: + application/json: + schema: + $ref: '#/components/schemas/TradesResponse' + examples: + example: + summary: User trades response + value: + limit: 100 + next_cursor: MTAw + count: 2 + data: + - id: trade-123 + taker_order_id: '0xabcdef1234567890abcdef1234567890abcdef12' + market: >- + 0x0000000000000000000000000000000000000000000000000000000000000001 + asset_id: >- + 15871154585880608648532107628464183779895785213830018178010423617714102767076 + side: BUY + size: '100000000' + fee_rate_bps: '30' + price: '0.5' + status: TRADE_STATUS_CONFIRMED + match_time: '1700000000' + last_update: '1700000000' + outcome: 'YES' + bucket_index: 0 + owner: f4f247b7-4ac7-ff29-a152-04fda0a8755a + maker_address: '0x1234567890123456789012345678901234567890' + transaction_hash: >- + 0x1234567890abcdef1234567890abcdef1234567890abcdef1234567890abcdef + trader_side: TAKER + maker_orders: [] + '400': + description: Bad request - Invalid parameters + content: + application/json: + schema: + $ref: '#/components/schemas/ErrorResponse' + example: + error: Invalid trade params payload + '401': + description: Unauthorized - Invalid API key or authentication failed + content: + application/json: + schema: + $ref: '#/components/schemas/ErrorResponse' + example: + error: Invalid API key + '500': + description: Internal server error + content: + application/json: + schema: + $ref: '#/components/schemas/ErrorResponse' + example: + error: Internal server error + security: + - polyApiKey: [] + polyAddress: [] + polySignature: [] + polyPassphrase: [] + polyTimestamp: [] +components: + schemas: + TradesResponse: + type: object + description: Paginated trades response + required: + - limit + - next_cursor + - count + - data + properties: + limit: + type: integer + description: Maximum number of items per page + example: 100 + next_cursor: + type: string + description: >- + Cursor for next page (base64 encoded offset). "LTE=" indicates no + more pages + example: MTAw + count: + type: integer + description: Number of items in current response + example: 2 + data: + type: array + description: Array of trades + items: + $ref: '#/components/schemas/Trade' + ErrorResponse: + type: object + required: + - error + properties: + error: + type: string + description: Error message + code: + type: string + description: Machine-readable error code, when provided + retry_after_seconds: + type: integer + description: Number of seconds to wait before retrying, when provided + Trade: + type: object + description: Trade information + required: + - id + - taker_order_id + - market + - asset_id + - side + - size + - price + - status + - match_time + - last_update + - outcome + - bucket_index + - owner + - maker_address + - trader_side + properties: + id: + type: string + description: Trade ID + example: trade-123 + taker_order_id: + type: string + description: Taker order ID (hash) + example: '0xabcdef1234567890abcdef1234567890abcdef12' + market: + type: string + description: Market (condition ID) + pattern: ^0x[a-fA-F0-9]{64}$ + example: '0x0000000000000000000000000000000000000000000000000000000000000001' + asset_id: + type: string + description: Asset ID (token ID) + example: >- + 15871154585880608648532107628464183779895785213830018178010423617714102767076 + side: + type: string + description: Trade side + enum: + - BUY + - SELL + example: BUY + size: + type: string + description: Trade size + example: '100000000' + fee_rate_bps: + type: string + description: Fee rate in basis points + example: '30' + price: + type: string + description: Trade price + example: '0.5' + status: + type: string + description: Trade status + enum: + - TRADE_STATUS_CONFIRMED + - TRADE_STATUS_FAILED + - TRADE_STATUS_RETRYING + - TRADE_STATUS_MATCHED + - TRADE_STATUS_MINED + example: TRADE_STATUS_CONFIRMED + match_time: + type: string + description: Match time (Unix timestamp) + example: '1700000000' + match_time_nano: + type: string + description: Match time in nanoseconds + example: '1700000000000000000' + last_update: + type: string + description: Last update time (Unix timestamp) + example: '1700000000' + outcome: + type: string + description: Market outcome + example: 'YES' + bucket_index: + type: integer + description: Bucket index + example: 0 + owner: + type: string + description: Owner UUID + example: f4f247b7-4ac7-ff29-a152-04fda0a8755a + maker_address: + type: string + description: Maker address + pattern: ^0x[a-fA-F0-9]{40}$ + example: '0x1234567890123456789012345678901234567890' + transaction_hash: + type: string + description: Transaction hash + pattern: ^0x[a-fA-F0-9]{64}$ + example: '0x1234567890abcdef1234567890abcdef1234567890abcdef1234567890abcdef' + err_msg: + type: + - string + - 'null' + description: Error message (if any) + example: null + maker_orders: + type: array + description: Array of maker orders associated with this trade + items: + type: object + properties: + order_id: + type: string + description: Order ID (hash) + owner: + type: string + description: Owner UUID + maker_address: + type: string + description: Maker address + matched_amount: + type: string + description: Matched amount + price: + type: string + description: Price + fee_rate_bps: + type: string + description: Fee rate in basis points + asset_id: + type: string + description: Asset ID + outcome: + type: string + description: Outcome + side: + type: string + enum: + - BUY + - SELL + example: [] + trader_side: + type: string + description: Trader side (TAKER or MAKER) + enum: + - TAKER + - MAKER + example: TAKER + securitySchemes: + polyApiKey: + type: apiKey + in: header + name: POLY_API_KEY + description: Your API key + polyAddress: + type: apiKey + in: header + name: POLY_ADDRESS + description: Ethereum address associated with the API key + polySignature: + type: apiKey + in: header + name: POLY_SIGNATURE + description: HMAC signature of the request + polyPassphrase: + type: apiKey + in: header + name: POLY_PASSPHRASE + description: API key passphrase + polyTimestamp: + type: apiKey + in: header + name: POLY_TIMESTAMP + description: Unix timestamp of the request + +```` \ No newline at end of file diff --git a/PolymarketDocumentation-main/docs/api-reference/trade/get-user-orders.md b/PolymarketDocumentation-main/docs/api-reference/trade/get-user-orders.md new file mode 100644 index 00000000..bee4ce30 --- /dev/null +++ b/PolymarketDocumentation-main/docs/api-reference/trade/get-user-orders.md @@ -0,0 +1,327 @@ +> ## Documentation Index +> Fetch the complete documentation index at: https://docs.polymarket.com/llms.txt +> Use this file to discover all available pages before exploring further. + +# Get user orders + +> Retrieves open orders for the authenticated user. Returns paginated results. +Builder-authenticated clients can also use this endpoint to retrieve orders attributed to their builder account. + + + + +## OpenAPI + +````yaml /api-spec/clob-openapi.yaml get /data/orders +openapi: 3.1.0 +info: + title: Polymarket CLOB API + description: Polymarket CLOB API Reference + license: + name: MIT + identifier: MIT + version: 1.0.0 +servers: + - url: https://clob.polymarket.com + description: Production CLOB API + - url: https://clob-staging.polymarket.com + description: Staging CLOB API +security: [] +tags: + - name: Trade + description: Trade endpoints + - name: Markets + description: Market data endpoints + - name: Account + description: Account and authentication endpoints + - name: Notifications + description: User notification endpoints + - name: Rewards + description: Rewards and earnings endpoints + - name: Rebates + description: Maker rebate endpoints +paths: + /data/orders: + get: + tags: + - Trade + summary: Get user orders + description: > + Retrieves open orders for the authenticated user. Returns paginated + results. + + Builder-authenticated clients can also use this endpoint to retrieve + orders attributed to their builder account. + operationId: getOrders + parameters: + - name: id + in: query + description: Order ID (hash) to filter by specific order + required: false + schema: + type: string + example: '0xabcdef1234567890abcdef1234567890abcdef12' + - name: market + in: query + description: Market (condition ID) to filter orders + required: false + schema: + type: string + example: '0x0000000000000000000000000000000000000000000000000000000000000001' + - name: asset_id + in: query + description: Asset ID (token ID) to filter orders + required: false + schema: + type: string + example: 0xabc123def456... + - name: next_cursor + in: query + description: Cursor for pagination (base64 encoded offset) + required: false + schema: + type: string + example: MA== + responses: + '200': + description: Successfully retrieved orders + content: + application/json: + schema: + $ref: '#/components/schemas/OrdersResponse' + examples: + example: + summary: User orders response + value: + limit: 100 + next_cursor: MTAw + count: 2 + data: + - id: '0xabcdef1234567890abcdef1234567890abcdef12' + status: ORDER_STATUS_LIVE + owner: f4f247b7-4ac7-ff29-a152-04fda0a8755a + maker_address: '0x1234567890123456789012345678901234567890' + market: >- + 0x0000000000000000000000000000000000000000000000000000000000000001 + asset_id: 0xabc123def456... + side: BUY + original_size: '100000000' + size_matched: '0' + price: '0.5' + outcome: 'YES' + expiration: '1735689600' + order_type: GTC + associate_trades: [] + created_at: 1700000000 + - id: '0xfedcba0987654321fedcba0987654321fedcba09' + status: ORDER_STATUS_LIVE + owner: f4f247b7-4ac7-ff29-a152-04fda0a8755a + maker_address: '0x1234567890123456789012345678901234567890' + market: >- + 0x0000000000000000000000000000000000000000000000000000000000000002 + asset_id: 0xdef456abc789... + side: SELL + original_size: '200000000' + size_matched: '50000000' + price: '0.75' + outcome: 'NO' + expiration: '1735689600' + order_type: GTC + associate_trades: + - trade-123 + created_at: 1700000001 + '400': + description: Bad request - Invalid parameters + content: + application/json: + schema: + $ref: '#/components/schemas/ErrorResponse' + example: + error: invalid order params payload + '401': + description: Unauthorized - Invalid API key or authentication failed + content: + application/json: + schema: + $ref: '#/components/schemas/ErrorResponse' + example: + error: Invalid API key + '500': + description: Internal server error + content: + application/json: + schema: + $ref: '#/components/schemas/ErrorResponse' + example: + error: Internal server error + security: + - polyApiKey: [] + polyAddress: [] + polySignature: [] + polyPassphrase: [] + polyTimestamp: [] +components: + schemas: + OrdersResponse: + type: object + required: + - limit + - next_cursor + - count + - data + properties: + limit: + type: integer + description: Maximum number of results per page + example: 100 + next_cursor: + type: string + description: >- + Cursor for pagination (base64 encoded offset). Empty if no more + results. + example: MTAw + count: + type: integer + description: Number of orders in this response + example: 2 + data: + type: array + description: Array of open orders + items: + $ref: '#/components/schemas/OpenOrder' + ErrorResponse: + type: object + required: + - error + properties: + error: + type: string + description: Error message + code: + type: string + description: Machine-readable error code, when provided + retry_after_seconds: + type: integer + description: Number of seconds to wait before retrying, when provided + OpenOrder: + type: object + required: + - id + - status + - owner + - maker_address + - market + - asset_id + - side + - original_size + - size_matched + - price + - expiration + - order_type + - created_at + - outcome + properties: + id: + type: string + description: Order ID (order hash) + example: '0xabcdef1234567890abcdef1234567890abcdef12' + status: + type: string + description: Order status + enum: + - ORDER_STATUS_LIVE + - ORDER_STATUS_INVALID + - ORDER_STATUS_CANCELED_MARKET_RESOLVED + - ORDER_STATUS_CANCELED + - ORDER_STATUS_MATCHED + owner: + type: string + description: UUID of the order owner + example: f4f247b7-4ac7-ff29-a152-04fda0a8755a + maker_address: + type: string + description: Ethereum address of the maker + example: '0x1234567890123456789012345678901234567890' + market: + type: string + description: Market (condition ID) + example: '0x0000000000000000000000000000000000000000000000000000000000000001' + asset_id: + type: string + description: Asset ID (token ID) + example: 0xabc123def456... + side: + type: string + description: Order side + enum: + - BUY + - SELL + example: BUY + original_size: + type: string + description: Original order size in fixed-math with 6 decimals + example: '100000000' + size_matched: + type: string + description: Size that has been matched in fixed-math with 6 decimals + example: '0' + price: + type: string + description: Order price + example: '0.5' + outcome: + type: string + description: Market outcome (YES/NO) + example: 'YES' + expiration: + type: string + description: Unix timestamp when the order expires + example: '1735689600' + order_type: + type: string + description: Order type + enum: + - GTC + - FOK + - GTD + - FAK + example: GTC + associate_trades: + type: array + description: Array of associated trade IDs + items: + type: string + example: + - trade-123 + created_at: + type: integer + description: Unix timestamp when the order was created + example: 1700000000 + securitySchemes: + polyApiKey: + type: apiKey + in: header + name: POLY_API_KEY + description: Your API key + polyAddress: + type: apiKey + in: header + name: POLY_ADDRESS + description: Ethereum address associated with the API key + polySignature: + type: apiKey + in: header + name: POLY_SIGNATURE + description: HMAC signature of the request + polyPassphrase: + type: apiKey + in: header + name: POLY_PASSPHRASE + description: API key passphrase + polyTimestamp: + type: apiKey + in: header + name: POLY_TIMESTAMP + description: Unix timestamp of the request + +```` \ No newline at end of file diff --git a/PolymarketDocumentation-main/docs/api-reference/trade/post-a-new-order.md b/PolymarketDocumentation-main/docs/api-reference/trade/post-a-new-order.md new file mode 100644 index 00000000..703f462c --- /dev/null +++ b/PolymarketDocumentation-main/docs/api-reference/trade/post-a-new-order.md @@ -0,0 +1,418 @@ +> ## Documentation Index +> Fetch the complete documentation index at: https://docs.polymarket.com/llms.txt +> Use this file to discover all available pages before exploring further. + +# Post a new order + +> Creates a new order in the order book + + + + +## OpenAPI + +````yaml /api-spec/clob-openapi.yaml post /order +openapi: 3.1.0 +info: + title: Polymarket CLOB API + description: Polymarket CLOB API Reference + license: + name: MIT + identifier: MIT + version: 1.0.0 +servers: + - url: https://clob.polymarket.com + description: Production CLOB API + - url: https://clob-staging.polymarket.com + description: Staging CLOB API +security: [] +tags: + - name: Trade + description: Trade endpoints + - name: Markets + description: Market data endpoints + - name: Account + description: Account and authentication endpoints + - name: Notifications + description: User notification endpoints + - name: Rewards + description: Rewards and earnings endpoints + - name: Rebates + description: Maker rebate endpoints +paths: + /order: + post: + tags: + - Trade + summary: Post a new order + description: | + Creates a new order in the order book + operationId: postOrder + requestBody: + required: true + content: + application/json: + schema: + $ref: '#/components/schemas/SendOrder' + examples: + example: + summary: Send order example + value: + order: + maker: '0x1234567890123456789012345678901234567890' + signer: '0x1234567890123456789012345678901234567890' + tokenId: 0xabc123def456... + makerAmount: '100000000' + takerAmount: '200000000' + side: BUY + expiration: '1735689600' + timestamp: '1735689600000' + metadata: '' + builder: >- + 0x0000000000000000000000000000000000000000000000000000000000000000 + signature: 0x1234abcd... + salt: 1234567890 + signatureType: 0 + owner: f4f247b7-4ac7-ff29-a152-04fda0a8755a + orderType: GTC + deferExec: false + postOnly: false + responses: + '200': + description: Order successfully processed + content: + application/json: + schema: + $ref: '#/components/schemas/SendOrderResponse' + examples: + live_order: + summary: Order placed on book + value: + success: true + orderID: '0xabcdef1234567890abcdef1234567890abcdef12' + status: live + makingAmount: '100000000' + takingAmount: '200000000' + errorMsg: '' + matched_order: + summary: Order immediately matched + value: + success: true + orderID: '0xabcdef1234567890abcdef1234567890abcdef12' + status: matched + makingAmount: '100000000' + takingAmount: '200000000' + transactionsHashes: + - '0x1234567890abcdef1234567890abcdef12345678' + tradeIDs: + - trade-123 + errorMsg: '' + delayed_order: + summary: Order delayed + value: + success: true + orderID: '0xabcdef1234567890abcdef1234567890abcdef12' + status: delayed + makingAmount: '100000000' + takingAmount: '200000000' + errorMsg: '' + '400': + description: Bad request - Invalid order payload or validation error + content: + application/json: + schema: + $ref: '#/components/schemas/ErrorResponse' + examples: + invalid_payload: + summary: Invalid order payload + value: + error: Invalid order payload + owner_mismatch: + summary: Owner mismatch + value: + error: the order owner has to be the owner of the API KEY + signer_mismatch: + summary: Signer mismatch + value: + error: >- + the order signer address has to be the address of the API + KEY + banned_address: + summary: Banned address + value: + error: '''0x1234...'' address banned' + closed_only_mode: + summary: Closed only mode violation + value: + error: '''0x1234...'' address in closed only mode' + invalid_order: + summary: Invalid order details + value: + error: >- + order 0xabc... is invalid. Price (100) breaks minimum tick + size rule: 0.1 + '401': + description: Unauthorized - Invalid API key or authentication failed + content: + application/json: + schema: + $ref: '#/components/schemas/ErrorResponse' + example: + error: Invalid API key + '500': + description: Internal server error + content: + application/json: + schema: + $ref: '#/components/schemas/ErrorResponse' + example: + error: could not insert order + '503': + description: Service unavailable - Trading disabled or cancel-only mode + headers: + Retry-After: + description: Seconds to wait before retrying when provided by post-only mode. + schema: + type: integer + content: + application/json: + schema: + $ref: '#/components/schemas/ErrorResponse' + examples: + trading_disabled: + summary: Trading disabled + value: + error: >- + Trading is currently disabled. Check polymarket.com for + updates + cancel_only: + summary: Cancel-only mode + value: + error: >- + Trading is currently cancel-only. New orders are not + accepted, but cancels are allowed. + post_only_mode: + summary: Post-only mode + value: + error: >- + post-only mode: only post-only orders and cancels are + allowed + code: post_only_mode + retry_after_seconds: 79 + security: + - polyApiKey: [] + polyAddress: [] + polySignature: [] + polyPassphrase: [] + polyTimestamp: [] +components: + schemas: + SendOrder: + type: object + required: + - order + - owner + properties: + order: + $ref: '#/components/schemas/Order' + owner: + type: string + description: UUID of the API key owner + example: f4f247b7-4ac7-ff29-a152-04fda0a8755a + orderType: + type: string + description: Time in force + enum: + - GTC + - FOK + - GTD + - FAK + default: GTC + deferExec: + type: boolean + description: Whether to defer execution + default: false + postOnly: + type: boolean + description: >- + Whether the order must rest on the book and not match immediately. + Only supported for GTC and GTD orders. + default: false + SendOrderResponse: + type: object + required: + - success + - orderID + - status + properties: + success: + type: boolean + description: Whether the order was successfully processed + example: true + orderID: + type: string + description: Unique identifier for the order (order hash) + example: '0xabcdef1234567890abcdef1234567890abcdef12' + status: + type: string + description: Status of the order after processing + enum: + - live + - matched + - delayed + makingAmount: + type: string + description: Amount the maker is providing in fixed-math with 6 decimals + example: '100000000' + takingAmount: + type: string + description: Amount the taker is providing in fixed-math with 6 decimals + example: '200000000' + transactionsHashes: + type: array + description: Array of transaction hashes (present when status is 'matched') + items: + type: string + example: + - '0x1234567890abcdef1234567890abcdef12345678' + tradeIDs: + type: array + description: Array of trade IDs (present when status is 'matched') + items: + type: string + errorMsg: + type: string + description: Error message (empty on success) + example: '' + ErrorResponse: + type: object + required: + - error + properties: + error: + type: string + description: Error message + code: + type: string + description: Machine-readable error code, when provided + retry_after_seconds: + type: integer + description: Number of seconds to wait before retrying, when provided + Order: + type: object + description: > + Order payload submitted to the CLOB API. In CLOB V2, `expiration` + remains in + + the POST /order wire body for GTD/order-expiry handling, but it is not + part + + of the EIP-712 signed order struct. + required: + - maker + - signer + - tokenId + - makerAmount + - takerAmount + - side + - expiration + - timestamp + - builder + - signature + - salt + - signatureType + properties: + maker: + type: string + description: >- + Ethereum address of the maker (In the default case, this is your + proxy address) + example: '0x1234567890123456789012345678901234567890' + signer: + type: string + description: Ethereum address of the signer + example: '0x1234567890123456789012345678901234567890' + tokenId: + type: string + description: Token ID (asset ID) for the order + example: 0xabc123def456... + makerAmount: + type: string + description: Amount the maker is providing in fixed-math with 6 decimals + example: '100000000' + takerAmount: + type: string + description: Amount the taker is providing in fixed-math with 6 decimals + example: '200000000' + side: + type: string + description: Order side + enum: + - BUY + - SELL + example: BUY + expiration: + type: string + description: >- + Unix timestamp when the order expires. Present in the API wire body; + not part of the CLOB V2 EIP-712 signed order struct. + example: '1735689600' + timestamp: + type: string + description: >- + Unix timestamp in milliseconds when the order was created (used for + order uniqueness) + example: '1735689600000' + metadata: + type: string + description: Reserved for future use + example: '' + builder: + type: string + description: >- + Builder code (bytes32) for integrator attribution. `0x` + 64 hex + chars or empty. + example: '0x0000000000000000000000000000000000000000000000000000000000000000' + signature: + type: string + description: Cryptographic signature of the order + example: 0x1234abcd... + salt: + type: integer + description: Random salt for order uniqueness + example: 1234567890 + signatureType: + type: integer + description: Type of signature (0 = EOA, 1 = POLY_PROXY, 2 = POLY_GNOSIS_SAFE) + enum: + - 0 + - 1 + - 2 + securitySchemes: + polyApiKey: + type: apiKey + in: header + name: POLY_API_KEY + description: Your API key + polyAddress: + type: apiKey + in: header + name: POLY_ADDRESS + description: Ethereum address associated with the API key + polySignature: + type: apiKey + in: header + name: POLY_SIGNATURE + description: HMAC signature of the request + polyPassphrase: + type: apiKey + in: header + name: POLY_PASSPHRASE + description: API key passphrase + polyTimestamp: + type: apiKey + in: header + name: POLY_TIMESTAMP + description: Unix timestamp of the request + +```` \ No newline at end of file diff --git a/PolymarketDocumentation-main/docs/api-reference/trade/post-multiple-orders.md b/PolymarketDocumentation-main/docs/api-reference/trade/post-multiple-orders.md new file mode 100644 index 00000000..20c1af1d --- /dev/null +++ b/PolymarketDocumentation-main/docs/api-reference/trade/post-multiple-orders.md @@ -0,0 +1,461 @@ +> ## Documentation Index +> Fetch the complete documentation index at: https://docs.polymarket.com/llms.txt +> Use this file to discover all available pages before exploring further. + +# Post multiple orders + +> Creates multiple new orders in the order book. Orders are processed in parallel. +Maximum 15 orders per request. + + + + +## OpenAPI + +````yaml /api-spec/clob-openapi.yaml post /orders +openapi: 3.1.0 +info: + title: Polymarket CLOB API + description: Polymarket CLOB API Reference + license: + name: MIT + identifier: MIT + version: 1.0.0 +servers: + - url: https://clob.polymarket.com + description: Production CLOB API + - url: https://clob-staging.polymarket.com + description: Staging CLOB API +security: [] +tags: + - name: Trade + description: Trade endpoints + - name: Markets + description: Market data endpoints + - name: Account + description: Account and authentication endpoints + - name: Notifications + description: User notification endpoints + - name: Rewards + description: Rewards and earnings endpoints + - name: Rebates + description: Maker rebate endpoints +paths: + /orders: + post: + tags: + - Trade + summary: Post multiple orders + description: > + Creates multiple new orders in the order book. Orders are processed in + parallel. + + Maximum 15 orders per request. + operationId: postOrders + requestBody: + required: true + content: + application/json: + schema: + type: array + items: + $ref: '#/components/schemas/SendOrder' + maxItems: 15 + examples: + example: + summary: Send multiple orders example + value: + - order: + maker: '0x1234567890123456789012345678901234567890' + signer: '0x1234567890123456789012345678901234567890' + tokenId: 0xabc123def456... + makerAmount: '100000000' + takerAmount: '200000000' + side: BUY + expiration: '1735689600' + timestamp: '1735689600000' + metadata: '' + builder: >- + 0x0000000000000000000000000000000000000000000000000000000000000000 + signature: 0x1234abcd... + salt: 1234567890 + signatureType: 0 + owner: f4f247b7-4ac7-ff29-a152-04fda0a8755a + orderType: GTC + deferExec: false + postOnly: false + - order: + maker: '0x1234567890123456789012345678901234567890' + signer: '0x1234567890123456789012345678901234567890' + tokenId: 0xdef456abc789... + makerAmount: '200000000' + takerAmount: '100000000' + side: SELL + expiration: '1735689600' + timestamp: '1735689600000' + metadata: '' + builder: >- + 0x0000000000000000000000000000000000000000000000000000000000000000 + signature: 0x5678efgh... + salt: 1234567891 + signatureType: 0 + owner: f4f247b7-4ac7-ff29-a152-04fda0a8755a + orderType: GTC + deferExec: false + postOnly: false + responses: + '200': + description: >- + Orders successfully processed. Returns an array of order responses, + one for each order in the request. + content: + application/json: + schema: + type: array + items: + $ref: '#/components/schemas/SendOrderResponse' + examples: + mixed_results: + summary: Mixed order results + value: + - success: true + orderID: '0xabcdef1234567890abcdef1234567890abcdef12' + status: live + makingAmount: '100000000' + takingAmount: '200000000' + errorMsg: '' + - success: true + orderID: '0xfedcba0987654321fedcba0987654321fedcba09' + status: matched + makingAmount: '200000000' + takingAmount: '100000000' + transactionsHashes: + - '0x1234567890abcdef1234567890abcdef12345678' + tradeIDs: + - trade-123 + errorMsg: '' + - success: false + orderID: '' + status: delayed + errorMsg: 'Rate limit exceeded for tokenId: 0xdef456abc789...' + post_only_mode: + summary: Post-only mode results + value: + - errorMsg: >- + post-only mode: only post-only orders and cancels are + allowed + orderID: '' + takingAmount: '' + makingAmount: '' + status: '' + success: true + - errorMsg: >- + post-only mode: only post-only orders and cancels are + allowed + orderID: '' + takingAmount: '' + makingAmount: '' + status: '' + success: true + '400': + description: Bad request - Invalid order payload or validation error + content: + application/json: + schema: + $ref: '#/components/schemas/ErrorResponse' + examples: + invalid_payload: + summary: Invalid order payload + value: + error: Invalid order payload + empty_payload: + summary: Empty orders array + value: + error: Invalid order payload + too_many_orders: + summary: Too many orders + value: + error: 'Too many orders in payload: 20, max allowed: 15' + owner_mismatch: + summary: Owner mismatch + value: + error: the order owner has to be the owner of the API KEY + signer_mismatch: + summary: Signer mismatch + value: + error: >- + the order signer address has to be the address of the API + KEY + banned_address: + summary: Banned address + value: + error: '''0x1234...'' address banned' + closed_only_mode: + summary: Closed only mode violation + value: + error: '''0x1234...'' address in closed only mode' + '401': + description: Unauthorized - Invalid API key or authentication failed + content: + application/json: + schema: + $ref: '#/components/schemas/ErrorResponse' + example: + error: Invalid API key + '500': + description: Internal server error + content: + application/json: + schema: + $ref: '#/components/schemas/ErrorResponse' + example: + error: could not insert order + '503': + description: Service unavailable - Trading disabled or cancel-only mode + headers: + Retry-After: + description: Seconds to wait before retrying when provided by post-only mode. + schema: + type: integer + content: + application/json: + schema: + $ref: '#/components/schemas/ErrorResponse' + examples: + trading_disabled: + summary: Trading disabled + value: + error: >- + Trading is currently disabled. Check polymarket.com for + updates + cancel_only: + summary: Cancel-only mode + value: + error: >- + Trading is currently cancel-only. New orders are not + accepted, but cancels are allowed. + post_only_mode: + summary: Post-only mode + value: + error: >- + post-only mode: only post-only orders and cancels are + allowed + code: post_only_mode + retry_after_seconds: 79 + security: + - polyApiKey: [] + polyAddress: [] + polySignature: [] + polyPassphrase: [] + polyTimestamp: [] +components: + schemas: + SendOrder: + type: object + required: + - order + - owner + properties: + order: + $ref: '#/components/schemas/Order' + owner: + type: string + description: UUID of the API key owner + example: f4f247b7-4ac7-ff29-a152-04fda0a8755a + orderType: + type: string + description: Time in force + enum: + - GTC + - FOK + - GTD + - FAK + default: GTC + deferExec: + type: boolean + description: Whether to defer execution + default: false + postOnly: + type: boolean + description: >- + Whether the order must rest on the book and not match immediately. + Only supported for GTC and GTD orders. + default: false + SendOrderResponse: + type: object + required: + - success + - orderID + - status + properties: + success: + type: boolean + description: Whether the order was successfully processed + example: true + orderID: + type: string + description: Unique identifier for the order (order hash) + example: '0xabcdef1234567890abcdef1234567890abcdef12' + status: + type: string + description: Status of the order after processing + enum: + - live + - matched + - delayed + makingAmount: + type: string + description: Amount the maker is providing in fixed-math with 6 decimals + example: '100000000' + takingAmount: + type: string + description: Amount the taker is providing in fixed-math with 6 decimals + example: '200000000' + transactionsHashes: + type: array + description: Array of transaction hashes (present when status is 'matched') + items: + type: string + example: + - '0x1234567890abcdef1234567890abcdef12345678' + tradeIDs: + type: array + description: Array of trade IDs (present when status is 'matched') + items: + type: string + errorMsg: + type: string + description: Error message (empty on success) + example: '' + ErrorResponse: + type: object + required: + - error + properties: + error: + type: string + description: Error message + code: + type: string + description: Machine-readable error code, when provided + retry_after_seconds: + type: integer + description: Number of seconds to wait before retrying, when provided + Order: + type: object + description: > + Order payload submitted to the CLOB API. In CLOB V2, `expiration` + remains in + + the POST /order wire body for GTD/order-expiry handling, but it is not + part + + of the EIP-712 signed order struct. + required: + - maker + - signer + - tokenId + - makerAmount + - takerAmount + - side + - expiration + - timestamp + - builder + - signature + - salt + - signatureType + properties: + maker: + type: string + description: >- + Ethereum address of the maker (In the default case, this is your + proxy address) + example: '0x1234567890123456789012345678901234567890' + signer: + type: string + description: Ethereum address of the signer + example: '0x1234567890123456789012345678901234567890' + tokenId: + type: string + description: Token ID (asset ID) for the order + example: 0xabc123def456... + makerAmount: + type: string + description: Amount the maker is providing in fixed-math with 6 decimals + example: '100000000' + takerAmount: + type: string + description: Amount the taker is providing in fixed-math with 6 decimals + example: '200000000' + side: + type: string + description: Order side + enum: + - BUY + - SELL + example: BUY + expiration: + type: string + description: >- + Unix timestamp when the order expires. Present in the API wire body; + not part of the CLOB V2 EIP-712 signed order struct. + example: '1735689600' + timestamp: + type: string + description: >- + Unix timestamp in milliseconds when the order was created (used for + order uniqueness) + example: '1735689600000' + metadata: + type: string + description: Reserved for future use + example: '' + builder: + type: string + description: >- + Builder code (bytes32) for integrator attribution. `0x` + 64 hex + chars or empty. + example: '0x0000000000000000000000000000000000000000000000000000000000000000' + signature: + type: string + description: Cryptographic signature of the order + example: 0x1234abcd... + salt: + type: integer + description: Random salt for order uniqueness + example: 1234567890 + signatureType: + type: integer + description: Type of signature (0 = EOA, 1 = POLY_PROXY, 2 = POLY_GNOSIS_SAFE) + enum: + - 0 + - 1 + - 2 + securitySchemes: + polyApiKey: + type: apiKey + in: header + name: POLY_API_KEY + description: Your API key + polyAddress: + type: apiKey + in: header + name: POLY_ADDRESS + description: Ethereum address associated with the API key + polySignature: + type: apiKey + in: header + name: POLY_SIGNATURE + description: HMAC signature of the request + polyPassphrase: + type: apiKey + in: header + name: POLY_PASSPHRASE + description: API key passphrase + polyTimestamp: + type: apiKey + in: header + name: POLY_TIMESTAMP + description: Unix timestamp of the request + +```` \ No newline at end of file diff --git a/PolymarketDocumentation-main/docs/api-reference/trade/send-heartbeat.md b/PolymarketDocumentation-main/docs/api-reference/trade/send-heartbeat.md new file mode 100644 index 00000000..1170819b --- /dev/null +++ b/PolymarketDocumentation-main/docs/api-reference/trade/send-heartbeat.md @@ -0,0 +1,146 @@ +> ## Documentation Index +> Fetch the complete documentation index at: https://docs.polymarket.com/llms.txt +> Use this file to discover all available pages before exploring further. + +# Send heartbeat + +> Sends a heartbeat signal to maintain active session status. +If heartbeats are not sent regularly, all open orders for the user will be automatically canceled. +This is useful for automated trading systems that need to ensure orders are canceled +if the system becomes unresponsive. + + + + +## OpenAPI + +````yaml /api-spec/clob-openapi.yaml post /heartbeats +openapi: 3.1.0 +info: + title: Polymarket CLOB API + description: Polymarket CLOB API Reference + license: + name: MIT + identifier: MIT + version: 1.0.0 +servers: + - url: https://clob.polymarket.com + description: Production CLOB API + - url: https://clob-staging.polymarket.com + description: Staging CLOB API +security: [] +tags: + - name: Trade + description: Trade endpoints + - name: Markets + description: Market data endpoints + - name: Account + description: Account and authentication endpoints + - name: Notifications + description: User notification endpoints + - name: Rewards + description: Rewards and earnings endpoints + - name: Rebates + description: Maker rebate endpoints +paths: + /heartbeats: + post: + tags: + - Trade + summary: Send heartbeat + description: > + Sends a heartbeat signal to maintain active session status. + + If heartbeats are not sent regularly, all open orders for the user will + be automatically canceled. + + This is useful for automated trading systems that need to ensure orders + are canceled + + if the system becomes unresponsive. + operationId: sendHeartbeat + responses: + '200': + description: Heartbeat acknowledged + content: + application/json: + schema: + $ref: '#/components/schemas/HeartbeatResponse' + example: + status: ok + '401': + description: Unauthorized - Invalid API key or authentication failed + content: + application/json: + schema: + $ref: '#/components/schemas/ErrorResponse' + example: + error: Invalid API key + '500': + description: Internal server error + content: + application/json: + schema: + $ref: '#/components/schemas/ErrorResponse' + example: + error: Internal server error + security: + - polyApiKey: [] + polyAddress: [] + polySignature: [] + polyPassphrase: [] + polyTimestamp: [] +components: + schemas: + HeartbeatResponse: + type: object + description: Response for heartbeat request + required: + - status + properties: + status: + type: string + description: Status of the heartbeat acknowledgment + example: ok + ErrorResponse: + type: object + required: + - error + properties: + error: + type: string + description: Error message + code: + type: string + description: Machine-readable error code, when provided + retry_after_seconds: + type: integer + description: Number of seconds to wait before retrying, when provided + securitySchemes: + polyApiKey: + type: apiKey + in: header + name: POLY_API_KEY + description: Your API key + polyAddress: + type: apiKey + in: header + name: POLY_ADDRESS + description: Ethereum address associated with the API key + polySignature: + type: apiKey + in: header + name: POLY_SIGNATURE + description: HMAC signature of the request + polyPassphrase: + type: apiKey + in: header + name: POLY_PASSPHRASE + description: API key passphrase + polyTimestamp: + type: apiKey + in: header + name: POLY_TIMESTAMP + description: Unix timestamp of the request + +```` \ No newline at end of file diff --git a/PolymarketDocumentation-main/docs/api-reference/update-leverage.md b/PolymarketDocumentation-main/docs/api-reference/update-leverage.md new file mode 100644 index 00000000..16063b59 --- /dev/null +++ b/PolymarketDocumentation-main/docs/api-reference/update-leverage.md @@ -0,0 +1,290 @@ +> ## Documentation Index +> Fetch the complete documentation index at: https://docs.polymarket.com/llms.txt +> Use this file to discover all available pages before exploring further. + +# Update Leverage + +> Update leverage for an instrument. +Requires proxy signature, see [proxy signing](/http/signing#2-proxy-signing). + + +Request Weight: **1** Action Weight: **1** + + +## OpenAPI + +````yaml /api-spec/perps-openapi.json patch /v1/trade/leverage +openapi: 3.0.3 +info: + title: Polymarket Perps HTTP API + version: 1.0.0 + description: HTTP API for Polymarket perpetual trading system. + license: + name: Apache 2.0 + url: https://www.apache.org/licenses/LICENSE-2.0.html +servers: + - url: https://api.perpetuals.polymarket.com + description: Production Perps HTTP API +security: [] +paths: + /v1/trade/leverage: + patch: + summary: Update Leverage + description: > + Update leverage for an instrument. + + Requires proxy signature, see [proxy + signing](/http/signing#2-proxy-signing). + operationId: updateLeverage + requestBody: + description: Leverage request. + content: + application/json: + schema: + $ref: '#/components/schemas/LeverageRequest' + examples: + updateLeverage: + summary: Update leverage for one instrument + value: + op: + type: updateLeverage + args: + iid: 1 + lev: 5 + cross: false + sig: >- + 0x59ed57f6dce8d15aa01e774ef53d9957c84801fb34ec655f6a2ea344af8a58843095314730a3f1bd8f0f4560f6dc6f8de69d3f2d0a6f3365fc877f7f4845d40b1c + salt: 333333333 + ts: 1767000012000 + responses: + '200': + description: The instrument's effective leverage configuration after the update. + content: + application/json: + schema: + $ref: '#/components/schemas/LeverageResponse' + '400': + $ref: '#/components/responses/Error400Response' + '422': + $ref: '#/components/responses/Error422Response' + '429': + $ref: '#/components/responses/Error429Response' + '500': + $ref: '#/components/responses/Error500Response' + security: [] +components: + schemas: + LeverageRequest: + allOf: + - type: object + required: + - op + properties: + op: + $ref: '#/components/schemas/OpUpdateLeverage' + - $ref: '#/components/schemas/BaseOp' + LeverageResponse: + description: The instrument's effective leverage configuration after the update. + type: object + required: + - status + - instrument_id + - leverage + - cross + properties: + status: + type: string + enum: + - ok + instrument_id: + $ref: '#/components/schemas/iid' + leverage: + $ref: '#/components/schemas/lev' + cross: + $ref: '#/components/schemas/cross' + OpUpdateLeverage: + type: object + required: + - type + - args + properties: + type: + type: string + enum: + - updateLeverage + args: + type: object + required: + - iid + - lev + - cross + properties: + iid: + $ref: '#/components/schemas/iid' + lev: + $ref: '#/components/schemas/lev' + cross: + $ref: '#/components/schemas/cross' + BaseOp: + type: object + required: + - sig + - salt + - ts + properties: + sig: + $ref: '#/components/schemas/sig' + salt: + $ref: '#/components/schemas/salt' + ts: + $ref: '#/components/schemas/ts' + iid: + type: integer + description: Instrument ID + example: 1 + lev: + type: integer + description: Leverage + example: 10 + cross: + type: boolean + description: Whether to use cross margin mode + Error400: + title: Error400 + type: object + required: + - status + - error + properties: + status: + type: string + enum: + - err + error: + $ref: '#/components/schemas/error' + GenericRejected: + type: object + required: + - status + - error + properties: + status: + type: string + enum: + - err + error: + $ref: '#/components/schemas/error' + Error429: + title: Error429 + type: object + required: + - status + - error + properties: + status: + type: string + enum: + - err + error: + $ref: '#/components/schemas/error' + Error500: + title: Error500 + type: object + required: + - status + - error + properties: + status: + type: string + enum: + - err + error: + $ref: '#/components/schemas/error' + sig: + type: string + description: Signature in hex format + example: 0x1234567890... + salt: + type: integer + description: Salt + example: 1234567890 + ts: + type: integer + description: >- + Request timestamp. Unix milliseconds for most operations; Unix seconds + for withdrawals (must match the on-chain EIP-712 struct verified against + block.timestamp). + example: 1767225600000 + error: + type: string + description: >- + Error identifier. For domain rejections and transport errors + (`401`/`404`/`429`/`500`) this is a stable, machine-readable snake_case + identifier that is part of the API contract and safe to branch on, e.g. + `insufficient_margin`, `insufficient_balance`, `order_not_found`, + `reduce_only_invalid`, `unauthorized`, `not_found`. For `400` it is a + human-readable validation detail whose wording may change. See the Error + handling guide for the domain identifiers. (Post-only / Fill-or-Kill + outcomes are order statuses such as `post_only_rejected`, not + rejections.) + example: insufficient_margin + responses: + Error400Response: + description: | + Bad request — the request was malformed or failed validation (bad query + parameters, unparseable body, invalid signature, or a domain pre-check). + The `error` field is a human-readable validation detail. + content: + application/json: + schema: + $ref: '#/components/schemas/Error400' + Error422Response: + description: | + Unprocessable Entity — the request was well-formed but a domain rule + rejected it on its merits (insufficient balance, invalid leverage, + proxy already exists, …). The body is the discriminated rejection + (`status: err`) with the engine error identifier in `error`. + content: + application/json: + schema: + $ref: '#/components/schemas/GenericRejected' + Error429Response: + description: > + Too Many Requests. `error` distinguishes the limit that was hit: + + `ip_rate_limited` (per-IP token bucket), `action_rate_limited` + (per-account + + action rate), or `open_orders_limit` (resting open-order cap). + headers: + Retry-After: + description: > + Whole seconds to wait before retrying. Present only on token-bucket + + rate-limit rejections (`ip_rate_limited` and `action_rate_limited`); + a + + conservative estimate of when enough capacity will have refilled to + + admit the request. Absent on `open_orders_limit`, which is a + capacity + + limit, not a rate limit — waiting does not free order slots; cancel + + resting orders or wait for fills instead. + schema: + type: integer + example: 2 + content: + application/json: + schema: + $ref: '#/components/schemas/Error429' + Error500Response: + description: | + Internal server error. `error` is `internal_error`. + content: + application/json: + schema: + $ref: '#/components/schemas/Error500' + +```` \ No newline at end of file diff --git a/PolymarketDocumentation-main/docs/api-reference/withdraw.md b/PolymarketDocumentation-main/docs/api-reference/withdraw.md new file mode 100644 index 00000000..a0cda591 --- /dev/null +++ b/PolymarketDocumentation-main/docs/api-reference/withdraw.md @@ -0,0 +1,318 @@ +> ## Documentation Index +> Fetch the complete documentation index at: https://docs.polymarket.com/llms.txt +> Use this file to discover all available pages before exploring further. + +# Withdraw + +> Submit a signed withdrawal request. +Requires EOA signature, see [EOA signing](/http/signing#1-eoa-signing). + +The `amount` field is the raw token amount including decimals (e.g. `"100000000"` for 100 USDC). +This must match the `uint256 amount` value used in the EIP-712 `Withdraw` signature. + +The `ts` field is Unix seconds (not milliseconds) because the on-chain contract validates it +against `block.timestamp`. It must also match the `uint64 ts` in the signed EIP-712 struct. + + +Request Weight: **1** + + +## OpenAPI + +````yaml /api-spec/perps-openapi.json post /v1/account/withdraw +openapi: 3.0.3 +info: + title: Polymarket Perps HTTP API + version: 1.0.0 + description: HTTP API for Polymarket perpetual trading system. + license: + name: Apache 2.0 + url: https://www.apache.org/licenses/LICENSE-2.0.html +servers: + - url: https://api.perpetuals.polymarket.com + description: Production Perps HTTP API +security: [] +paths: + /v1/account/withdraw: + post: + summary: Withdraw + description: > + Submit a signed withdrawal request. + + Requires EOA signature, see [EOA signing](/http/signing#1-eoa-signing). + + + The `amount` field is the raw token amount including decimals (e.g. + `"100000000"` for 100 USDC). + + This must match the `uint256 amount` value used in the EIP-712 + `Withdraw` signature. + + + The `ts` field is Unix seconds (not milliseconds) because the on-chain + contract validates it + + against `block.timestamp`. It must also match the `uint64 ts` in the + signed EIP-712 struct. + operationId: withdraw + requestBody: + description: Withdraw request. + content: + application/json: + schema: + $ref: '#/components/schemas/WithdrawRequest' + examples: + withdraw: + summary: Withdraw 100 USDC + value: + op: + type: withdraw + args: + account: '0xf39Fd6e51aad88F6F4ce6aB8827279cffFb92266' + token: '0xaf88d065e77c8cc2239327c5edb3a432268e5831' + amount: '100000000' + to: '0x70997970C51812dc3A010C7d01b50e0d17dc79C8' + sig: >- + 0x5a6b7c8d9e0f1a2b3c4d5e6f7a8b9c0d1e2f3a4b5c6d7e8f9a0b1c2d3e4f5a6b7c8d9e0f1a2b3c4d5e6f7a8b9c0d1e2f3a4b5c6d7e8f9a0b1c2d3e4f5a1c + salt: 555555555 + ts: 1767000014 + responses: + '200': + description: The accepted withdrawal, carrying its `withdraw_id`. + content: + application/json: + schema: + $ref: '#/components/schemas/WithdrawAccepted' + '400': + $ref: '#/components/responses/Error400Response' + '422': + description: > + The withdrawal was rejected on its merits (e.g. insufficient + balance). + + The body carries `withdraw_id` and `error`. + content: + application/json: + schema: + $ref: '#/components/schemas/WithdrawRejected' + '429': + $ref: '#/components/responses/Error429Response' + '500': + $ref: '#/components/responses/Error500Response' + security: [] +components: + schemas: + WithdrawRequest: + allOf: + - type: object + required: + - op + properties: + op: + $ref: '#/components/schemas/OpWithdraw' + - $ref: '#/components/schemas/BaseOp' + WithdrawAccepted: + type: object + required: + - status + - withdraw_id + properties: + status: + type: string + enum: + - ok + withdraw_id: + $ref: '#/components/schemas/withdraw_id' + WithdrawRejected: + type: object + required: + - status + - withdraw_id + - error + properties: + status: + type: string + enum: + - err + withdraw_id: + $ref: '#/components/schemas/withdraw_id' + error: + $ref: '#/components/schemas/error' + OpWithdraw: + type: object + required: + - type + - args + properties: + type: + type: string + enum: + - withdraw + args: + type: object + required: + - account + - token + - amount + - to + properties: + account: + $ref: '#/components/schemas/account' + token: + $ref: '#/components/schemas/token' + amount: + $ref: '#/components/schemas/amount' + to: + $ref: '#/components/schemas/to' + BaseOp: + type: object + required: + - sig + - salt + - ts + properties: + sig: + $ref: '#/components/schemas/sig' + salt: + $ref: '#/components/schemas/salt' + ts: + $ref: '#/components/schemas/ts' + withdraw_id: + type: integer + description: Withdraw ID + Error400: + title: Error400 + type: object + required: + - status + - error + properties: + status: + type: string + enum: + - err + error: + $ref: '#/components/schemas/error' + error: + type: string + description: >- + Error identifier. For domain rejections and transport errors + (`401`/`404`/`429`/`500`) this is a stable, machine-readable snake_case + identifier that is part of the API contract and safe to branch on, e.g. + `insufficient_margin`, `insufficient_balance`, `order_not_found`, + `reduce_only_invalid`, `unauthorized`, `not_found`. For `400` it is a + human-readable validation detail whose wording may change. See the Error + handling guide for the domain identifiers. (Post-only / Fill-or-Kill + outcomes are order statuses such as `post_only_rejected`, not + rejections.) + example: insufficient_margin + Error429: + title: Error429 + type: object + required: + - status + - error + properties: + status: + type: string + enum: + - err + error: + $ref: '#/components/schemas/error' + Error500: + title: Error500 + type: object + required: + - status + - error + properties: + status: + type: string + enum: + - err + error: + $ref: '#/components/schemas/error' + account: + type: string + description: Account address in hex format + example: '0xf39Fd6e51aad88F6F4ce6aB8827279cffFb92266' + token: + type: string + description: Token contract address in hex format + example: '0xaf88d065e77c8cc2239327c5edb3a432268e5831' + amount: + type: string + description: >- + Raw token amount including decimals. For withdrawals this matches the + uint256 amount in the EIP-712 signature (e.g. "100000000" for 100 USDC + with 6 decimals). + example: '100000000' + to: + type: string + description: Destination address in hex format + example: '0x1234567890abcdef1234567890abcdef12345678' + sig: + type: string + description: Signature in hex format + example: 0x1234567890... + salt: + type: integer + description: Salt + example: 1234567890 + ts: + type: integer + description: >- + Request timestamp. Unix milliseconds for most operations; Unix seconds + for withdrawals (must match the on-chain EIP-712 struct verified against + block.timestamp). + example: 1767225600000 + responses: + Error400Response: + description: | + Bad request — the request was malformed or failed validation (bad query + parameters, unparseable body, invalid signature, or a domain pre-check). + The `error` field is a human-readable validation detail. + content: + application/json: + schema: + $ref: '#/components/schemas/Error400' + Error429Response: + description: > + Too Many Requests. `error` distinguishes the limit that was hit: + + `ip_rate_limited` (per-IP token bucket), `action_rate_limited` + (per-account + + action rate), or `open_orders_limit` (resting open-order cap). + headers: + Retry-After: + description: > + Whole seconds to wait before retrying. Present only on token-bucket + + rate-limit rejections (`ip_rate_limited` and `action_rate_limited`); + a + + conservative estimate of when enough capacity will have refilled to + + admit the request. Absent on `open_orders_limit`, which is a + capacity + + limit, not a rate limit — waiting does not free order slots; cancel + + resting orders or wait for fills instead. + schema: + type: integer + example: 2 + content: + application/json: + schema: + $ref: '#/components/schemas/Error429' + Error500Response: + description: | + Internal server error. `error` is `internal_error`. + content: + application/json: + schema: + $ref: '#/components/schemas/Error500' + +```` \ No newline at end of file diff --git a/PolymarketDocumentation-main/docs/api-reference/wss/market.md b/PolymarketDocumentation-main/docs/api-reference/wss/market.md new file mode 100644 index 00000000..6010a445 --- /dev/null +++ b/PolymarketDocumentation-main/docs/api-reference/wss/market.md @@ -0,0 +1,1328 @@ +> ## Documentation Index +> Fetch the complete documentation index at: https://docs.polymarket.com/llms.txt +> Use this file to discover all available pages before exploring further. + +# Market Channel + +> Public WebSocket for real-time orderbook, price, and market lifecycle updates. + + + +## AsyncAPI + +````yaml asyncapi.json market +id: market +title: Market Channel +description: >- + Public channel for real-time market data. Subscribe by providing asset IDs + (token IDs). Receive orderbook snapshots, price updates, trade executions, and + market lifecycle events. +servers: + - id: production + protocol: wss + host: ws-subscriptions-clob.polymarket.com + bindings: [] + variables: [] +address: /ws/market +parameters: [] +bindings: [] +operations: + - &ref_3 + id: subscribe + title: Subscribe + description: Send initial subscription request to receive market data + type: receive + messages: + - &ref_14 + id: subscriptionRequest + contentType: application/json + payload: + - name: Subscription Request + description: Initial subscription message sent after connecting + type: object + properties: + - name: assets_ids + type: array + description: Asset IDs (token IDs) to subscribe to + required: true + properties: + - name: item + type: string + required: false + - name: type + type: string + description: Must be 'market' + required: true + - name: initial_dump + type: boolean + description: >- + Whether to send an initial orderbook snapshot on subscribe. + Defaults to true. + required: false + - name: level + type: integer + description: Subscription level. Defaults to 2. + enumValues: + - 1 + - 2 + - 3 + required: false + - name: custom_feature_enabled + type: boolean + description: Enable best_bid_ask, new_market, and market_resolved events. + required: false + headers: [] + jsonPayloadSchema: + type: object + description: Initial subscription request payload + required: + - assets_ids + - type + properties: + assets_ids: + type: array + description: Asset IDs (token IDs) to subscribe to + items: + type: string + x-parser-schema-id: + x-parser-schema-id: + type: + type: string + const: market + description: Must be 'market' + x-parser-schema-id: + initial_dump: + type: boolean + description: >- + Whether to send an initial orderbook snapshot on subscribe. + Defaults to true. + default: true + x-parser-schema-id: + level: + type: integer + enum: + - 1 + - 2 + - 3 + description: Subscription level. Defaults to 2. + default: 2 + x-parser-schema-id: + custom_feature_enabled: + type: boolean + description: Enable best_bid_ask, new_market, and market_resolved events. + default: false + x-parser-schema-id: + x-parser-schema-id: SubscriptionRequest + title: Subscription Request + description: Initial subscription message sent after connecting + example: |- + { + "assets_ids": [ + "65818619657568813474341868652308942079804919287380422192892211131408793125422", + "52114319501245915516055106046884209969926127482827954674443846427813813222426" + ], + "type": "market" + } + bindings: [] + extensions: + - id: x-parser-unique-object-id + value: subscriptionRequest + bindings: [] + extensions: &ref_0 + - id: x-parser-unique-object-id + value: market + - &ref_4 + id: updateSubscription + title: Update Subscription + description: Dynamically subscribe or unsubscribe from assets without reconnecting + type: receive + messages: + - &ref_15 + id: subscriptionRequestUpdate + contentType: application/json + payload: + - name: Subscription Update + description: Subscribe or unsubscribe from assets without reconnecting + type: object + properties: + - name: operation + type: string + enumValues: + - subscribe + - unsubscribe + required: true + - name: assets_ids + type: array + required: true + properties: + - name: item + type: string + required: false + - name: level + type: integer + enumValues: + - 1 + - 2 + - 3 + required: false + - name: custom_feature_enabled + type: boolean + required: false + headers: [] + jsonPayloadSchema: + type: object + description: Dynamically update asset subscriptions + required: + - operation + - assets_ids + properties: + operation: + type: string + enum: + - subscribe + - unsubscribe + x-parser-schema-id: + assets_ids: + type: array + items: + type: string + x-parser-schema-id: + x-parser-schema-id: + level: + type: integer + enum: + - 1 + - 2 + - 3 + x-parser-schema-id: + custom_feature_enabled: + type: boolean + x-parser-schema-id: + x-parser-schema-id: SubscriptionRequestUpdate + title: Subscription Update + description: Subscribe or unsubscribe from assets without reconnecting + example: |- + { + "operation": "subscribe", + "assets_ids": [ + "71321045679252212594626385532706912750332728571942532289631379312455583992563" + ] + } + bindings: [] + extensions: + - id: x-parser-unique-object-id + value: subscriptionRequestUpdate + bindings: [] + extensions: *ref_0 + - &ref_5 + id: ping + title: Ping + description: Send PING every 10 seconds to keep the connection alive + type: receive + messages: + - &ref_16 + id: ping + contentType: text/plain + payload: + - type: string + const: PING + x-parser-schema-id: + name: Ping + description: Client heartbeat — send every 10 seconds + headers: [] + jsonPayloadSchema: + type: string + const: PING + x-parser-schema-id: + title: Ping + description: Client heartbeat — send every 10 seconds + example: '{}' + bindings: [] + extensions: + - id: x-parser-unique-object-id + value: ping + bindings: [] + extensions: *ref_0 + - &ref_6 + id: pong + title: Pong + description: Server responds to PING with PONG + type: send + messages: + - &ref_17 + id: pong + contentType: text/plain + payload: + - type: string + const: PONG + x-parser-schema-id: + name: Pong + description: Server heartbeat response + headers: [] + jsonPayloadSchema: + type: string + const: PONG + x-parser-schema-id: + title: Pong + description: Server heartbeat response + example: '{}' + bindings: [] + extensions: + - id: x-parser-unique-object-id + value: pong + bindings: [] + extensions: *ref_0 + - &ref_7 + id: receiveBook + title: Orderbook Snapshot + description: Full orderbook snapshot sent on subscribe or after a trade + type: send + messages: + - &ref_18 + id: book + contentType: application/json + payload: + - name: Orderbook Snapshot + description: Full aggregated orderbook for an asset + type: object + properties: + - name: event_type + type: string + description: book + required: true + - name: asset_id + type: string + description: Asset ID (token ID) + required: true + - name: market + type: string + description: Condition ID of the market + required: true + - name: bids + type: array + description: Aggregated buy orders by price level + required: true + properties: + - name: price + type: string + description: Price level (e.g., '0.50') + required: true + - name: size + type: string + description: Total size at this price level + required: true + - name: asks + type: array + description: Aggregated sell orders by price level + required: true + properties: + - name: price + type: string + description: Price level (e.g., '0.50') + required: true + - name: size + type: string + description: Total size at this price level + required: true + - name: timestamp + type: string + description: Unix timestamp in milliseconds + required: true + - name: hash + type: string + description: Hash of the orderbook content + required: true + headers: [] + jsonPayloadSchema: + type: object + description: Full orderbook snapshot + required: + - event_type + - asset_id + - market + - bids + - asks + - timestamp + - hash + properties: + event_type: + type: string + const: book + x-parser-schema-id: + asset_id: + type: string + description: Asset ID (token ID) + x-parser-schema-id: + market: + type: string + description: Condition ID of the market + x-parser-schema-id: + bids: + type: array + description: Aggregated buy orders by price level + items: &ref_1 + type: object + description: Aggregated order at a price level + required: + - price + - size + properties: + price: + type: string + description: Price level (e.g., '0.50') + x-parser-schema-id: + size: + type: string + description: Total size at this price level + x-parser-schema-id: + x-parser-schema-id: OrderSummary + x-parser-schema-id: + asks: + type: array + description: Aggregated sell orders by price level + items: *ref_1 + x-parser-schema-id: + timestamp: + type: string + description: Unix timestamp in milliseconds + x-parser-schema-id: + hash: + type: string + description: Hash of the orderbook content + x-parser-schema-id: + x-parser-schema-id: BookEvent + title: Orderbook Snapshot + description: Full aggregated orderbook for an asset + example: |- + { + "event_type": "book", + "asset_id": "65818619657568813474341868652308942079804919287380422192892211131408793125422", + "market": "0xbd31dc8a20211944f6b70f31557f1001557b59905b7738480ca09bd4532f84af", + "bids": [ + { + "price": "0.48", + "size": "30" + }, + { + "price": "0.49", + "size": "20" + }, + { + "price": "0.50", + "size": "15" + } + ], + "asks": [ + { + "price": "0.52", + "size": "25" + }, + { + "price": "0.53", + "size": "60" + }, + { + "price": "0.54", + "size": "10" + } + ], + "timestamp": "1757908892351", + "hash": "0xabc123..." + } + bindings: [] + extensions: + - id: x-parser-unique-object-id + value: book + bindings: [] + extensions: *ref_0 + - &ref_8 + id: receivePriceChange + title: Price Change + description: >- + Delta update to orderbook price levels when an order is placed or + cancelled + type: send + messages: + - &ref_19 + id: priceChange + contentType: application/json + payload: + - name: Price Change + description: Orderbook price level delta update + type: object + properties: + - name: event_type + type: string + description: price_change + required: true + - name: market + type: string + description: Condition ID of the market + required: true + - name: price_changes + type: array + required: true + properties: + - name: asset_id + type: string + required: true + - name: price + type: string + description: Price level affected + required: true + - name: size + type: string + description: New aggregate size (0 means level removed) + required: true + - name: side + type: string + enumValues: + - BUY + - SELL + required: true + - name: hash + type: string + description: Hash of the order that caused this change + required: true + - name: best_bid + type: string + required: false + - name: best_ask + type: string + required: false + - name: timestamp + type: string + description: Unix timestamp in milliseconds + required: true + headers: [] + jsonPayloadSchema: + type: object + description: One or more price level updates + required: + - event_type + - market + - price_changes + - timestamp + properties: + event_type: + type: string + const: price_change + x-parser-schema-id: + market: + type: string + description: Condition ID of the market + x-parser-schema-id: + price_changes: + type: array + items: + type: object + description: Individual price level change + required: + - asset_id + - price + - size + - side + - hash + properties: + asset_id: + type: string + x-parser-schema-id: + price: + type: string + description: Price level affected + x-parser-schema-id: + size: + type: string + description: New aggregate size (0 means level removed) + x-parser-schema-id: + side: + type: string + enum: + - BUY + - SELL + x-parser-schema-id: + hash: + type: string + description: Hash of the order that caused this change + x-parser-schema-id: + best_bid: + type: string + x-parser-schema-id: + best_ask: + type: string + x-parser-schema-id: + x-parser-schema-id: PriceChangeMessage + x-parser-schema-id: + timestamp: + type: string + description: Unix timestamp in milliseconds + x-parser-schema-id: + x-parser-schema-id: PriceChangeEvent + title: Price Change + description: Orderbook price level delta update + example: |- + { + "event_type": "price_change", + "market": "0x5f65177b394277fd294cd75650044e32ba009a95022d88a0c1d565897d72f8f1", + "price_changes": [ + { + "asset_id": "71321045679252212594626385532706912750332728571942532289631379312455583992563", + "price": "0.5", + "size": "200", + "side": "BUY", + "hash": "56621a121a47ed9333273e21c83b660cff37ae50", + "best_bid": "0.5", + "best_ask": "1" + } + ], + "timestamp": "1757908892351" + } + bindings: [] + extensions: + - id: x-parser-unique-object-id + value: priceChange + bindings: [] + extensions: *ref_0 + - &ref_9 + id: receiveLastTradePrice + title: Last Trade Price + description: Trade execution notification + type: send + messages: + - &ref_20 + id: lastTradePrice + contentType: application/json + payload: + - name: Last Trade Price + description: Trade execution event + type: object + properties: + - name: event_type + type: string + description: last_trade_price + required: true + - name: asset_id + type: string + required: true + - name: market + type: string + required: true + - name: price + type: string + description: Trade execution price + required: true + - name: size + type: string + description: Trade size + required: true + - name: fee_rate_bps + type: string + description: Fee rate in basis points + required: false + - name: side + type: string + description: From taker's perspective + enumValues: + - BUY + - SELL + required: true + - name: timestamp + type: string + description: Unix timestamp in milliseconds + required: true + - name: transaction_hash + type: string + required: false + headers: [] + jsonPayloadSchema: + type: object + description: Last trade price event + required: + - event_type + - asset_id + - market + - price + - size + - side + - timestamp + properties: + event_type: + type: string + const: last_trade_price + x-parser-schema-id: + asset_id: + type: string + x-parser-schema-id: + market: + type: string + x-parser-schema-id: + price: + type: string + description: Trade execution price + x-parser-schema-id: + size: + type: string + description: Trade size + x-parser-schema-id: + fee_rate_bps: + type: string + description: Fee rate in basis points + x-parser-schema-id: + side: + type: string + enum: + - BUY + - SELL + description: From taker's perspective + x-parser-schema-id: + timestamp: + type: string + description: Unix timestamp in milliseconds + x-parser-schema-id: + transaction_hash: + type: string + x-parser-schema-id: + x-parser-schema-id: LastTradePriceEvent + title: Last Trade Price + description: Trade execution event + example: |- + { + "event_type": "last_trade_price", + "asset_id": "114122071509644379678018727908709560226618148003371446110114509806601493071694", + "market": "0x6a67b9d828d53862160e470329ffea5246f338ecfffdf2cab45211ec578b0347", + "price": "0.456", + "size": "219.217767", + "fee_rate_bps": "0", + "side": "BUY", + "timestamp": "1750428146322", + "transaction_hash": "0xeeefffggghhh" + } + bindings: [] + extensions: + - id: x-parser-unique-object-id + value: lastTradePrice + bindings: [] + extensions: *ref_0 + - &ref_10 + id: receiveTickSizeChange + title: Tick Size Change + description: Market tick size update when price approaches limits + type: send + messages: + - &ref_21 + id: tickSizeChange + contentType: application/json + payload: + - name: Tick Size Change + description: Market tick size update event + type: object + properties: + - name: event_type + type: string + description: tick_size_change + required: true + - name: asset_id + type: string + required: true + - name: market + type: string + required: true + - name: old_tick_size + type: string + required: true + - name: new_tick_size + type: string + required: true + - name: timestamp + type: string + required: true + headers: [] + jsonPayloadSchema: + type: object + description: Tick size change event + required: + - event_type + - asset_id + - market + - old_tick_size + - new_tick_size + - timestamp + properties: + event_type: + type: string + const: tick_size_change + x-parser-schema-id: + asset_id: + type: string + x-parser-schema-id: + market: + type: string + x-parser-schema-id: + old_tick_size: + type: string + x-parser-schema-id: + new_tick_size: + type: string + x-parser-schema-id: + timestamp: + type: string + x-parser-schema-id: + x-parser-schema-id: TickSizeChangeEvent + title: Tick Size Change + description: Market tick size update event + example: |- + { + "event_type": "tick_size_change", + "asset_id": "65818619657568813474341868652308942079804919287380422192892211131408793125422", + "market": "0xbd31dc8a20211944f6b70f31557f1001557b59905b7738480ca09bd4532f84af", + "old_tick_size": "0.01", + "new_tick_size": "0.001", + "timestamp": "1757908892351" + } + bindings: [] + extensions: + - id: x-parser-unique-object-id + value: tickSizeChange + bindings: [] + extensions: *ref_0 + - &ref_11 + id: receiveBestBidAsk + title: Best Bid/Ask + description: 'Best bid and ask update (requires custom_feature_enabled: true)' + type: send + messages: + - &ref_22 + id: bestBidAsk + contentType: application/json + payload: + - name: Best Bid/Ask + description: >- + Best bid and ask price update — requires custom_feature_enabled: + true + type: object + properties: + - name: event_type + type: string + description: best_bid_ask + required: true + - name: asset_id + type: string + required: true + - name: market + type: string + required: true + - name: best_bid + type: string + required: true + - name: best_ask + type: string + required: true + - name: spread + type: string + required: true + - name: timestamp + type: string + required: true + headers: [] + jsonPayloadSchema: + type: object + description: Best bid/ask event — requires custom_feature_enabled + required: + - event_type + - asset_id + - market + - best_bid + - best_ask + - spread + - timestamp + properties: + event_type: + type: string + const: best_bid_ask + x-parser-schema-id: + asset_id: + type: string + x-parser-schema-id: + market: + type: string + x-parser-schema-id: + best_bid: + type: string + x-parser-schema-id: + best_ask: + type: string + x-parser-schema-id: + spread: + type: string + x-parser-schema-id: + timestamp: + type: string + x-parser-schema-id: + x-parser-schema-id: BestBidAskEvent + title: Best Bid/Ask + description: 'Best bid and ask price update — requires custom_feature_enabled: true' + example: |- + { + "event_type": "best_bid_ask", + "market": "0x0005c0d312de0be897668695bae9f32b624b4a1ae8b140c49f08447fcc74f442", + "asset_id": "85354956062430465315924116860125388538595433819574542752031640332592237464430", + "best_bid": "0.73", + "best_ask": "0.77", + "spread": "0.04", + "timestamp": "1766789469958" + } + bindings: [] + extensions: + - id: x-parser-unique-object-id + value: bestBidAsk + bindings: [] + extensions: *ref_0 + - &ref_12 + id: receiveNewMarket + title: New Market + description: 'New market creation event (requires custom_feature_enabled: true)' + type: send + messages: + - &ref_23 + id: newMarket + contentType: application/json + payload: + - name: New Market + description: 'New market creation event — requires custom_feature_enabled: true' + type: object + properties: + - name: event_type + type: string + description: new_market + required: true + - name: id + type: string + description: Market ID + required: true + - name: question + type: string + required: true + - name: market + type: string + description: Condition ID + required: true + - name: slug + type: string + required: true + - name: description + type: string + required: false + - name: assets_ids + type: array + required: true + properties: + - name: item + type: string + required: false + - name: outcomes + type: array + required: true + properties: + - name: item + type: string + required: false + - name: event_message + type: object + description: Parent event metadata for grouped markets + required: false + properties: + - name: id + type: string + required: false + - name: ticker + type: string + required: false + - name: slug + type: string + required: false + - name: title + type: string + required: false + - name: description + type: string + required: false + - name: timestamp + type: string + required: true + - name: tags + type: array + required: false + properties: + - name: item + type: string + required: false + - name: condition_id + type: string + description: Condition ID + required: false + - name: active + type: boolean + description: Whether the market is active + required: false + - name: clob_token_ids + type: array + description: CLOB token IDs for the market + required: false + properties: + - name: item + type: string + required: false + - name: sports_market_type + type: string + description: Sports market type such as spread or moneyline + required: false + - name: line + type: string + description: Betting line value, or an empty string when not applicable + required: false + - name: game_start_time + type: string + description: >- + Game start time in RFC3339 format, or an empty string when not + applicable + required: false + - name: order_price_min_tick_size + type: string + description: Minimum tick size for order prices + required: false + - name: group_item_title + type: string + description: Display title for the group item + required: false + headers: [] + jsonPayloadSchema: + type: object + description: New market creation event — requires custom_feature_enabled + required: + - event_type + - id + - question + - market + - slug + - assets_ids + - outcomes + - timestamp + properties: + event_type: + type: string + const: new_market + x-parser-schema-id: + id: + type: string + description: Market ID + x-parser-schema-id: + question: + type: string + x-parser-schema-id: + market: + type: string + description: Condition ID + x-parser-schema-id: + slug: + type: string + x-parser-schema-id: + description: + type: string + x-parser-schema-id: + assets_ids: + type: array + items: + type: string + x-parser-schema-id: + x-parser-schema-id: + outcomes: + type: array + items: + type: string + x-parser-schema-id: + x-parser-schema-id: + event_message: &ref_2 + type: object + description: Parent event metadata for grouped markets + properties: + id: + type: string + x-parser-schema-id: + ticker: + type: string + x-parser-schema-id: + slug: + type: string + x-parser-schema-id: + title: + type: string + x-parser-schema-id: + description: + type: string + x-parser-schema-id: + x-parser-schema-id: EventMessage + timestamp: + type: string + x-parser-schema-id: + tags: + type: array + items: + type: string + x-parser-schema-id: + x-parser-schema-id: + condition_id: + type: string + description: Condition ID + x-parser-schema-id: + active: + type: boolean + description: Whether the market is active + x-parser-schema-id: + clob_token_ids: + type: array + description: CLOB token IDs for the market + items: + type: string + x-parser-schema-id: + x-parser-schema-id: + sports_market_type: + type: string + description: Sports market type such as spread or moneyline + x-parser-schema-id: + line: + type: string + description: Betting line value, or an empty string when not applicable + x-parser-schema-id: + game_start_time: + type: string + description: >- + Game start time in RFC3339 format, or an empty string when not + applicable + x-parser-schema-id: + order_price_min_tick_size: + type: string + description: Minimum tick size for order prices + x-parser-schema-id: + group_item_title: + type: string + description: Display title for the group item + x-parser-schema-id: + x-parser-schema-id: NewMarketEvent + title: New Market + description: 'New market creation event — requires custom_feature_enabled: true' + example: |- + { + "event_type": "new_market", + "id": "1031769", + "question": "Will NVIDIA (NVDA) close above $240 end of January?", + "market": "0x311d0c4b6671ab54af4970c06fcf58662516f5168997bdda209ec3db5aa6b0c1", + "slug": "nvda-above-240-on-january-30-2026", + "description": "This market will resolve to \"Yes\" if the official closing price for NVIDIA (NVDA) on the final trading day of January 2026 is higher than the listed price. Otherwise, this market will resolve to \"No\".", + "assets_ids": [ + "76043073756653678226373981964075571318267289248134717369284518995922789326425", + "31690934263385727664202099278545688007799199447969475608906331829650099442770" + ], + "outcomes": [ + "Yes", + "No" + ], + "event_message": { + "id": "125819", + "ticker": "nvda-above-in-january-2026", + "slug": "nvda-above-in-january-2026", + "title": "Will NVIDIA (NVDA) close above ___ end of January?", + "description": "This market will resolve to \"Yes\" if the official closing price for NVIDIA (NVDA) on the final trading day of January 2026 is higher than the listed price. Otherwise, this market will resolve to \"No\"." + }, + "timestamp": "1766790415550", + "tags": [ + "stocks" + ], + "condition_id": "0x311d0c4b6671ab54af4970c06fcf58662516f5168997bdda209ec3db5aa6b0c1", + "active": true, + "clob_token_ids": [ + "76043073756653678226373981964075571318267289248134717369284518995922789326425", + "31690934263385727664202099278545688007799199447969475608906331829650099442770" + ], + "sports_market_type": "", + "line": "", + "game_start_time": "", + "order_price_min_tick_size": "0.01", + "group_item_title": "NVDA above $240" + } + bindings: [] + extensions: + - id: x-parser-unique-object-id + value: newMarket + bindings: [] + extensions: *ref_0 + - &ref_13 + id: receiveMarketResolved + title: Market Resolved + description: 'Market resolution event (requires custom_feature_enabled: true)' + type: send + messages: + - &ref_24 + id: marketResolved + contentType: application/json + payload: + - name: Market Resolved + description: 'Market resolution event — requires custom_feature_enabled: true' + type: object + properties: + - name: event_type + type: string + description: market_resolved + required: true + - name: id + type: string + required: true + - name: market + type: string + description: Condition ID + required: true + - name: assets_ids + type: array + required: true + properties: + - name: item + type: string + required: false + - name: winning_asset_id + type: string + required: true + - name: winning_outcome + type: string + required: true + - name: event_message + type: object + description: Parent event metadata for grouped markets + required: false + properties: + - name: id + type: string + required: false + - name: ticker + type: string + required: false + - name: slug + type: string + required: false + - name: title + type: string + required: false + - name: description + type: string + required: false + - name: timestamp + type: string + required: true + - name: tags + type: array + required: false + properties: + - name: item + type: string + required: false + headers: [] + jsonPayloadSchema: + type: object + description: Market resolution event — requires custom_feature_enabled + required: + - event_type + - id + - market + - assets_ids + - winning_asset_id + - winning_outcome + - timestamp + properties: + event_type: + type: string + const: market_resolved + x-parser-schema-id: + id: + type: string + x-parser-schema-id: + market: + type: string + description: Condition ID + x-parser-schema-id: + assets_ids: + type: array + items: + type: string + x-parser-schema-id: + x-parser-schema-id: + winning_asset_id: + type: string + x-parser-schema-id: + winning_outcome: + type: string + x-parser-schema-id: + event_message: *ref_2 + timestamp: + type: string + x-parser-schema-id: + tags: + type: array + items: + type: string + x-parser-schema-id: + x-parser-schema-id: + x-parser-schema-id: MarketResolvedEvent + title: Market Resolved + description: 'Market resolution event — requires custom_feature_enabled: true' + example: |- + { + "event_type": "market_resolved", + "id": "1031769", + "market": "0x311d0c4b6671ab54af4970c06fcf58662516f5168997bdda209ec3db5aa6b0c1", + "assets_ids": [ + "76043073756653678226373981964075571318267289248134717369284518995922789326425", + "31690934263385727664202099278545688007799199447969475608906331829650099442770" + ], + "winning_asset_id": "76043073756653678226373981964075571318267289248134717369284518995922789326425", + "winning_outcome": "Yes", + "timestamp": "1766790415550", + "tags": [ + "stocks" + ] + } + bindings: [] + extensions: + - id: x-parser-unique-object-id + value: marketResolved + bindings: [] + extensions: *ref_0 +sendOperations: + - *ref_3 + - *ref_4 + - *ref_5 +receiveOperations: + - *ref_6 + - *ref_7 + - *ref_8 + - *ref_9 + - *ref_10 + - *ref_11 + - *ref_12 + - *ref_13 +sendMessages: + - *ref_14 + - *ref_15 + - *ref_16 +receiveMessages: + - *ref_17 + - *ref_18 + - *ref_19 + - *ref_20 + - *ref_21 + - *ref_22 + - *ref_23 + - *ref_24 +extensions: + - id: x-parser-unique-object-id + value: market +securitySchemes: [] + +```` \ No newline at end of file diff --git a/PolymarketDocumentation-main/docs/api-reference/wss/perps-auth.md b/PolymarketDocumentation-main/docs/api-reference/wss/perps-auth.md new file mode 100644 index 00000000..cdedcd2f --- /dev/null +++ b/PolymarketDocumentation-main/docs/api-reference/wss/perps-auth.md @@ -0,0 +1,274 @@ +> ## Documentation Index +> Fetch the complete documentation index at: https://docs.polymarket.com/llms.txt +> Use this file to discover all available pages before exploring further. + +# Auth + +> Perps WebSocket authentication. + + + +## AsyncAPI + +````yaml asyncapi-perps.json auth +id: auth +title: Auth +description: Authentication to access private channels. +servers: + - id: production + protocol: wss + host: ws.perpetuals.polymarket.com + bindings: [] + variables: [] +address: /v1/ws +parameters: [] +bindings: [] +operations: + - &ref_1 + id: AuthSend + title: Auth send + description: Authenticate connection + type: receive + messages: + - &ref_3 + id: Request + contentType: application/json + payload: + - name: Auth + description: Authenticate this WebSocket connection for private channels + type: object + properties: + - name: id + type: integer + description: Correlation ID for request-response matching + required: false + - name: req + type: string + description: Request type + enumValues: + - post + - sub + - unsub + required: true + - name: op + type: object + required: true + properties: + - name: type + type: string + enumValues: + - auth + required: true + - name: args + type: object + required: true + properties: + - name: proxy + type: string + description: Proxy address in hex format + required: true + - name: secret + type: string + description: API secret + required: true + headers: [] + jsonPayloadSchema: + type: object + title: Base Request + properties: + id: + type: integer + description: Correlation ID for request-response matching + x-parser-schema-id: + req: + type: string + description: Request type + enum: + - post + - sub + - unsub + x-parser-schema-id: + op: + type: object + required: + - type + - args + properties: + type: + type: string + enum: + - auth + x-parser-schema-id: + args: + type: object + required: + - proxy + - secret + properties: + proxy: + type: string + description: Proxy address in hex format + example: '0x70997970C51812dc3A010C7d01b50e0d17dc79C8' + x-parser-schema-id: + secret: + type: string + description: API secret + example: wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY + x-parser-schema-id: + x-parser-schema-id: + x-parser-schema-id: + required: + - req + - op + x-parser-schema-id: + title: Auth + description: Authenticate this WebSocket connection for private channels + example: |- + { + "req": "post", + "op": { + "type": "auth", + "args": { + "proxy": "0x70997970C51812dc3A010C7d01b50e0d17dc79C8", + "secret": "wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY" + } + } + } + bindings: [] + extensions: + - id: x-parser-unique-object-id + value: Request + bindings: [] + extensions: &ref_0 + - id: x-parser-unique-object-id + value: auth + - &ref_2 + id: AuthReceive + title: Auth receive + description: Auth response + type: send + messages: + - &ref_4 + id: Response + contentType: application/json + payload: + - name: Auth Response + description: Authentication result + type: object + properties: + - name: id + type: integer + description: Correlation ID for request-response matching + required: false + - name: data + type: object + required: true + properties: + - name: status + type: string + enumValues: + - ok + required: true + - name: status + type: string + enumValues: + - err + required: true + - name: error + type: string + description: >- + Error identifier. For domain rejections and transport + errors (`401`/`404`/`429`/`500`) this is a stable, + machine-readable snake_case identifier that is part of the + API contract and safe to branch on, e.g. + `insufficient_margin`, `insufficient_balance`, + `order_not_found`, `reduce_only_invalid`, `unauthorized`, + `not_found`. For `400` it is a human-readable validation + detail whose wording may change. See the Error handling + guide for the domain identifiers. (Post-only / + Fill-or-Kill outcomes are order statuses such as + `post_only_rejected`, not rejections.) + required: true + headers: [] + jsonPayloadSchema: + type: object + title: Base Response + properties: + id: + type: integer + description: Correlation ID for request-response matching + x-parser-schema-id: + data: + oneOf: + - type: object + required: + - status + properties: + status: + type: string + enum: + - ok + x-parser-schema-id: + x-parser-schema-id: + - type: object + required: + - status + - error + properties: + status: + type: string + enum: + - err + x-parser-schema-id: + error: + type: string + description: >- + Error identifier. For domain rejections and transport + errors (`401`/`404`/`429`/`500`) this is a stable, + machine-readable snake_case identifier that is part of + the API contract and safe to branch on, e.g. + `insufficient_margin`, `insufficient_balance`, + `order_not_found`, `reduce_only_invalid`, + `unauthorized`, `not_found`. For `400` it is a + human-readable validation detail whose wording may + change. See the Error handling guide for the domain + identifiers. (Post-only / Fill-or-Kill outcomes are + order statuses such as `post_only_rejected`, not + rejections.) + example: insufficient_margin + x-parser-schema-id: + x-parser-schema-id: + x-parser-schema-id: + required: + - data + x-parser-schema-id: + title: Auth Response + description: Authentication result + example: |- + { + "id": 123, + "data": { + "status": "", + "error": "" + } + } + bindings: [] + extensions: + - id: x-parser-unique-object-id + value: Response + bindings: [] + extensions: *ref_0 +sendOperations: + - *ref_1 +receiveOperations: + - *ref_2 +sendMessages: + - *ref_3 +receiveMessages: + - *ref_4 +extensions: + - id: x-parser-unique-object-id + value: auth +securitySchemes: [] + +```` \ No newline at end of file diff --git a/PolymarketDocumentation-main/docs/api-reference/wss/perps-auto-cancel.md b/PolymarketDocumentation-main/docs/api-reference/wss/perps-auto-cancel.md new file mode 100644 index 00000000..a380148c --- /dev/null +++ b/PolymarketDocumentation-main/docs/api-reference/wss/perps-auto-cancel.md @@ -0,0 +1,305 @@ +> ## Documentation Index +> Fetch the complete documentation index at: https://docs.polymarket.com/llms.txt +> Use this file to discover all available pages before exploring further. + +# Auto Cancel + +> Perps WebSocket dead man's switch updates. + + + +## AsyncAPI + +````yaml asyncapi-perps.json autoCancel +id: autoCancel +title: Auto-Cancel +description: | + Arm or clear the per-account auto-cancel schedule. + Requires proxy signature, see [proxy signing](/http/signing#2-proxy-signing). + + Action Weight: **10** +servers: + - id: production + protocol: wss + host: ws.perpetuals.polymarket.com + bindings: [] + variables: [] +address: /v1/ws +parameters: [] +bindings: [] +operations: + - &ref_1 + id: AutoCancelSend + title: Auto cancel send + description: Set or clear auto-cancel + type: receive + messages: + - &ref_3 + id: Request + contentType: application/json + payload: + - name: Auto-Cancel Request + description: Client submits a signed auto-cancel request + type: object + properties: + - name: id + type: integer + description: Correlation ID for request-response matching + required: false + - name: req + type: string + description: Request type + enumValues: + - post + - sub + - unsub + required: true + - name: op + type: object + required: true + properties: + - name: type + type: string + enumValues: + - autoCancel + required: true + - name: args + type: object + required: true + properties: + - name: time + type: integer + description: Timestamp in milliseconds + required: true + - name: sig + type: string + description: Signature in hex format + required: true + - name: salt + type: integer + description: Salt + required: true + - name: ts + type: integer + description: >- + Request timestamp. Unix milliseconds for most operations; Unix + seconds for withdrawals (must match the on-chain EIP-712 + struct verified against block.timestamp). + required: true + headers: [] + jsonPayloadSchema: + type: object + title: Base Request + properties: + id: + type: integer + description: Correlation ID for request-response matching + x-parser-schema-id: + req: + type: string + description: Request type + enum: + - post + - sub + - unsub + x-parser-schema-id: + op: + type: object + required: + - type + - args + properties: + type: + type: string + enum: + - autoCancel + x-parser-schema-id: + args: + type: object + required: + - time + properties: + time: + type: integer + description: Timestamp in milliseconds + example: 1767225600000 + x-parser-schema-id: + x-parser-schema-id: + x-parser-schema-id: + sig: + type: string + description: Signature in hex format + example: 0x1234567890... + x-parser-schema-id: + salt: + type: integer + description: Salt + example: 1234567890 + x-parser-schema-id: + ts: + type: integer + description: >- + Request timestamp. Unix milliseconds for most operations; Unix + seconds for withdrawals (must match the on-chain EIP-712 struct + verified against block.timestamp). + example: 1767225600000 + x-parser-schema-id: + required: + - req + - op + - sig + - salt + - ts + x-parser-schema-id: + title: Auto-Cancel Request + description: Client submits a signed auto-cancel request + example: |- + { + "req": "post", + "op": { + "type": "autoCancel", + "args": { + "time": 1767225600000 + } + }, + "sig": "0x1234567890...", + "salt": 1234567890, + "ts": 1767225600000 + } + bindings: [] + extensions: + - id: x-parser-unique-object-id + value: Request + bindings: [] + extensions: &ref_0 + - id: x-parser-unique-object-id + value: autoCancel + - &ref_2 + id: AutoCancelReceive + title: Auto cancel receive + description: Auto-cancel response + type: send + messages: + - &ref_4 + id: Response + contentType: application/json + payload: + - name: Auto-Cancel Response + description: Server responds with auto-cancel result + type: object + properties: + - name: id + type: integer + description: Correlation ID for request-response matching + required: false + - name: data + type: object + required: true + properties: + - name: status + type: string + enumValues: + - ok + required: true + - name: status + type: string + enumValues: + - err + required: true + - name: error + type: string + description: >- + Error identifier. For domain rejections and transport + errors (`401`/`404`/`429`/`500`) this is a stable, + machine-readable snake_case identifier that is part of the + API contract and safe to branch on, e.g. + `insufficient_margin`, `insufficient_balance`, + `order_not_found`, `reduce_only_invalid`, `unauthorized`, + `not_found`. For `400` it is a human-readable validation + detail whose wording may change. See the Error handling + guide for the domain identifiers. (Post-only / + Fill-or-Kill outcomes are order statuses such as + `post_only_rejected`, not rejections.) + required: true + headers: [] + jsonPayloadSchema: + type: object + title: Base Response + properties: + id: + type: integer + description: Correlation ID for request-response matching + x-parser-schema-id: + data: + oneOf: + - type: object + required: + - status + properties: + status: + type: string + enum: + - ok + x-parser-schema-id: + x-parser-schema-id: + - type: object + required: + - status + - error + properties: + status: + type: string + enum: + - err + x-parser-schema-id: + error: + type: string + description: >- + Error identifier. For domain rejections and transport + errors (`401`/`404`/`429`/`500`) this is a stable, + machine-readable snake_case identifier that is part of + the API contract and safe to branch on, e.g. + `insufficient_margin`, `insufficient_balance`, + `order_not_found`, `reduce_only_invalid`, + `unauthorized`, `not_found`. For `400` it is a + human-readable validation detail whose wording may + change. See the Error handling guide for the domain + identifiers. (Post-only / Fill-or-Kill outcomes are + order statuses such as `post_only_rejected`, not + rejections.) + example: insufficient_margin + x-parser-schema-id: + x-parser-schema-id: + x-parser-schema-id: + required: + - data + x-parser-schema-id: + title: Auto-Cancel Response + description: Server responds with auto-cancel result + example: |- + { + "id": 5, + "data": { + "status": "ok" + } + } + bindings: [] + extensions: + - id: x-parser-unique-object-id + value: Response + bindings: [] + extensions: *ref_0 +sendOperations: + - *ref_1 +receiveOperations: + - *ref_2 +sendMessages: + - *ref_3 +receiveMessages: + - *ref_4 +extensions: + - id: x-parser-unique-object-id + value: autoCancel +securitySchemes: [] + +```` \ No newline at end of file diff --git a/PolymarketDocumentation-main/docs/api-reference/wss/perps-balances.md b/PolymarketDocumentation-main/docs/api-reference/wss/perps-balances.md new file mode 100644 index 00000000..95b5a91f --- /dev/null +++ b/PolymarketDocumentation-main/docs/api-reference/wss/perps-balances.md @@ -0,0 +1,586 @@ +> ## Documentation Index +> Fetch the complete documentation index at: https://docs.polymarket.com/llms.txt +> Use this file to discover all available pages before exploring further. + +# Balances + +> Perps WebSocket private balance updates. + + + +## AsyncAPI + +````yaml asyncapi-perps.json balances +id: balances +title: Balances +description: >- + Real-time balance updates. Pushed every 5 seconds. Requires authentication, + see [Auth](/ws/auth). +servers: + - id: production + protocol: wss + host: ws.perpetuals.polymarket.com + bindings: [] + variables: [] +address: /v1/ws +parameters: [] +bindings: [] +operations: + - &ref_1 + id: BalancesSubscribe + title: Balances subscribe + description: Subscribe to balances + type: receive + messages: + - &ref_6 + id: SubscribeRequest + contentType: application/json + payload: + - name: Subscribe + description: Subscribe to private balance updates (requires prior auth) + type: object + properties: + - name: id + type: integer + description: Correlation ID for request-response matching + required: false + - name: req + type: string + description: Request type + enumValues: + - post + - sub + - unsub + required: true + - name: chs + type: array + description: 'Balances private channel: "balances"' + required: true + properties: + - name: item + type: string + enumValues: + - balances + required: false + headers: [] + jsonPayloadSchema: + type: object + title: Base Request + properties: + id: + type: integer + description: Correlation ID for request-response matching + x-parser-schema-id: + req: + type: string + description: Request type + enum: + - post + - sub + - unsub + x-parser-schema-id: + chs: + type: array + description: 'Balances private channel: "balances"' + items: + type: string + enum: + - balances + x-parser-schema-id: + example: + - balances + x-parser-schema-id: + required: + - req + - chs + x-parser-schema-id: + title: Subscribe + description: Subscribe to private balance updates (requires prior auth) + example: |- + { + "req": "sub", + "chs": [ + "balances" + ] + } + bindings: [] + extensions: + - id: x-parser-unique-object-id + value: SubscribeRequest + bindings: [] + extensions: &ref_0 + - id: x-parser-unique-object-id + value: balances + - &ref_3 + id: BalancesSubscribeResponse + title: Balances subscribe response + description: Balances subscribe response + type: send + messages: + - &ref_8 + id: SubscribeResponse + contentType: application/json + payload: + - name: Subscribe Response + description: Response to balances subscribe request + type: object + properties: + - name: id + type: integer + description: Correlation ID for request-response matching + required: false + - name: data + type: array + title: Subscribe Response + required: true + properties: + - name: item + type: object + required: false + properties: + - name: status + type: string + enumValues: + - ok + required: true + - name: status + type: string + enumValues: + - err + required: true + - name: error + type: string + description: >- + Error identifier. For domain rejections and transport + errors (`401`/`404`/`429`/`500`) this is a stable, + machine-readable snake_case identifier that is part of + the API contract and safe to branch on, e.g. + `insufficient_margin`, `insufficient_balance`, + `order_not_found`, `reduce_only_invalid`, + `unauthorized`, `not_found`. For `400` it is a + human-readable validation detail whose wording may + change. See the Error handling guide for the domain + identifiers. (Post-only / Fill-or-Kill outcomes are + order statuses such as `post_only_rejected`, not + rejections.) + required: true + headers: [] + jsonPayloadSchema: + type: object + title: Base Response + properties: + id: + type: integer + description: Correlation ID for request-response matching + x-parser-schema-id: + data: + title: Subscribe Response + type: array + items: + oneOf: + - type: object + required: + - status + properties: + status: + type: string + enum: + - ok + x-parser-schema-id: + x-parser-schema-id: + - type: object + required: + - status + - error + properties: + status: + type: string + enum: + - err + x-parser-schema-id: + error: + type: string + description: >- + Error identifier. For domain rejections and transport + errors (`401`/`404`/`429`/`500`) this is a stable, + machine-readable snake_case identifier that is part of + the API contract and safe to branch on, e.g. + `insufficient_margin`, `insufficient_balance`, + `order_not_found`, `reduce_only_invalid`, + `unauthorized`, `not_found`. For `400` it is a + human-readable validation detail whose wording may + change. See the Error handling guide for the domain + identifiers. (Post-only / Fill-or-Kill outcomes are + order statuses such as `post_only_rejected`, not + rejections.) + example: insufficient_margin + x-parser-schema-id: + x-parser-schema-id: + x-parser-schema-id: + x-parser-schema-id: + required: + - data + x-parser-schema-id: + title: Subscribe Response + description: Response to balances subscribe request + example: |- + { + "data": [] + } + bindings: [] + extensions: + - id: x-parser-unique-object-id + value: SubscribeResponse + bindings: [] + extensions: *ref_0 + - &ref_2 + id: BalancesUnsubscribe + title: Balances unsubscribe + description: Unsubscribe from balances + type: receive + messages: + - &ref_7 + id: UnsubscribeRequest + contentType: application/json + payload: + - name: Unsubscribe + description: Unsubscribe from private balance updates + type: object + properties: + - name: id + type: integer + description: Correlation ID for request-response matching + required: false + - name: req + type: string + description: Request type + enumValues: + - post + - sub + - unsub + required: true + - name: chs + type: array + description: 'Balances private channel: "balances"' + required: true + properties: + - name: item + type: string + enumValues: + - balances + required: false + headers: [] + jsonPayloadSchema: + type: object + title: Base Request + properties: + id: + type: integer + description: Correlation ID for request-response matching + x-parser-schema-id: + req: + type: string + description: Request type + enum: + - post + - sub + - unsub + x-parser-schema-id: + chs: + type: array + description: 'Balances private channel: "balances"' + items: + type: string + enum: + - balances + x-parser-schema-id: + example: + - balances + x-parser-schema-id: + required: + - req + - chs + x-parser-schema-id: + title: Unsubscribe + description: Unsubscribe from private balance updates + example: |- + { + "req": "unsub", + "chs": [ + "balances" + ] + } + bindings: [] + extensions: + - id: x-parser-unique-object-id + value: UnsubscribeRequest + bindings: [] + extensions: *ref_0 + - &ref_4 + id: BalancesUnsubscribeResponse + title: Balances unsubscribe response + description: Balances unsubscribe response + type: send + messages: + - &ref_9 + id: UnsubscribeResponse + contentType: application/json + payload: + - name: Unsubscribe Response + description: Response to balances unsubscribe request + type: object + properties: + - name: id + type: integer + description: Correlation ID for request-response matching + required: false + - name: data + type: array + title: Subscribe Response + required: true + properties: + - name: item + type: object + required: false + properties: + - name: status + type: string + enumValues: + - ok + required: true + - name: status + type: string + enumValues: + - err + required: true + - name: error + type: string + description: >- + Error identifier. For domain rejections and transport + errors (`401`/`404`/`429`/`500`) this is a stable, + machine-readable snake_case identifier that is part of + the API contract and safe to branch on, e.g. + `insufficient_margin`, `insufficient_balance`, + `order_not_found`, `reduce_only_invalid`, + `unauthorized`, `not_found`. For `400` it is a + human-readable validation detail whose wording may + change. See the Error handling guide for the domain + identifiers. (Post-only / Fill-or-Kill outcomes are + order statuses such as `post_only_rejected`, not + rejections.) + required: true + headers: [] + jsonPayloadSchema: + type: object + title: Base Response + properties: + id: + type: integer + description: Correlation ID for request-response matching + x-parser-schema-id: + data: + title: Subscribe Response + type: array + items: + oneOf: + - type: object + required: + - status + properties: + status: + type: string + enum: + - ok + x-parser-schema-id: + x-parser-schema-id: + - type: object + required: + - status + - error + properties: + status: + type: string + enum: + - err + x-parser-schema-id: + error: + type: string + description: >- + Error identifier. For domain rejections and transport + errors (`401`/`404`/`429`/`500`) this is a stable, + machine-readable snake_case identifier that is part of + the API contract and safe to branch on, e.g. + `insufficient_margin`, `insufficient_balance`, + `order_not_found`, `reduce_only_invalid`, + `unauthorized`, `not_found`. For `400` it is a + human-readable validation detail whose wording may + change. See the Error handling guide for the domain + identifiers. (Post-only / Fill-or-Kill outcomes are + order statuses such as `post_only_rejected`, not + rejections.) + example: insufficient_margin + x-parser-schema-id: + x-parser-schema-id: + x-parser-schema-id: + x-parser-schema-id: + required: + - data + x-parser-schema-id: + title: Unsubscribe Response + description: Response to balances unsubscribe request + example: |- + { + "data": [] + } + bindings: [] + extensions: + - id: x-parser-unique-object-id + value: UnsubscribeResponse + bindings: [] + extensions: *ref_0 + - &ref_5 + id: BalancesUpdate + title: Balances update + description: Receive balance updates + type: send + messages: + - &ref_10 + id: Update + contentType: application/json + payload: + - name: Update + description: Balance updates pushed every 5 seconds + type: object + properties: + - name: ch + type: string + description: >- + Channel name for push data. Parameterized channels include the + instrument ID (e.g. "trades::1", "book::1", "klines::1::1m", + "tickers::all"). Private channels use plain names (e.g. + "fills", "orders"). + required: true + - name: ts + type: integer + description: >- + Request timestamp. Unix milliseconds for most operations; Unix + seconds for withdrawals (must match the on-chain EIP-712 + struct verified against block.timestamp). + required: true + - name: sq + type: integer + description: Sequence number + required: true + - name: data + type: object + description: Balance object + required: true + properties: + - name: asset + type: string + description: Asset name + required: true + - name: balance + type: string + description: Total balance + required: true + - name: value + type: string + description: USD value + required: true + headers: [] + jsonPayloadSchema: + title: Balances Update + type: object + properties: + ch: + type: string + description: >- + Channel name for push data. Parameterized channels include the + instrument ID (e.g. "trades::1", "book::1", "klines::1::1m", + "tickers::all"). Private channels use plain names (e.g. "fills", + "orders"). + example: trades::1 + x-parser-schema-id: + ts: + type: integer + description: >- + Request timestamp. Unix milliseconds for most operations; Unix + seconds for withdrawals (must match the on-chain EIP-712 struct + verified against block.timestamp). + example: 1767225600000 + x-parser-schema-id: + sq: + type: integer + description: Sequence number + example: 1234567890 + x-parser-schema-id: + data: + type: object + description: Balance object + properties: + asset: + type: string + description: Asset name + example: USDC + x-parser-schema-id: + balance: + type: string + description: Total balance + example: '10000.00' + x-parser-schema-id: + value: + type: string + description: USD value + example: '10000.00' + x-parser-schema-id: + required: + - asset + - balance + - value + x-parser-schema-id: + required: + - ch + - ts + - sq + - data + x-parser-schema-id: + title: Update + description: Balance updates pushed every 5 seconds + example: |- + { + "ch": "balances", + "ts": 1767225600000, + "sq": 1234567890, + "data": { + "asset": "USDC", + "balance": "10000.00", + "value": "10000.00" + } + } + bindings: [] + extensions: + - id: x-parser-unique-object-id + value: Update + bindings: [] + extensions: *ref_0 +sendOperations: + - *ref_1 + - *ref_2 +receiveOperations: + - *ref_3 + - *ref_4 + - *ref_5 +sendMessages: + - *ref_6 + - *ref_7 +receiveMessages: + - *ref_8 + - *ref_9 + - *ref_10 +extensions: + - id: x-parser-unique-object-id + value: balances +securitySchemes: [] + +```` \ No newline at end of file diff --git a/PolymarketDocumentation-main/docs/api-reference/wss/perps-bbo.md b/PolymarketDocumentation-main/docs/api-reference/wss/perps-bbo.md new file mode 100644 index 00000000..52221e9e --- /dev/null +++ b/PolymarketDocumentation-main/docs/api-reference/wss/perps-bbo.md @@ -0,0 +1,606 @@ +> ## Documentation Index +> Fetch the complete documentation index at: https://docs.polymarket.com/llms.txt +> Use this file to discover all available pages before exploring further. + +# BBO + +> Perps WebSocket best bid and offer updates. + + + +## AsyncAPI + +````yaml asyncapi-perps.json bbo +id: bbo +title: BBO +description: Best bid and offer real-time updates. +servers: + - id: production + protocol: wss + host: ws.perpetuals.polymarket.com + bindings: [] + variables: [] +address: /v1/ws +parameters: [] +bindings: [] +operations: + - &ref_1 + id: BBOSubscribe + title: B b o subscribe + description: Subscribe to BBO + type: receive + messages: + - &ref_6 + id: SubscribeRequest + contentType: application/json + payload: + - name: Subscribe + description: Subscribe to BBO updates for a specific instrument + type: object + properties: + - name: id + type: integer + description: Correlation ID for request-response matching + required: false + - name: req + type: string + description: Request type + enumValues: + - post + - sub + - unsub + required: true + - name: chs + type: array + description: | + BBO subscription per instrument: `bbo::{iid}` (e.g. `bbo::1`). + required: true + properties: + - name: item + type: string + required: false + headers: [] + jsonPayloadSchema: + type: object + title: Base Request + properties: + id: + type: integer + description: Correlation ID for request-response matching + x-parser-schema-id: + req: + type: string + description: Request type + enum: + - post + - sub + - unsub + x-parser-schema-id: + chs: + type: array + description: | + BBO subscription per instrument: `bbo::{iid}` (e.g. `bbo::1`). + items: + type: string + pattern: ^bbo::\d+$ + x-parser-schema-id: + example: + - bbo::1 + x-parser-schema-id: + required: + - req + - chs + x-parser-schema-id: + title: Subscribe + description: Subscribe to BBO updates for a specific instrument + example: |- + { + "req": "sub", + "chs": [ + "bbo::1" + ] + } + bindings: [] + extensions: + - id: x-parser-unique-object-id + value: SubscribeRequest + bindings: [] + extensions: &ref_0 + - id: x-parser-unique-object-id + value: bbo + - &ref_3 + id: BBOSubscribeResponse + title: B b o subscribe response + description: BBO subscribe response + type: send + messages: + - &ref_8 + id: SubscribeResponse + contentType: application/json + payload: + - name: Subscribe Response + description: Response to BBO subscribe request + type: object + properties: + - name: id + type: integer + description: Correlation ID for request-response matching + required: false + - name: data + type: array + title: Subscribe Response + required: true + properties: + - name: item + type: object + required: false + properties: + - name: status + type: string + enumValues: + - ok + required: true + - name: status + type: string + enumValues: + - err + required: true + - name: error + type: string + description: >- + Error identifier. For domain rejections and transport + errors (`401`/`404`/`429`/`500`) this is a stable, + machine-readable snake_case identifier that is part of + the API contract and safe to branch on, e.g. + `insufficient_margin`, `insufficient_balance`, + `order_not_found`, `reduce_only_invalid`, + `unauthorized`, `not_found`. For `400` it is a + human-readable validation detail whose wording may + change. See the Error handling guide for the domain + identifiers. (Post-only / Fill-or-Kill outcomes are + order statuses such as `post_only_rejected`, not + rejections.) + required: true + headers: [] + jsonPayloadSchema: + type: object + title: Base Response + properties: + id: + type: integer + description: Correlation ID for request-response matching + x-parser-schema-id: + data: + title: Subscribe Response + type: array + items: + oneOf: + - type: object + required: + - status + properties: + status: + type: string + enum: + - ok + x-parser-schema-id: + x-parser-schema-id: + - type: object + required: + - status + - error + properties: + status: + type: string + enum: + - err + x-parser-schema-id: + error: + type: string + description: >- + Error identifier. For domain rejections and transport + errors (`401`/`404`/`429`/`500`) this is a stable, + machine-readable snake_case identifier that is part of + the API contract and safe to branch on, e.g. + `insufficient_margin`, `insufficient_balance`, + `order_not_found`, `reduce_only_invalid`, + `unauthorized`, `not_found`. For `400` it is a + human-readable validation detail whose wording may + change. See the Error handling guide for the domain + identifiers. (Post-only / Fill-or-Kill outcomes are + order statuses such as `post_only_rejected`, not + rejections.) + example: insufficient_margin + x-parser-schema-id: + x-parser-schema-id: + x-parser-schema-id: + x-parser-schema-id: + required: + - data + x-parser-schema-id: + title: Subscribe Response + description: Response to BBO subscribe request + example: |- + { + "data": [] + } + bindings: [] + extensions: + - id: x-parser-unique-object-id + value: SubscribeResponse + bindings: [] + extensions: *ref_0 + - &ref_2 + id: BBOUnsubscribe + title: B b o unsubscribe + description: Unsubscribe from BBO + type: receive + messages: + - &ref_7 + id: UnsubscribeRequest + contentType: application/json + payload: + - name: Unsubscribe + description: Unsubscribe from BBO updates + type: object + properties: + - name: id + type: integer + description: Correlation ID for request-response matching + required: false + - name: req + type: string + description: Request type + enumValues: + - post + - sub + - unsub + required: true + - name: chs + type: array + description: | + BBO subscription per instrument: `bbo::{iid}` (e.g. `bbo::1`). + required: true + properties: + - name: item + type: string + required: false + headers: [] + jsonPayloadSchema: + type: object + title: Base Request + properties: + id: + type: integer + description: Correlation ID for request-response matching + x-parser-schema-id: + req: + type: string + description: Request type + enum: + - post + - sub + - unsub + x-parser-schema-id: + chs: + type: array + description: | + BBO subscription per instrument: `bbo::{iid}` (e.g. `bbo::1`). + items: + type: string + pattern: ^bbo::\d+$ + x-parser-schema-id: + example: + - bbo::1 + x-parser-schema-id: + required: + - req + - chs + x-parser-schema-id: + title: Unsubscribe + description: Unsubscribe from BBO updates + example: |- + { + "req": "unsub", + "chs": [ + "bbo::1" + ] + } + bindings: [] + extensions: + - id: x-parser-unique-object-id + value: UnsubscribeRequest + bindings: [] + extensions: *ref_0 + - &ref_4 + id: BBOUnsubscribeResponse + title: B b o unsubscribe response + description: BBO unsubscribe response + type: send + messages: + - &ref_9 + id: UnsubscribeResponse + contentType: application/json + payload: + - name: Unsubscribe Response + description: Response to BBO unsubscribe request + type: object + properties: + - name: id + type: integer + description: Correlation ID for request-response matching + required: false + - name: data + type: array + title: Subscribe Response + required: true + properties: + - name: item + type: object + required: false + properties: + - name: status + type: string + enumValues: + - ok + required: true + - name: status + type: string + enumValues: + - err + required: true + - name: error + type: string + description: >- + Error identifier. For domain rejections and transport + errors (`401`/`404`/`429`/`500`) this is a stable, + machine-readable snake_case identifier that is part of + the API contract and safe to branch on, e.g. + `insufficient_margin`, `insufficient_balance`, + `order_not_found`, `reduce_only_invalid`, + `unauthorized`, `not_found`. For `400` it is a + human-readable validation detail whose wording may + change. See the Error handling guide for the domain + identifiers. (Post-only / Fill-or-Kill outcomes are + order statuses such as `post_only_rejected`, not + rejections.) + required: true + headers: [] + jsonPayloadSchema: + type: object + title: Base Response + properties: + id: + type: integer + description: Correlation ID for request-response matching + x-parser-schema-id: + data: + title: Subscribe Response + type: array + items: + oneOf: + - type: object + required: + - status + properties: + status: + type: string + enum: + - ok + x-parser-schema-id: + x-parser-schema-id: + - type: object + required: + - status + - error + properties: + status: + type: string + enum: + - err + x-parser-schema-id: + error: + type: string + description: >- + Error identifier. For domain rejections and transport + errors (`401`/`404`/`429`/`500`) this is a stable, + machine-readable snake_case identifier that is part of + the API contract and safe to branch on, e.g. + `insufficient_margin`, `insufficient_balance`, + `order_not_found`, `reduce_only_invalid`, + `unauthorized`, `not_found`. For `400` it is a + human-readable validation detail whose wording may + change. See the Error handling guide for the domain + identifiers. (Post-only / Fill-or-Kill outcomes are + order statuses such as `post_only_rejected`, not + rejections.) + example: insufficient_margin + x-parser-schema-id: + x-parser-schema-id: + x-parser-schema-id: + x-parser-schema-id: + required: + - data + x-parser-schema-id: + title: Unsubscribe Response + description: Response to BBO unsubscribe request + example: |- + { + "data": [] + } + bindings: [] + extensions: + - id: x-parser-unique-object-id + value: UnsubscribeResponse + bindings: [] + extensions: *ref_0 + - &ref_5 + id: BBOUpdate + title: B b o update + description: Receive BBO updates + type: send + messages: + - &ref_10 + id: Update + contentType: application/json + payload: + - name: Update + description: Real-time BBO updates for subscribed instruments + type: object + properties: + - name: ch + type: string + description: >- + Channel name for push data. Parameterized channels include the + instrument ID (e.g. "trades::1", "book::1", "klines::1::1m", + "tickers::all"). Private channels use plain names (e.g. + "fills", "orders"). + required: true + - name: ts + type: integer + description: >- + Request timestamp. Unix milliseconds for most operations; Unix + seconds for withdrawals (must match the on-chain EIP-712 + struct verified against block.timestamp). + required: true + - name: sq + type: integer + description: Sequence number + required: true + - name: data + type: object + title: BBO Data + description: BBO object + required: true + properties: + - name: iid + type: integer + description: Instrument ID + required: true + - name: bp + type: string + description: Best bid price + required: true + - name: bq + type: string + description: Best bid quantity + required: true + - name: ap + type: string + description: Best ask price + required: true + - name: aq + type: string + description: Best ask quantity + required: true + headers: [] + jsonPayloadSchema: + title: BBO Update + type: object + properties: + ch: + type: string + description: >- + Channel name for push data. Parameterized channels include the + instrument ID (e.g. "trades::1", "book::1", "klines::1::1m", + "tickers::all"). Private channels use plain names (e.g. "fills", + "orders"). + example: trades::1 + x-parser-schema-id: + ts: + type: integer + description: >- + Request timestamp. Unix milliseconds for most operations; Unix + seconds for withdrawals (must match the on-chain EIP-712 struct + verified against block.timestamp). + example: 1767225600000 + x-parser-schema-id: + sq: + type: integer + description: Sequence number + example: 1234567890 + x-parser-schema-id: + data: + type: object + description: BBO object + title: BBO Data + properties: + iid: + type: integer + description: Instrument ID + example: 1 + x-parser-schema-id: + bp: + type: string + description: Best bid price + example: '99.50' + x-parser-schema-id: + bq: + type: string + description: Best bid quantity + example: '10.00' + x-parser-schema-id: + ap: + type: string + description: Best ask price + example: '100.50' + x-parser-schema-id: + aq: + type: string + description: Best ask quantity + example: '10.00' + x-parser-schema-id: + required: + - iid + - bp + - bq + - ap + - aq + x-parser-schema-id: + required: + - ch + - ts + - sq + - data + x-parser-schema-id: + title: Update + description: Real-time BBO updates for subscribed instruments + example: |- + { + "ch": "bbo::1", + "ts": 1767225600000, + "sq": 1234567890, + "data": { + "iid": 1, + "bp": "99.50", + "bq": "10.00", + "ap": "100.50", + "aq": "10.00" + } + } + bindings: [] + extensions: + - id: x-parser-unique-object-id + value: Update + bindings: [] + extensions: *ref_0 +sendOperations: + - *ref_1 + - *ref_2 +receiveOperations: + - *ref_3 + - *ref_4 + - *ref_5 +sendMessages: + - *ref_6 + - *ref_7 +receiveMessages: + - *ref_8 + - *ref_9 + - *ref_10 +extensions: + - id: x-parser-unique-object-id + value: bbo +securitySchemes: [] + +```` \ No newline at end of file diff --git a/PolymarketDocumentation-main/docs/api-reference/wss/perps-book.md b/PolymarketDocumentation-main/docs/api-reference/wss/perps-book.md new file mode 100644 index 00000000..93880513 --- /dev/null +++ b/PolymarketDocumentation-main/docs/api-reference/wss/perps-book.md @@ -0,0 +1,621 @@ +> ## Documentation Index +> Fetch the complete documentation index at: https://docs.polymarket.com/llms.txt +> Use this file to discover all available pages before exploring further. + +# Book + +> Perps WebSocket order book updates. + + + +## AsyncAPI + +````yaml asyncapi-perps.json book +id: book +title: Book +description: Order book snapshot updates. Pushed every 100ms. +servers: + - id: production + protocol: wss + host: ws.perpetuals.polymarket.com + bindings: [] + variables: [] +address: /v1/ws +parameters: [] +bindings: [] +operations: + - &ref_1 + id: BookSubscribe + title: Book subscribe + description: Subscribe to book + type: receive + messages: + - &ref_6 + id: SubscribeRequest + contentType: application/json + payload: + - name: Subscribe + description: Subscribe to order book updates for an instrument + type: object + properties: + - name: id + type: integer + description: Correlation ID for request-response matching + required: false + - name: req + type: string + description: Request type + enumValues: + - post + - sub + - unsub + required: true + - name: chs + type: array + description: Book subscription in format "book::{iid}" (e.g., "book::1") + required: true + properties: + - name: item + type: string + required: false + headers: [] + jsonPayloadSchema: + type: object + title: Base Request + properties: + id: + type: integer + description: Correlation ID for request-response matching + x-parser-schema-id: + req: + type: string + description: Request type + enum: + - post + - sub + - unsub + x-parser-schema-id: + chs: + type: array + description: Book subscription in format "book::{iid}" (e.g., "book::1") + items: + type: string + pattern: ^book::\d+$ + x-parser-schema-id: + example: + - book::1 + x-parser-schema-id: + required: + - req + - chs + x-parser-schema-id: + title: Subscribe + description: Subscribe to order book updates for an instrument + example: |- + { + "req": "sub", + "chs": [ + "book::1" + ] + } + bindings: [] + extensions: + - id: x-parser-unique-object-id + value: SubscribeRequest + bindings: [] + extensions: &ref_0 + - id: x-parser-unique-object-id + value: book + - &ref_3 + id: BookSubscribeResponse + title: Book subscribe response + description: Book subscribe response + type: send + messages: + - &ref_8 + id: SubscribeResponse + contentType: application/json + payload: + - name: Subscribe Response + description: Response to book subscribe request + type: object + properties: + - name: id + type: integer + description: Correlation ID for request-response matching + required: false + - name: data + type: array + title: Subscribe Response + required: true + properties: + - name: item + type: object + required: false + properties: + - name: status + type: string + enumValues: + - ok + required: true + - name: status + type: string + enumValues: + - err + required: true + - name: error + type: string + description: >- + Error identifier. For domain rejections and transport + errors (`401`/`404`/`429`/`500`) this is a stable, + machine-readable snake_case identifier that is part of + the API contract and safe to branch on, e.g. + `insufficient_margin`, `insufficient_balance`, + `order_not_found`, `reduce_only_invalid`, + `unauthorized`, `not_found`. For `400` it is a + human-readable validation detail whose wording may + change. See the Error handling guide for the domain + identifiers. (Post-only / Fill-or-Kill outcomes are + order statuses such as `post_only_rejected`, not + rejections.) + required: true + headers: [] + jsonPayloadSchema: + type: object + title: Base Response + properties: + id: + type: integer + description: Correlation ID for request-response matching + x-parser-schema-id: + data: + title: Subscribe Response + type: array + items: + oneOf: + - type: object + required: + - status + properties: + status: + type: string + enum: + - ok + x-parser-schema-id: + x-parser-schema-id: + - type: object + required: + - status + - error + properties: + status: + type: string + enum: + - err + x-parser-schema-id: + error: + type: string + description: >- + Error identifier. For domain rejections and transport + errors (`401`/`404`/`429`/`500`) this is a stable, + machine-readable snake_case identifier that is part of + the API contract and safe to branch on, e.g. + `insufficient_margin`, `insufficient_balance`, + `order_not_found`, `reduce_only_invalid`, + `unauthorized`, `not_found`. For `400` it is a + human-readable validation detail whose wording may + change. See the Error handling guide for the domain + identifiers. (Post-only / Fill-or-Kill outcomes are + order statuses such as `post_only_rejected`, not + rejections.) + example: insufficient_margin + x-parser-schema-id: + x-parser-schema-id: + x-parser-schema-id: + x-parser-schema-id: + required: + - data + x-parser-schema-id: + title: Subscribe Response + description: Response to book subscribe request + example: |- + { + "data": [] + } + bindings: [] + extensions: + - id: x-parser-unique-object-id + value: SubscribeResponse + bindings: [] + extensions: *ref_0 + - &ref_2 + id: BookUnsubscribe + title: Book unsubscribe + description: Unsubscribe from book + type: receive + messages: + - &ref_7 + id: UnsubscribeRequest + contentType: application/json + payload: + - name: Unsubscribe + description: Unsubscribe from order book updates + type: object + properties: + - name: id + type: integer + description: Correlation ID for request-response matching + required: false + - name: req + type: string + description: Request type + enumValues: + - post + - sub + - unsub + required: true + - name: chs + type: array + description: Book subscription in format "book::{iid}" (e.g., "book::1") + required: true + properties: + - name: item + type: string + required: false + headers: [] + jsonPayloadSchema: + type: object + title: Base Request + properties: + id: + type: integer + description: Correlation ID for request-response matching + x-parser-schema-id: + req: + type: string + description: Request type + enum: + - post + - sub + - unsub + x-parser-schema-id: + chs: + type: array + description: Book subscription in format "book::{iid}" (e.g., "book::1") + items: + type: string + pattern: ^book::\d+$ + x-parser-schema-id: + example: + - book::1 + x-parser-schema-id: + required: + - req + - chs + x-parser-schema-id: + title: Unsubscribe + description: Unsubscribe from order book updates + example: |- + { + "req": "unsub", + "chs": [ + "book::1" + ] + } + bindings: [] + extensions: + - id: x-parser-unique-object-id + value: UnsubscribeRequest + bindings: [] + extensions: *ref_0 + - &ref_4 + id: BookUnsubscribeResponse + title: Book unsubscribe response + description: Book unsubscribe response + type: send + messages: + - &ref_9 + id: UnsubscribeResponse + contentType: application/json + payload: + - name: Unsubscribe Response + description: Response to book unsubscribe request + type: object + properties: + - name: id + type: integer + description: Correlation ID for request-response matching + required: false + - name: data + type: array + title: Subscribe Response + required: true + properties: + - name: item + type: object + required: false + properties: + - name: status + type: string + enumValues: + - ok + required: true + - name: status + type: string + enumValues: + - err + required: true + - name: error + type: string + description: >- + Error identifier. For domain rejections and transport + errors (`401`/`404`/`429`/`500`) this is a stable, + machine-readable snake_case identifier that is part of + the API contract and safe to branch on, e.g. + `insufficient_margin`, `insufficient_balance`, + `order_not_found`, `reduce_only_invalid`, + `unauthorized`, `not_found`. For `400` it is a + human-readable validation detail whose wording may + change. See the Error handling guide for the domain + identifiers. (Post-only / Fill-or-Kill outcomes are + order statuses such as `post_only_rejected`, not + rejections.) + required: true + headers: [] + jsonPayloadSchema: + type: object + title: Base Response + properties: + id: + type: integer + description: Correlation ID for request-response matching + x-parser-schema-id: + data: + title: Subscribe Response + type: array + items: + oneOf: + - type: object + required: + - status + properties: + status: + type: string + enum: + - ok + x-parser-schema-id: + x-parser-schema-id: + - type: object + required: + - status + - error + properties: + status: + type: string + enum: + - err + x-parser-schema-id: + error: + type: string + description: >- + Error identifier. For domain rejections and transport + errors (`401`/`404`/`429`/`500`) this is a stable, + machine-readable snake_case identifier that is part of + the API contract and safe to branch on, e.g. + `insufficient_margin`, `insufficient_balance`, + `order_not_found`, `reduce_only_invalid`, + `unauthorized`, `not_found`. For `400` it is a + human-readable validation detail whose wording may + change. See the Error handling guide for the domain + identifiers. (Post-only / Fill-or-Kill outcomes are + order statuses such as `post_only_rejected`, not + rejections.) + example: insufficient_margin + x-parser-schema-id: + x-parser-schema-id: + x-parser-schema-id: + x-parser-schema-id: + required: + - data + x-parser-schema-id: + title: Unsubscribe Response + description: Response to book unsubscribe request + example: |- + { + "data": [] + } + bindings: [] + extensions: + - id: x-parser-unique-object-id + value: UnsubscribeResponse + bindings: [] + extensions: *ref_0 + - &ref_5 + id: BookUpdate + title: Book update + description: Receive book updates + type: send + messages: + - &ref_10 + id: Update + contentType: application/json + payload: + - name: Update + description: Real-time order book updates for subscribed instruments + type: object + properties: + - name: ch + type: string + description: >- + Channel name for push data. Parameterized channels include the + instrument ID (e.g. "trades::1", "book::1", "klines::1::1m", + "tickers::all"). Private channels use plain names (e.g. + "fills", "orders"). + required: true + - name: ts + type: integer + description: >- + Request timestamp. Unix milliseconds for most operations; Unix + seconds for withdrawals (must match the on-chain EIP-712 + struct verified against block.timestamp). + required: true + - name: sq + type: integer + description: Sequence number + required: true + - name: data + type: object + required: true + properties: + - name: b + type: array + description: Bid levels + required: true + properties: + - name: item + type: array + description: | + - `"100.00"` - Price + - `"10.00"` - Quantity + required: false + properties: + - name: item + type: string + required: false + - name: a + type: array + description: Ask levels + required: true + properties: + - name: item + type: array + description: | + - `"100.00"` - Price + - `"10.00"` - Quantity + required: false + properties: + - name: item + type: string + required: false + headers: [] + jsonPayloadSchema: + title: Book Update + type: object + properties: + ch: + type: string + description: >- + Channel name for push data. Parameterized channels include the + instrument ID (e.g. "trades::1", "book::1", "klines::1::1m", + "tickers::all"). Private channels use plain names (e.g. "fills", + "orders"). + example: trades::1 + x-parser-schema-id: + ts: + type: integer + description: >- + Request timestamp. Unix milliseconds for most operations; Unix + seconds for withdrawals (must match the on-chain EIP-712 struct + verified against block.timestamp). + example: 1767225600000 + x-parser-schema-id: + sq: + type: integer + description: Sequence number + example: 1234567890 + x-parser-schema-id: + data: + type: object + required: + - b + - a + properties: + b: + type: array + items: + type: array + items: + type: string + x-parser-schema-id: + maxItems: 2 + description: | + - `"100.00"` - Price + - `"10.00"` - Quantity + example: + - '100.00' + - '10.00' + x-parser-schema-id: + description: Bid levels + x-parser-schema-id: + a: + type: array + items: + type: array + items: + type: string + x-parser-schema-id: + maxItems: 2 + description: | + - `"100.00"` - Price + - `"10.00"` - Quantity + example: + - '100.00' + - '10.00' + x-parser-schema-id: + description: Ask levels + x-parser-schema-id: + x-parser-schema-id: + required: + - ch + - ts + - sq + - data + x-parser-schema-id: + title: Update + description: Real-time order book updates for subscribed instruments + example: |- + { + "ch": "book::1", + "ts": 1767225600000, + "sq": 1234567890, + "data": { + "b": [ + [ + "100.00", + "10.00" + ] + ], + "a": [ + [ + "100.00", + "10.00" + ] + ] + } + } + bindings: [] + extensions: + - id: x-parser-unique-object-id + value: Update + bindings: [] + extensions: *ref_0 +sendOperations: + - *ref_1 + - *ref_2 +receiveOperations: + - *ref_3 + - *ref_4 + - *ref_5 +sendMessages: + - *ref_6 + - *ref_7 +receiveMessages: + - *ref_8 + - *ref_9 + - *ref_10 +extensions: + - id: x-parser-unique-object-id + value: book +securitySchemes: [] + +```` \ No newline at end of file diff --git a/PolymarketDocumentation-main/docs/api-reference/wss/perps-cancel-orders-coid.md b/PolymarketDocumentation-main/docs/api-reference/wss/perps-cancel-orders-coid.md new file mode 100644 index 00000000..542d303d --- /dev/null +++ b/PolymarketDocumentation-main/docs/api-reference/wss/perps-cancel-orders-coid.md @@ -0,0 +1,406 @@ +> ## Documentation Index +> Fetch the complete documentation index at: https://docs.polymarket.com/llms.txt +> Use this file to discover all available pages before exploring further. + +# Cancel Orders by Client Order ID + +> Perps WebSocket order cancellation by client order ID. + + + +## AsyncAPI + +````yaml asyncapi-perps.json cancelOrdersCOID +id: cancelOrdersCOID +title: Cancel Orders COID +description: | + Cancel orders by client order ID. + Requires proxy signature, see [proxy signing](/http/signing#2-proxy-signing). + + Action Weight: **0** +servers: + - id: production + protocol: wss + host: ws.perpetuals.polymarket.com + bindings: [] + variables: [] +address: /v1/ws +parameters: [] +bindings: [] +operations: + - &ref_1 + id: CancelOrdersCOIDSend + title: Cancel orders c o i d send + description: Cancel orders by client order ID + type: receive + messages: + - &ref_3 + id: Request + contentType: application/json + payload: + - name: Cancel Orders COID Request + description: Client submits a signed cancel-by-client-order-id request + type: object + properties: + - name: id + type: integer + description: Correlation ID for request-response matching + required: false + - name: req + type: string + description: Request type + enumValues: + - post + - sub + - unsub + required: true + - name: op + type: object + required: true + properties: + - name: type + type: string + enumValues: + - cancelOrdersCOID + required: true + - name: args + type: array + description: > + Array of client order IDs to cancel. Cancelling an order + that has + + attached take-profit / stop-loss children (see + `CreateOrder.tr`) + + cascades to those children — they are cancelled with + reason + + `ParentCancelled`. + required: true + properties: + - name: item + type: string + description: Client order ID + required: false + - name: sig + type: string + description: Signature in hex format + required: true + - name: salt + type: integer + description: Salt + required: true + - name: ts + type: integer + description: >- + Request timestamp. Unix milliseconds for most operations; Unix + seconds for withdrawals (must match the on-chain EIP-712 + struct verified against block.timestamp). + required: true + - name: exp + type: integer + description: >- + Command expiry timestamp in Unix milliseconds. If provided, it + must be in the future and within the gateway's default command + timeout. It can shorten request validity but cannot extend it. + This is not an order auto-cancel time. + required: false + headers: [] + jsonPayloadSchema: + type: object + title: Base Request + properties: + id: + type: integer + description: Correlation ID for request-response matching + x-parser-schema-id: + req: + type: string + description: Request type + enum: + - post + - sub + - unsub + x-parser-schema-id: + op: + type: object + required: + - type + - args + properties: + type: + type: string + enum: + - cancelOrdersCOID + x-parser-schema-id: + args: + type: array + description: > + Array of client order IDs to cancel. Cancelling an order + that has + + attached take-profit / stop-loss children (see + `CreateOrder.tr`) + + cascades to those children — they are cancelled with reason + + `ParentCancelled`. + items: + type: string + description: Client order ID + minLength: 32 + maxLength: 32 + pattern: ^[0-9a-f]{32}$ + example: 550e8400e29b41d4a716446655440000 + x-parser-schema-id: + x-parser-schema-id: + x-parser-schema-id: + sig: + type: string + description: Signature in hex format + example: 0x1234567890... + x-parser-schema-id: + salt: + type: integer + description: Salt + example: 1234567890 + x-parser-schema-id: + ts: + type: integer + description: >- + Request timestamp. Unix milliseconds for most operations; Unix + seconds for withdrawals (must match the on-chain EIP-712 struct + verified against block.timestamp). + example: 1767225600000 + x-parser-schema-id: + exp: + type: integer + description: >- + Command expiry timestamp in Unix milliseconds. If provided, it + must be in the future and within the gateway's default command + timeout. It can shorten request validity but cannot extend it. + This is not an order auto-cancel time. + example: 1767225600000 + x-parser-schema-id: + required: + - req + - op + - sig + - salt + - ts + x-parser-schema-id: + title: Cancel Orders COID Request + description: Client submits a signed cancel-by-client-order-id request + example: |- + { + "req": "post", + "op": { + "type": "cancelOrdersCOID", + "args": [ + "550e8400e29b41d4a716446655440000" + ] + }, + "sig": "0x1234567890...", + "salt": 1234567890, + "ts": 1767225600000, + "exp": 1767225600000 + } + bindings: [] + extensions: + - id: x-parser-unique-object-id + value: Request + bindings: [] + extensions: &ref_0 + - id: x-parser-unique-object-id + value: cancelOrdersCOID + - &ref_2 + id: CancelOrdersCOIDReceive + title: Cancel orders c o i d receive + description: Cancel by client order ID response + type: send + messages: + - &ref_4 + id: Response + contentType: application/json + payload: + - name: Cancel Orders COID Response + description: Server responds with cancel result for each client order ID + type: object + properties: + - name: id + type: integer + description: Correlation ID for request-response matching + required: false + - name: data + type: array + description: Array of cancel results + required: true + properties: + - name: item + type: object + required: false + properties: + - name: status + type: string + enumValues: + - ok + required: true + - name: oid + type: integer + description: Order ID + required: true + - name: coid + type: string + description: Client order ID + required: false + - name: status + type: string + enumValues: + - err + required: true + - name: oid + type: integer + description: Order ID + required: false + - name: coid + type: string + description: Client order ID + required: false + - name: error + type: string + description: >- + Error identifier. For domain rejections and transport + errors (`401`/`404`/`429`/`500`) this is a stable, + machine-readable snake_case identifier that is part of + the API contract and safe to branch on, e.g. + `insufficient_margin`, `insufficient_balance`, + `order_not_found`, `reduce_only_invalid`, + `unauthorized`, `not_found`. For `400` it is a + human-readable validation detail whose wording may + change. See the Error handling guide for the domain + identifiers. (Post-only / Fill-or-Kill outcomes are + order statuses such as `post_only_rejected`, not + rejections.) + required: true + headers: [] + jsonPayloadSchema: + type: object + title: Base Response + properties: + id: + type: integer + description: Correlation ID for request-response matching + x-parser-schema-id: + data: + type: array + description: Array of cancel results + items: + oneOf: + - type: object + required: + - status + - oid + properties: + status: + type: string + enum: + - ok + x-parser-schema-id: + oid: + type: integer + description: Order ID + example: 1234567890 + x-parser-schema-id: + coid: + type: string + description: Client order ID + minLength: 32 + maxLength: 32 + pattern: ^[0-9a-f]{32}$ + example: 550e8400e29b41d4a716446655440000 + x-parser-schema-id: + x-parser-schema-id: + - type: object + required: + - status + - error + properties: + status: + type: string + enum: + - err + x-parser-schema-id: + oid: + type: integer + description: Order ID + example: 1234567890 + x-parser-schema-id: + coid: + type: string + description: Client order ID + minLength: 32 + maxLength: 32 + pattern: ^[0-9a-f]{32}$ + example: 550e8400e29b41d4a716446655440000 + x-parser-schema-id: + error: + type: string + description: >- + Error identifier. For domain rejections and transport + errors (`401`/`404`/`429`/`500`) this is a stable, + machine-readable snake_case identifier that is part of + the API contract and safe to branch on, e.g. + `insufficient_margin`, `insufficient_balance`, + `order_not_found`, `reduce_only_invalid`, + `unauthorized`, `not_found`. For `400` it is a + human-readable validation detail whose wording may + change. See the Error handling guide for the domain + identifiers. (Post-only / Fill-or-Kill outcomes are + order statuses such as `post_only_rejected`, not + rejections.) + example: insufficient_margin + x-parser-schema-id: + x-parser-schema-id: + x-parser-schema-id: + x-parser-schema-id: + required: + - data + x-parser-schema-id: + title: Cancel Orders COID Response + description: Server responds with cancel result for each client order ID + example: |- + { + "id": 3, + "data": [ + { + "status": "ok", + "oid": 1234567890, + "coid": "550e8400e29b41d4a716446655440000" + }, + { + "status": "ok", + "oid": 1234567891, + "coid": "550e8400e29b41d4a716446655440001" + } + ] + } + bindings: [] + extensions: + - id: x-parser-unique-object-id + value: Response + bindings: [] + extensions: *ref_0 +sendOperations: + - *ref_1 +receiveOperations: + - *ref_2 +sendMessages: + - *ref_3 +receiveMessages: + - *ref_4 +extensions: + - id: x-parser-unique-object-id + value: cancelOrdersCOID +securitySchemes: [] + +```` \ No newline at end of file diff --git a/PolymarketDocumentation-main/docs/api-reference/wss/perps-cancel-orders.md b/PolymarketDocumentation-main/docs/api-reference/wss/perps-cancel-orders.md new file mode 100644 index 00000000..2c3aa2eb --- /dev/null +++ b/PolymarketDocumentation-main/docs/api-reference/wss/perps-cancel-orders.md @@ -0,0 +1,398 @@ +> ## Documentation Index +> Fetch the complete documentation index at: https://docs.polymarket.com/llms.txt +> Use this file to discover all available pages before exploring further. + +# Cancel Orders + +> Perps WebSocket order cancellation by order ID. + + + +## AsyncAPI + +````yaml asyncapi-perps.json cancelOrders +id: cancelOrders +title: Cancel Orders +description: | + Cancel orders. + Requires proxy signature, see [proxy signing](/http/signing#2-proxy-signing). + + Action Weight: **0** +servers: + - id: production + protocol: wss + host: ws.perpetuals.polymarket.com + bindings: [] + variables: [] +address: /v1/ws +parameters: [] +bindings: [] +operations: + - &ref_1 + id: CancelOrdersSend + title: Cancel orders send + description: Cancel orders + type: receive + messages: + - &ref_3 + id: Request + contentType: application/json + payload: + - name: Cancel Orders Request + description: Client submits a signed order cancellation request + type: object + properties: + - name: id + type: integer + description: Correlation ID for request-response matching + required: false + - name: req + type: string + description: Request type + enumValues: + - post + - sub + - unsub + required: true + - name: op + type: object + required: true + properties: + - name: type + type: string + enumValues: + - cancelOrders + required: true + - name: args + type: array + description: > + Array of order IDs to cancel. Cancelling an order that has + attached + + take-profit / stop-loss children (see `CreateOrder.tr`) + cascades to + + those children — they are cancelled with reason + `ParentCancelled`. + required: true + properties: + - name: item + type: integer + description: Order ID + required: false + - name: sig + type: string + description: Signature in hex format + required: true + - name: salt + type: integer + description: Salt + required: true + - name: ts + type: integer + description: >- + Request timestamp. Unix milliseconds for most operations; Unix + seconds for withdrawals (must match the on-chain EIP-712 + struct verified against block.timestamp). + required: true + - name: exp + type: integer + description: >- + Command expiry timestamp in Unix milliseconds. If provided, it + must be in the future and within the gateway's default command + timeout. It can shorten request validity but cannot extend it. + This is not an order auto-cancel time. + required: false + headers: [] + jsonPayloadSchema: + type: object + title: Base Request + properties: + id: + type: integer + description: Correlation ID for request-response matching + x-parser-schema-id: + req: + type: string + description: Request type + enum: + - post + - sub + - unsub + x-parser-schema-id: + op: + type: object + required: + - type + - args + properties: + type: + type: string + enum: + - cancelOrders + x-parser-schema-id: + args: + type: array + description: > + Array of order IDs to cancel. Cancelling an order that has + attached + + take-profit / stop-loss children (see `CreateOrder.tr`) + cascades to + + those children — they are cancelled with reason + `ParentCancelled`. + items: + type: integer + description: Order ID + example: 1234567890 + x-parser-schema-id: + x-parser-schema-id: + x-parser-schema-id: + sig: + type: string + description: Signature in hex format + example: 0x1234567890... + x-parser-schema-id: + salt: + type: integer + description: Salt + example: 1234567890 + x-parser-schema-id: + ts: + type: integer + description: >- + Request timestamp. Unix milliseconds for most operations; Unix + seconds for withdrawals (must match the on-chain EIP-712 struct + verified against block.timestamp). + example: 1767225600000 + x-parser-schema-id: + exp: + type: integer + description: >- + Command expiry timestamp in Unix milliseconds. If provided, it + must be in the future and within the gateway's default command + timeout. It can shorten request validity but cannot extend it. + This is not an order auto-cancel time. + example: 1767225600000 + x-parser-schema-id: + required: + - req + - op + - sig + - salt + - ts + x-parser-schema-id: + title: Cancel Orders Request + description: Client submits a signed order cancellation request + example: |- + { + "req": "post", + "op": { + "type": "cancelOrders", + "args": [ + 1234567890 + ] + }, + "sig": "0x1234567890...", + "salt": 1234567890, + "ts": 1767225600000, + "exp": 1767225600000 + } + bindings: [] + extensions: + - id: x-parser-unique-object-id + value: Request + bindings: [] + extensions: &ref_0 + - id: x-parser-unique-object-id + value: cancelOrders + - &ref_2 + id: CancelOrdersReceive + title: Cancel orders receive + description: Cancel response + type: send + messages: + - &ref_4 + id: Response + contentType: application/json + payload: + - name: Cancel Orders Response + description: Server responds with cancel result for each order + type: object + properties: + - name: id + type: integer + description: Correlation ID for request-response matching + required: false + - name: data + type: array + description: Array of cancel results + required: true + properties: + - name: item + type: object + required: false + properties: + - name: status + type: string + enumValues: + - ok + required: true + - name: oid + type: integer + description: Order ID + required: true + - name: coid + type: string + description: Client order ID + required: false + - name: status + type: string + enumValues: + - err + required: true + - name: oid + type: integer + description: Order ID + required: false + - name: coid + type: string + description: Client order ID + required: false + - name: error + type: string + description: >- + Error identifier. For domain rejections and transport + errors (`401`/`404`/`429`/`500`) this is a stable, + machine-readable snake_case identifier that is part of + the API contract and safe to branch on, e.g. + `insufficient_margin`, `insufficient_balance`, + `order_not_found`, `reduce_only_invalid`, + `unauthorized`, `not_found`. For `400` it is a + human-readable validation detail whose wording may + change. See the Error handling guide for the domain + identifiers. (Post-only / Fill-or-Kill outcomes are + order statuses such as `post_only_rejected`, not + rejections.) + required: true + headers: [] + jsonPayloadSchema: + type: object + title: Base Response + properties: + id: + type: integer + description: Correlation ID for request-response matching + x-parser-schema-id: + data: + type: array + description: Array of cancel results + items: + oneOf: + - type: object + required: + - status + - oid + properties: + status: + type: string + enum: + - ok + x-parser-schema-id: + oid: + type: integer + description: Order ID + example: 1234567890 + x-parser-schema-id: + coid: + type: string + description: Client order ID + minLength: 32 + maxLength: 32 + pattern: ^[0-9a-f]{32}$ + example: 550e8400e29b41d4a716446655440000 + x-parser-schema-id: + x-parser-schema-id: + - type: object + required: + - status + - error + properties: + status: + type: string + enum: + - err + x-parser-schema-id: + oid: + type: integer + description: Order ID + example: 1234567890 + x-parser-schema-id: + coid: + type: string + description: Client order ID + minLength: 32 + maxLength: 32 + pattern: ^[0-9a-f]{32}$ + example: 550e8400e29b41d4a716446655440000 + x-parser-schema-id: + error: + type: string + description: >- + Error identifier. For domain rejections and transport + errors (`401`/`404`/`429`/`500`) this is a stable, + machine-readable snake_case identifier that is part of + the API contract and safe to branch on, e.g. + `insufficient_margin`, `insufficient_balance`, + `order_not_found`, `reduce_only_invalid`, + `unauthorized`, `not_found`. For `400` it is a + human-readable validation detail whose wording may + change. See the Error handling guide for the domain + identifiers. (Post-only / Fill-or-Kill outcomes are + order statuses such as `post_only_rejected`, not + rejections.) + example: insufficient_margin + x-parser-schema-id: + x-parser-schema-id: + x-parser-schema-id: + x-parser-schema-id: + required: + - data + x-parser-schema-id: + title: Cancel Orders Response + description: Server responds with cancel result for each order + example: |- + { + "id": 3, + "data": [ + { + "status": "ok", + "oid": 1234567890 + }, + { + "status": "ok", + "oid": 1234567891 + } + ] + } + bindings: [] + extensions: + - id: x-parser-unique-object-id + value: Response + bindings: [] + extensions: *ref_0 +sendOperations: + - *ref_1 +receiveOperations: + - *ref_2 +sendMessages: + - *ref_3 +receiveMessages: + - *ref_4 +extensions: + - id: x-parser-unique-object-id + value: cancelOrders +securitySchemes: [] + +```` \ No newline at end of file diff --git a/PolymarketDocumentation-main/docs/api-reference/wss/perps-deposits.md b/PolymarketDocumentation-main/docs/api-reference/wss/perps-deposits.md new file mode 100644 index 00000000..dc578920 --- /dev/null +++ b/PolymarketDocumentation-main/docs/api-reference/wss/perps-deposits.md @@ -0,0 +1,614 @@ +> ## Documentation Index +> Fetch the complete documentation index at: https://docs.polymarket.com/llms.txt +> Use this file to discover all available pages before exploring further. + +# Deposits + +> Perps WebSocket private deposit updates. + + + +## AsyncAPI + +````yaml asyncapi-perps.json deposits +id: deposits +title: Deposits +description: >- + Real-time deposit status updates. Requires authentication, see + [Auth](/ws/auth). +servers: + - id: production + protocol: wss + host: ws.perpetuals.polymarket.com + bindings: [] + variables: [] +address: /v1/ws +parameters: [] +bindings: [] +operations: + - &ref_1 + id: DepositsSubscribe + title: Deposits subscribe + description: Subscribe to deposits + type: receive + messages: + - &ref_6 + id: SubscribeRequest + contentType: application/json + payload: + - name: Subscribe + description: Subscribe to private deposit updates (requires prior auth) + type: object + properties: + - name: id + type: integer + description: Correlation ID for request-response matching + required: false + - name: req + type: string + description: Request type + enumValues: + - post + - sub + - unsub + required: true + - name: chs + type: array + description: 'Deposits private channel: "deposits"' + required: true + properties: + - name: item + type: string + enumValues: + - deposits + required: false + headers: [] + jsonPayloadSchema: + type: object + title: Base Request + properties: + id: + type: integer + description: Correlation ID for request-response matching + x-parser-schema-id: + req: + type: string + description: Request type + enum: + - post + - sub + - unsub + x-parser-schema-id: + chs: + type: array + description: 'Deposits private channel: "deposits"' + items: + type: string + enum: + - deposits + x-parser-schema-id: + example: + - deposits + x-parser-schema-id: + required: + - req + - chs + x-parser-schema-id: + title: Subscribe + description: Subscribe to private deposit updates (requires prior auth) + example: |- + { + "req": "sub", + "chs": [ + "deposits" + ] + } + bindings: [] + extensions: + - id: x-parser-unique-object-id + value: SubscribeRequest + bindings: [] + extensions: &ref_0 + - id: x-parser-unique-object-id + value: deposits + - &ref_3 + id: DepositsSubscribeResponse + title: Deposits subscribe response + description: Deposits subscribe response + type: send + messages: + - &ref_8 + id: SubscribeResponse + contentType: application/json + payload: + - name: Subscribe Response + description: Response to deposits subscribe request + type: object + properties: + - name: id + type: integer + description: Correlation ID for request-response matching + required: false + - name: data + type: array + title: Subscribe Response + required: true + properties: + - name: item + type: object + required: false + properties: + - name: status + type: string + enumValues: + - ok + required: true + - name: status + type: string + enumValues: + - err + required: true + - name: error + type: string + description: >- + Error identifier. For domain rejections and transport + errors (`401`/`404`/`429`/`500`) this is a stable, + machine-readable snake_case identifier that is part of + the API contract and safe to branch on, e.g. + `insufficient_margin`, `insufficient_balance`, + `order_not_found`, `reduce_only_invalid`, + `unauthorized`, `not_found`. For `400` it is a + human-readable validation detail whose wording may + change. See the Error handling guide for the domain + identifiers. (Post-only / Fill-or-Kill outcomes are + order statuses such as `post_only_rejected`, not + rejections.) + required: true + headers: [] + jsonPayloadSchema: + type: object + title: Base Response + properties: + id: + type: integer + description: Correlation ID for request-response matching + x-parser-schema-id: + data: + title: Subscribe Response + type: array + items: + oneOf: + - type: object + required: + - status + properties: + status: + type: string + enum: + - ok + x-parser-schema-id: + x-parser-schema-id: + - type: object + required: + - status + - error + properties: + status: + type: string + enum: + - err + x-parser-schema-id: + error: + type: string + description: >- + Error identifier. For domain rejections and transport + errors (`401`/`404`/`429`/`500`) this is a stable, + machine-readable snake_case identifier that is part of + the API contract and safe to branch on, e.g. + `insufficient_margin`, `insufficient_balance`, + `order_not_found`, `reduce_only_invalid`, + `unauthorized`, `not_found`. For `400` it is a + human-readable validation detail whose wording may + change. See the Error handling guide for the domain + identifiers. (Post-only / Fill-or-Kill outcomes are + order statuses such as `post_only_rejected`, not + rejections.) + example: insufficient_margin + x-parser-schema-id: + x-parser-schema-id: + x-parser-schema-id: + x-parser-schema-id: + required: + - data + x-parser-schema-id: + title: Subscribe Response + description: Response to deposits subscribe request + example: |- + { + "data": [] + } + bindings: [] + extensions: + - id: x-parser-unique-object-id + value: SubscribeResponse + bindings: [] + extensions: *ref_0 + - &ref_2 + id: DepositsUnsubscribe + title: Deposits unsubscribe + description: Unsubscribe from deposits + type: receive + messages: + - &ref_7 + id: UnsubscribeRequest + contentType: application/json + payload: + - name: Unsubscribe + description: Unsubscribe from private deposit updates + type: object + properties: + - name: id + type: integer + description: Correlation ID for request-response matching + required: false + - name: req + type: string + description: Request type + enumValues: + - post + - sub + - unsub + required: true + - name: chs + type: array + description: 'Deposits private channel: "deposits"' + required: true + properties: + - name: item + type: string + enumValues: + - deposits + required: false + headers: [] + jsonPayloadSchema: + type: object + title: Base Request + properties: + id: + type: integer + description: Correlation ID for request-response matching + x-parser-schema-id: + req: + type: string + description: Request type + enum: + - post + - sub + - unsub + x-parser-schema-id: + chs: + type: array + description: 'Deposits private channel: "deposits"' + items: + type: string + enum: + - deposits + x-parser-schema-id: + example: + - deposits + x-parser-schema-id: + required: + - req + - chs + x-parser-schema-id: + title: Unsubscribe + description: Unsubscribe from private deposit updates + example: |- + { + "req": "unsub", + "chs": [ + "deposits" + ] + } + bindings: [] + extensions: + - id: x-parser-unique-object-id + value: UnsubscribeRequest + bindings: [] + extensions: *ref_0 + - &ref_4 + id: DepositsUnsubscribeResponse + title: Deposits unsubscribe response + description: Deposits unsubscribe response + type: send + messages: + - &ref_9 + id: UnsubscribeResponse + contentType: application/json + payload: + - name: Unsubscribe Response + description: Response to deposits unsubscribe request + type: object + properties: + - name: id + type: integer + description: Correlation ID for request-response matching + required: false + - name: data + type: array + title: Subscribe Response + required: true + properties: + - name: item + type: object + required: false + properties: + - name: status + type: string + enumValues: + - ok + required: true + - name: status + type: string + enumValues: + - err + required: true + - name: error + type: string + description: >- + Error identifier. For domain rejections and transport + errors (`401`/`404`/`429`/`500`) this is a stable, + machine-readable snake_case identifier that is part of + the API contract and safe to branch on, e.g. + `insufficient_margin`, `insufficient_balance`, + `order_not_found`, `reduce_only_invalid`, + `unauthorized`, `not_found`. For `400` it is a + human-readable validation detail whose wording may + change. See the Error handling guide for the domain + identifiers. (Post-only / Fill-or-Kill outcomes are + order statuses such as `post_only_rejected`, not + rejections.) + required: true + headers: [] + jsonPayloadSchema: + type: object + title: Base Response + properties: + id: + type: integer + description: Correlation ID for request-response matching + x-parser-schema-id: + data: + title: Subscribe Response + type: array + items: + oneOf: + - type: object + required: + - status + properties: + status: + type: string + enum: + - ok + x-parser-schema-id: + x-parser-schema-id: + - type: object + required: + - status + - error + properties: + status: + type: string + enum: + - err + x-parser-schema-id: + error: + type: string + description: >- + Error identifier. For domain rejections and transport + errors (`401`/`404`/`429`/`500`) this is a stable, + machine-readable snake_case identifier that is part of + the API contract and safe to branch on, e.g. + `insufficient_margin`, `insufficient_balance`, + `order_not_found`, `reduce_only_invalid`, + `unauthorized`, `not_found`. For `400` it is a + human-readable validation detail whose wording may + change. See the Error handling guide for the domain + identifiers. (Post-only / Fill-or-Kill outcomes are + order statuses such as `post_only_rejected`, not + rejections.) + example: insufficient_margin + x-parser-schema-id: + x-parser-schema-id: + x-parser-schema-id: + x-parser-schema-id: + required: + - data + x-parser-schema-id: + title: Unsubscribe Response + description: Response to deposits unsubscribe request + example: |- + { + "data": [] + } + bindings: [] + extensions: + - id: x-parser-unique-object-id + value: UnsubscribeResponse + bindings: [] + extensions: *ref_0 + - &ref_5 + id: DepositsUpdate + title: Deposits update + description: Receive deposit updates + type: send + messages: + - &ref_10 + id: Update + contentType: application/json + payload: + - name: Update + description: Deposit status updates for authenticated users + type: object + properties: + - name: ch + type: string + description: >- + Channel name for push data. Parameterized channels include the + instrument ID (e.g. "trades::1", "book::1", "klines::1::1m", + "tickers::all"). Private channels use plain names (e.g. + "fills", "orders"). + required: true + - name: ts + type: integer + description: >- + Request timestamp. Unix milliseconds for most operations; Unix + seconds for withdrawals (must match the on-chain EIP-712 + struct verified against block.timestamp). + required: true + - name: sq + type: integer + description: Sequence number + required: true + - name: data + type: object + description: Array of deposit objects + required: true + properties: + - name: hash + type: string + description: On-chain transaction hash, "0x" if not yet mined + required: true + - name: asset + type: string + description: Asset name + required: true + - name: amount + type: string + description: >- + Raw token amount including decimals. For withdrawals this + matches the uint256 amount in the EIP-712 signature (e.g. + "100000000" for 100 USDC with 6 decimals). + required: true + - name: status + type: string + description: Deposit status + enumValues: + - pending + - confirmed + - removed + required: true + headers: [] + jsonPayloadSchema: + title: Deposits Update + type: object + properties: + ch: + type: string + description: >- + Channel name for push data. Parameterized channels include the + instrument ID (e.g. "trades::1", "book::1", "klines::1::1m", + "tickers::all"). Private channels use plain names (e.g. "fills", + "orders"). + example: trades::1 + x-parser-schema-id: + ts: + type: integer + description: >- + Request timestamp. Unix milliseconds for most operations; Unix + seconds for withdrawals (must match the on-chain EIP-712 struct + verified against block.timestamp). + example: 1767225600000 + x-parser-schema-id: + sq: + type: integer + description: Sequence number + example: 1234567890 + x-parser-schema-id: + data: + type: object + description: Array of deposit objects + properties: + hash: + type: string + description: On-chain transaction hash, "0x" if not yet mined + default: 0x + example: >- + 0x1234567890abcdef1234567890abcdef1234567890abcdef1234567890abcdef + x-parser-schema-id: + asset: + type: string + description: Asset name + example: USDC + x-parser-schema-id: + amount: + type: string + description: >- + Raw token amount including decimals. For withdrawals this + matches the uint256 amount in the EIP-712 signature (e.g. + "100000000" for 100 USDC with 6 decimals). + example: '100000000' + x-parser-schema-id: + status: + type: string + description: Deposit status + enum: + - pending + - confirmed + - removed + x-parser-schema-id: + required: + - hash + - asset + - amount + - status + x-parser-schema-id: + required: + - ch + - ts + - sq + - data + x-parser-schema-id: + title: Update + description: Deposit status updates for authenticated users + example: |- + { + "ch": "deposits", + "ts": 1767225600000, + "sq": 1234567890, + "data": [ + { + "hash": "0x1234567890abcdef1234567890abcdef1234567890abcdef1234567890abcdef", + "asset": "USDC", + "amount": "100000000", + "status": "pending" + } + ] + } + bindings: [] + extensions: + - id: x-parser-unique-object-id + value: Update + bindings: [] + extensions: *ref_0 +sendOperations: + - *ref_1 + - *ref_2 +receiveOperations: + - *ref_3 + - *ref_4 + - *ref_5 +sendMessages: + - *ref_6 + - *ref_7 +receiveMessages: + - *ref_8 + - *ref_9 + - *ref_10 +extensions: + - id: x-parser-unique-object-id + value: deposits +securitySchemes: [] + +```` \ No newline at end of file diff --git a/PolymarketDocumentation-main/docs/api-reference/wss/perps-fills.md b/PolymarketDocumentation-main/docs/api-reference/wss/perps-fills.md new file mode 100644 index 00000000..3f1b35e0 --- /dev/null +++ b/PolymarketDocumentation-main/docs/api-reference/wss/perps-fills.md @@ -0,0 +1,727 @@ +> ## Documentation Index +> Fetch the complete documentation index at: https://docs.polymarket.com/llms.txt +> Use this file to discover all available pages before exploring further. + +# Fills + +> Perps WebSocket private fill updates. + + + +## AsyncAPI + +````yaml asyncapi-perps.json fills +id: fills +title: Fills +description: Real-time fill updates. Requires authentication, see [Auth](/ws/auth). +servers: + - id: production + protocol: wss + host: ws.perpetuals.polymarket.com + bindings: [] + variables: [] +address: /v1/ws +parameters: [] +bindings: [] +operations: + - &ref_1 + id: FillsSubscribe + title: Fills subscribe + description: Subscribe to fills + type: receive + messages: + - &ref_6 + id: SubscribeRequest + contentType: application/json + payload: + - name: Subscribe + description: Subscribe to private fill updates (requires prior auth) + type: object + properties: + - name: id + type: integer + description: Correlation ID for request-response matching + required: false + - name: req + type: string + description: Request type + enumValues: + - post + - sub + - unsub + required: true + - name: chs + type: array + description: 'Fills private channel: "fills"' + required: true + properties: + - name: item + type: string + enumValues: + - fills + required: false + headers: [] + jsonPayloadSchema: + type: object + title: Base Request + properties: + id: + type: integer + description: Correlation ID for request-response matching + x-parser-schema-id: + req: + type: string + description: Request type + enum: + - post + - sub + - unsub + x-parser-schema-id: + chs: + type: array + description: 'Fills private channel: "fills"' + items: + type: string + enum: + - fills + x-parser-schema-id: + example: + - fills + x-parser-schema-id: + required: + - req + - chs + x-parser-schema-id: + title: Subscribe + description: Subscribe to private fill updates (requires prior auth) + example: |- + { + "req": "sub", + "chs": [ + "fills" + ] + } + bindings: [] + extensions: + - id: x-parser-unique-object-id + value: SubscribeRequest + bindings: [] + extensions: &ref_0 + - id: x-parser-unique-object-id + value: fills + - &ref_3 + id: FillsSubscribeResponse + title: Fills subscribe response + description: Fills subscribe response + type: send + messages: + - &ref_8 + id: SubscribeResponse + contentType: application/json + payload: + - name: Subscribe Response + description: Response to fills subscribe request + type: object + properties: + - name: id + type: integer + description: Correlation ID for request-response matching + required: false + - name: data + type: array + title: Subscribe Response + required: true + properties: + - name: item + type: object + required: false + properties: + - name: status + type: string + enumValues: + - ok + required: true + - name: status + type: string + enumValues: + - err + required: true + - name: error + type: string + description: >- + Error identifier. For domain rejections and transport + errors (`401`/`404`/`429`/`500`) this is a stable, + machine-readable snake_case identifier that is part of + the API contract and safe to branch on, e.g. + `insufficient_margin`, `insufficient_balance`, + `order_not_found`, `reduce_only_invalid`, + `unauthorized`, `not_found`. For `400` it is a + human-readable validation detail whose wording may + change. See the Error handling guide for the domain + identifiers. (Post-only / Fill-or-Kill outcomes are + order statuses such as `post_only_rejected`, not + rejections.) + required: true + headers: [] + jsonPayloadSchema: + type: object + title: Base Response + properties: + id: + type: integer + description: Correlation ID for request-response matching + x-parser-schema-id: + data: + title: Subscribe Response + type: array + items: + oneOf: + - type: object + required: + - status + properties: + status: + type: string + enum: + - ok + x-parser-schema-id: + x-parser-schema-id: + - type: object + required: + - status + - error + properties: + status: + type: string + enum: + - err + x-parser-schema-id: + error: + type: string + description: >- + Error identifier. For domain rejections and transport + errors (`401`/`404`/`429`/`500`) this is a stable, + machine-readable snake_case identifier that is part of + the API contract and safe to branch on, e.g. + `insufficient_margin`, `insufficient_balance`, + `order_not_found`, `reduce_only_invalid`, + `unauthorized`, `not_found`. For `400` it is a + human-readable validation detail whose wording may + change. See the Error handling guide for the domain + identifiers. (Post-only / Fill-or-Kill outcomes are + order statuses such as `post_only_rejected`, not + rejections.) + example: insufficient_margin + x-parser-schema-id: + x-parser-schema-id: + x-parser-schema-id: + x-parser-schema-id: + required: + - data + x-parser-schema-id: + title: Subscribe Response + description: Response to fills subscribe request + example: |- + { + "data": [] + } + bindings: [] + extensions: + - id: x-parser-unique-object-id + value: SubscribeResponse + bindings: [] + extensions: *ref_0 + - &ref_2 + id: FillsUnsubscribe + title: Fills unsubscribe + description: Unsubscribe from fills + type: receive + messages: + - &ref_7 + id: UnsubscribeRequest + contentType: application/json + payload: + - name: Unsubscribe + description: Unsubscribe from private fill updates + type: object + properties: + - name: id + type: integer + description: Correlation ID for request-response matching + required: false + - name: req + type: string + description: Request type + enumValues: + - post + - sub + - unsub + required: true + - name: chs + type: array + description: 'Fills private channel: "fills"' + required: true + properties: + - name: item + type: string + enumValues: + - fills + required: false + headers: [] + jsonPayloadSchema: + type: object + title: Base Request + properties: + id: + type: integer + description: Correlation ID for request-response matching + x-parser-schema-id: + req: + type: string + description: Request type + enum: + - post + - sub + - unsub + x-parser-schema-id: + chs: + type: array + description: 'Fills private channel: "fills"' + items: + type: string + enum: + - fills + x-parser-schema-id: + example: + - fills + x-parser-schema-id: + required: + - req + - chs + x-parser-schema-id: + title: Unsubscribe + description: Unsubscribe from private fill updates + example: |- + { + "req": "unsub", + "chs": [ + "fills" + ] + } + bindings: [] + extensions: + - id: x-parser-unique-object-id + value: UnsubscribeRequest + bindings: [] + extensions: *ref_0 + - &ref_4 + id: FillsUnsubscribeResponse + title: Fills unsubscribe response + description: Fills unsubscribe response + type: send + messages: + - &ref_9 + id: UnsubscribeResponse + contentType: application/json + payload: + - name: Unsubscribe Response + description: Response to fills unsubscribe request + type: object + properties: + - name: id + type: integer + description: Correlation ID for request-response matching + required: false + - name: data + type: array + title: Subscribe Response + required: true + properties: + - name: item + type: object + required: false + properties: + - name: status + type: string + enumValues: + - ok + required: true + - name: status + type: string + enumValues: + - err + required: true + - name: error + type: string + description: >- + Error identifier. For domain rejections and transport + errors (`401`/`404`/`429`/`500`) this is a stable, + machine-readable snake_case identifier that is part of + the API contract and safe to branch on, e.g. + `insufficient_margin`, `insufficient_balance`, + `order_not_found`, `reduce_only_invalid`, + `unauthorized`, `not_found`. For `400` it is a + human-readable validation detail whose wording may + change. See the Error handling guide for the domain + identifiers. (Post-only / Fill-or-Kill outcomes are + order statuses such as `post_only_rejected`, not + rejections.) + required: true + headers: [] + jsonPayloadSchema: + type: object + title: Base Response + properties: + id: + type: integer + description: Correlation ID for request-response matching + x-parser-schema-id: + data: + title: Subscribe Response + type: array + items: + oneOf: + - type: object + required: + - status + properties: + status: + type: string + enum: + - ok + x-parser-schema-id: + x-parser-schema-id: + - type: object + required: + - status + - error + properties: + status: + type: string + enum: + - err + x-parser-schema-id: + error: + type: string + description: >- + Error identifier. For domain rejections and transport + errors (`401`/`404`/`429`/`500`) this is a stable, + machine-readable snake_case identifier that is part of + the API contract and safe to branch on, e.g. + `insufficient_margin`, `insufficient_balance`, + `order_not_found`, `reduce_only_invalid`, + `unauthorized`, `not_found`. For `400` it is a + human-readable validation detail whose wording may + change. See the Error handling guide for the domain + identifiers. (Post-only / Fill-or-Kill outcomes are + order statuses such as `post_only_rejected`, not + rejections.) + example: insufficient_margin + x-parser-schema-id: + x-parser-schema-id: + x-parser-schema-id: + x-parser-schema-id: + required: + - data + x-parser-schema-id: + title: Unsubscribe Response + description: Response to fills unsubscribe request + example: |- + { + "data": [] + } + bindings: [] + extensions: + - id: x-parser-unique-object-id + value: UnsubscribeResponse + bindings: [] + extensions: *ref_0 + - &ref_5 + id: FillsUpdate + title: Fills update + description: Receive fill updates + type: send + messages: + - &ref_10 + id: Update + contentType: application/json + payload: + - name: Update + description: Real-time fill updates for authenticated users + type: object + properties: + - name: ch + type: string + description: >- + Channel name for push data. Parameterized channels include the + instrument ID (e.g. "trades::1", "book::1", "klines::1::1m", + "tickers::all"). Private channels use plain names (e.g. + "fills", "orders"). + required: true + - name: ts + type: integer + description: >- + Request timestamp. Unix milliseconds for most operations; Unix + seconds for withdrawals (must match the on-chain EIP-712 + struct verified against block.timestamp). + required: true + - name: sq + type: integer + description: Sequence number + required: true + - name: data + type: object + description: Array of fill objects + required: true + properties: + - name: tid + type: integer + description: Trade ID + required: true + - name: oid + type: integer + description: Order ID + required: true + - name: iid + type: integer + description: Instrument ID + required: true + - name: side + type: string + description: Side + enumValues: + - long + - short + required: true + - name: p + type: string + description: Price + required: true + - name: qty + type: string + description: Quantity in no. of contracts + required: true + - name: taker + type: boolean + description: Whether this side was the taker + required: true + - name: fee + type: string + description: Fee amount for this trade side + required: true + - name: fea + type: string + description: Fee asset name + required: true + - name: psz + type: string + description: Position size before the fill + required: true + - name: pep + type: string + description: Position entry price before the fill + required: true + - name: pnl + type: string + description: PnL in USD + required: true + - name: liq + type: boolean + description: Whether the fill was a liquidation + required: true + - name: ts + type: integer + description: >- + Request timestamp. Unix milliseconds for most operations; + Unix seconds for withdrawals (must match the on-chain + EIP-712 struct verified against block.timestamp). + required: true + - name: coid + type: string + description: Client order ID + required: false + headers: [] + jsonPayloadSchema: + title: Fills Update + type: object + properties: + ch: + type: string + description: >- + Channel name for push data. Parameterized channels include the + instrument ID (e.g. "trades::1", "book::1", "klines::1::1m", + "tickers::all"). Private channels use plain names (e.g. "fills", + "orders"). + example: trades::1 + x-parser-schema-id: + ts: + type: integer + description: >- + Request timestamp. Unix milliseconds for most operations; Unix + seconds for withdrawals (must match the on-chain EIP-712 struct + verified against block.timestamp). + example: 1767225600000 + x-parser-schema-id: + sq: + type: integer + description: Sequence number + example: 1234567890 + x-parser-schema-id: + data: + type: object + description: Array of fill objects + properties: + tid: + type: integer + description: Trade ID + example: 1 + x-parser-schema-id: + oid: + type: integer + description: Order ID + example: 1234567890 + x-parser-schema-id: + iid: + type: integer + description: Instrument ID + example: 1 + x-parser-schema-id: + side: + type: string + description: Side + enum: + - long + - short + x-parser-schema-id: + p: + type: string + description: Price + example: '100.00' + x-parser-schema-id: + qty: + type: string + description: Quantity in no. of contracts + example: '10.00' + x-parser-schema-id: + taker: + type: boolean + description: Whether this side was the taker + x-parser-schema-id: + fee: + type: string + description: Fee amount for this trade side + example: '1.25' + x-parser-schema-id: + fea: + type: string + description: Fee asset name + example: USDC + x-parser-schema-id: + psz: + type: string + description: Position size before the fill + example: '26.86' + x-parser-schema-id: + pep: + type: string + description: Position entry price before the fill + example: '100.00' + x-parser-schema-id: + pnl: + type: string + description: PnL in USD + example: '100.00' + x-parser-schema-id: + liq: + type: boolean + description: Whether the fill was a liquidation + x-parser-schema-id: + ts: + type: integer + description: >- + Request timestamp. Unix milliseconds for most operations; + Unix seconds for withdrawals (must match the on-chain + EIP-712 struct verified against block.timestamp). + example: 1767225600000 + x-parser-schema-id: + coid: + type: string + description: Client order ID + minLength: 32 + maxLength: 32 + pattern: ^[0-9a-f]{32}$ + example: 550e8400e29b41d4a716446655440000 + x-parser-schema-id: + required: + - tid + - oid + - iid + - side + - p + - qty + - taker + - fee + - fea + - psz + - pep + - pnl + - ts + - liq + x-parser-schema-id: + required: + - ch + - ts + - sq + - data + x-parser-schema-id: + title: Update + description: Real-time fill updates for authenticated users + example: |- + { + "ch": "fills", + "ts": 1767225600000, + "sq": 1234567890, + "data": [ + { + "tid": 1, + "oid": 1234567890, + "iid": 1, + "side": "long", + "p": "100.00", + "qty": "10.00", + "fee": "1.25", + "fea": "USDC", + "psz": "26.86", + "pep": "100.00", + "pnl": "100.00", + "ts": 1767225600000, + "coid": "550e8400e29b41d4a716446655440000" + } + ] + } + bindings: [] + extensions: + - id: x-parser-unique-object-id + value: Update + bindings: [] + extensions: *ref_0 +sendOperations: + - *ref_1 + - *ref_2 +receiveOperations: + - *ref_3 + - *ref_4 + - *ref_5 +sendMessages: + - *ref_6 + - *ref_7 +receiveMessages: + - *ref_8 + - *ref_9 + - *ref_10 +extensions: + - id: x-parser-unique-object-id + value: fills +securitySchemes: [] + +```` \ No newline at end of file diff --git a/PolymarketDocumentation-main/docs/api-reference/wss/perps-funding.md b/PolymarketDocumentation-main/docs/api-reference/wss/perps-funding.md new file mode 100644 index 00000000..857173ab --- /dev/null +++ b/PolymarketDocumentation-main/docs/api-reference/wss/perps-funding.md @@ -0,0 +1,631 @@ +> ## Documentation Index +> Fetch the complete documentation index at: https://docs.polymarket.com/llms.txt +> Use this file to discover all available pages before exploring further. + +# Funding + +> Perps WebSocket private funding updates. + + + +## AsyncAPI + +````yaml asyncapi-perps.json funding +id: funding +title: Funding +description: >- + Real-time funding payment updates. Requires authentication, see + [Auth](/ws/auth). +servers: + - id: production + protocol: wss + host: ws.perpetuals.polymarket.com + bindings: [] + variables: [] +address: /v1/ws +parameters: [] +bindings: [] +operations: + - &ref_1 + id: FundingSubscribe + title: Funding subscribe + description: Subscribe to funding + type: receive + messages: + - &ref_6 + id: SubscribeRequest + contentType: application/json + payload: + - name: Subscribe + description: Subscribe to private funding payment updates (requires prior auth) + type: object + properties: + - name: id + type: integer + description: Correlation ID for request-response matching + required: false + - name: req + type: string + description: Request type + enumValues: + - post + - sub + - unsub + required: true + - name: chs + type: array + description: 'Funding private channel: "funding"' + required: true + properties: + - name: item + type: string + enumValues: + - funding + required: false + headers: [] + jsonPayloadSchema: + type: object + title: Base Request + properties: + id: + type: integer + description: Correlation ID for request-response matching + x-parser-schema-id: + req: + type: string + description: Request type + enum: + - post + - sub + - unsub + x-parser-schema-id: + chs: + type: array + description: 'Funding private channel: "funding"' + items: + type: string + enum: + - funding + x-parser-schema-id: + example: + - funding + x-parser-schema-id: + required: + - req + - chs + x-parser-schema-id: + title: Subscribe + description: Subscribe to private funding payment updates (requires prior auth) + example: |- + { + "req": "sub", + "chs": [ + "funding" + ] + } + bindings: [] + extensions: + - id: x-parser-unique-object-id + value: SubscribeRequest + bindings: [] + extensions: &ref_0 + - id: x-parser-unique-object-id + value: funding + - &ref_3 + id: FundingSubscribeResponse + title: Funding subscribe response + description: Funding subscribe response + type: send + messages: + - &ref_8 + id: SubscribeResponse + contentType: application/json + payload: + - name: Subscribe Response + description: Response to funding subscribe request + type: object + properties: + - name: id + type: integer + description: Correlation ID for request-response matching + required: false + - name: data + type: array + title: Subscribe Response + required: true + properties: + - name: item + type: object + required: false + properties: + - name: status + type: string + enumValues: + - ok + required: true + - name: status + type: string + enumValues: + - err + required: true + - name: error + type: string + description: >- + Error identifier. For domain rejections and transport + errors (`401`/`404`/`429`/`500`) this is a stable, + machine-readable snake_case identifier that is part of + the API contract and safe to branch on, e.g. + `insufficient_margin`, `insufficient_balance`, + `order_not_found`, `reduce_only_invalid`, + `unauthorized`, `not_found`. For `400` it is a + human-readable validation detail whose wording may + change. See the Error handling guide for the domain + identifiers. (Post-only / Fill-or-Kill outcomes are + order statuses such as `post_only_rejected`, not + rejections.) + required: true + headers: [] + jsonPayloadSchema: + type: object + title: Base Response + properties: + id: + type: integer + description: Correlation ID for request-response matching + x-parser-schema-id: + data: + title: Subscribe Response + type: array + items: + oneOf: + - type: object + required: + - status + properties: + status: + type: string + enum: + - ok + x-parser-schema-id: + x-parser-schema-id: + - type: object + required: + - status + - error + properties: + status: + type: string + enum: + - err + x-parser-schema-id: + error: + type: string + description: >- + Error identifier. For domain rejections and transport + errors (`401`/`404`/`429`/`500`) this is a stable, + machine-readable snake_case identifier that is part of + the API contract and safe to branch on, e.g. + `insufficient_margin`, `insufficient_balance`, + `order_not_found`, `reduce_only_invalid`, + `unauthorized`, `not_found`. For `400` it is a + human-readable validation detail whose wording may + change. See the Error handling guide for the domain + identifiers. (Post-only / Fill-or-Kill outcomes are + order statuses such as `post_only_rejected`, not + rejections.) + example: insufficient_margin + x-parser-schema-id: + x-parser-schema-id: + x-parser-schema-id: + x-parser-schema-id: + required: + - data + x-parser-schema-id: + title: Subscribe Response + description: Response to funding subscribe request + example: |- + { + "data": [] + } + bindings: [] + extensions: + - id: x-parser-unique-object-id + value: SubscribeResponse + bindings: [] + extensions: *ref_0 + - &ref_2 + id: FundingUnsubscribe + title: Funding unsubscribe + description: Unsubscribe from funding + type: receive + messages: + - &ref_7 + id: UnsubscribeRequest + contentType: application/json + payload: + - name: Unsubscribe + description: Unsubscribe from private funding updates + type: object + properties: + - name: id + type: integer + description: Correlation ID for request-response matching + required: false + - name: req + type: string + description: Request type + enumValues: + - post + - sub + - unsub + required: true + - name: chs + type: array + description: 'Funding private channel: "funding"' + required: true + properties: + - name: item + type: string + enumValues: + - funding + required: false + headers: [] + jsonPayloadSchema: + type: object + title: Base Request + properties: + id: + type: integer + description: Correlation ID for request-response matching + x-parser-schema-id: + req: + type: string + description: Request type + enum: + - post + - sub + - unsub + x-parser-schema-id: + chs: + type: array + description: 'Funding private channel: "funding"' + items: + type: string + enum: + - funding + x-parser-schema-id: + example: + - funding + x-parser-schema-id: + required: + - req + - chs + x-parser-schema-id: + title: Unsubscribe + description: Unsubscribe from private funding updates + example: |- + { + "req": "unsub", + "chs": [ + "funding" + ] + } + bindings: [] + extensions: + - id: x-parser-unique-object-id + value: UnsubscribeRequest + bindings: [] + extensions: *ref_0 + - &ref_4 + id: FundingUnsubscribeResponse + title: Funding unsubscribe response + description: Funding unsubscribe response + type: send + messages: + - &ref_9 + id: UnsubscribeResponse + contentType: application/json + payload: + - name: Unsubscribe Response + description: Response to funding unsubscribe request + type: object + properties: + - name: id + type: integer + description: Correlation ID for request-response matching + required: false + - name: data + type: array + title: Subscribe Response + required: true + properties: + - name: item + type: object + required: false + properties: + - name: status + type: string + enumValues: + - ok + required: true + - name: status + type: string + enumValues: + - err + required: true + - name: error + type: string + description: >- + Error identifier. For domain rejections and transport + errors (`401`/`404`/`429`/`500`) this is a stable, + machine-readable snake_case identifier that is part of + the API contract and safe to branch on, e.g. + `insufficient_margin`, `insufficient_balance`, + `order_not_found`, `reduce_only_invalid`, + `unauthorized`, `not_found`. For `400` it is a + human-readable validation detail whose wording may + change. See the Error handling guide for the domain + identifiers. (Post-only / Fill-or-Kill outcomes are + order statuses such as `post_only_rejected`, not + rejections.) + required: true + headers: [] + jsonPayloadSchema: + type: object + title: Base Response + properties: + id: + type: integer + description: Correlation ID for request-response matching + x-parser-schema-id: + data: + title: Subscribe Response + type: array + items: + oneOf: + - type: object + required: + - status + properties: + status: + type: string + enum: + - ok + x-parser-schema-id: + x-parser-schema-id: + - type: object + required: + - status + - error + properties: + status: + type: string + enum: + - err + x-parser-schema-id: + error: + type: string + description: >- + Error identifier. For domain rejections and transport + errors (`401`/`404`/`429`/`500`) this is a stable, + machine-readable snake_case identifier that is part of + the API contract and safe to branch on, e.g. + `insufficient_margin`, `insufficient_balance`, + `order_not_found`, `reduce_only_invalid`, + `unauthorized`, `not_found`. For `400` it is a + human-readable validation detail whose wording may + change. See the Error handling guide for the domain + identifiers. (Post-only / Fill-or-Kill outcomes are + order statuses such as `post_only_rejected`, not + rejections.) + example: insufficient_margin + x-parser-schema-id: + x-parser-schema-id: + x-parser-schema-id: + x-parser-schema-id: + required: + - data + x-parser-schema-id: + title: Unsubscribe Response + description: Response to funding unsubscribe request + example: |- + { + "data": [] + } + bindings: [] + extensions: + - id: x-parser-unique-object-id + value: UnsubscribeResponse + bindings: [] + extensions: *ref_0 + - &ref_5 + id: FundingUpdate + title: Funding update + description: Receive funding updates + type: send + messages: + - &ref_10 + id: Update + contentType: application/json + payload: + - name: Update + description: Real-time funding payment updates for authenticated users + type: object + properties: + - name: ch + type: string + description: >- + Channel name for push data. Parameterized channels include the + instrument ID (e.g. "trades::1", "book::1", "klines::1::1m", + "tickers::all"). Private channels use plain names (e.g. + "fills", "orders"). + required: true + - name: ts + type: integer + description: >- + Request timestamp. Unix milliseconds for most operations; Unix + seconds for withdrawals (must match the on-chain EIP-712 + struct verified against block.timestamp). + required: true + - name: sq + type: integer + description: Sequence number + required: true + - name: data + type: object + description: Array of funding objects + required: true + properties: + - name: iid + type: integer + description: Instrument ID + required: true + - name: sz + type: string + description: >- + Signed position size in no. of contracts (positive = long, + negative = short) + required: true + - name: fr + type: string + description: Funding rate + required: true + - name: fund + type: string + description: Funding paid in USD + required: true + - name: fua + type: string + description: Funding asset name + required: true + - name: ts + type: integer + description: >- + Request timestamp. Unix milliseconds for most operations; + Unix seconds for withdrawals (must match the on-chain + EIP-712 struct verified against block.timestamp). + required: true + headers: [] + jsonPayloadSchema: + title: Funding Update + type: object + properties: + ch: + type: string + description: >- + Channel name for push data. Parameterized channels include the + instrument ID (e.g. "trades::1", "book::1", "klines::1::1m", + "tickers::all"). Private channels use plain names (e.g. "fills", + "orders"). + example: trades::1 + x-parser-schema-id: + ts: + type: integer + description: >- + Request timestamp. Unix milliseconds for most operations; Unix + seconds for withdrawals (must match the on-chain EIP-712 struct + verified against block.timestamp). + example: 1767225600000 + x-parser-schema-id: + sq: + type: integer + description: Sequence number + example: 1234567890 + x-parser-schema-id: + data: + type: object + description: Array of funding objects + properties: + iid: + type: integer + description: Instrument ID + example: 1 + x-parser-schema-id: + sz: + type: string + description: >- + Signed position size in no. of contracts (positive = long, + negative = short) + example: '10.00' + x-parser-schema-id: + fr: + type: string + description: Funding rate + example: '0.0001' + x-parser-schema-id: + fund: + type: string + description: Funding paid in USD + example: '1.00' + x-parser-schema-id: + fua: + type: string + description: Funding asset name + example: USDC + x-parser-schema-id: + ts: + type: integer + description: >- + Request timestamp. Unix milliseconds for most operations; + Unix seconds for withdrawals (must match the on-chain + EIP-712 struct verified against block.timestamp). + example: 1767225600000 + x-parser-schema-id: + required: + - iid + - sz + - fr + - fund + - fua + - ts + x-parser-schema-id: + required: + - ch + - ts + - sq + - data + x-parser-schema-id: + title: Update + description: Real-time funding payment updates for authenticated users + example: |- + { + "ch": "funding", + "ts": 1767225600000, + "sq": 1234567890, + "data": [ + { + "iid": 1, + "sz": "10.00", + "fr": "0.0001", + "fund": "1.00", + "fua": "USDC", + "ts": 1767225600000 + } + ] + } + bindings: [] + extensions: + - id: x-parser-unique-object-id + value: Update + bindings: [] + extensions: *ref_0 +sendOperations: + - *ref_1 + - *ref_2 +receiveOperations: + - *ref_3 + - *ref_4 + - *ref_5 +sendMessages: + - *ref_6 + - *ref_7 +receiveMessages: + - *ref_8 + - *ref_9 + - *ref_10 +extensions: + - id: x-parser-unique-object-id + value: funding +securitySchemes: [] + +```` \ No newline at end of file diff --git a/PolymarketDocumentation-main/docs/api-reference/wss/perps-klines.md b/PolymarketDocumentation-main/docs/api-reference/wss/perps-klines.md new file mode 100644 index 00000000..65f758a3 --- /dev/null +++ b/PolymarketDocumentation-main/docs/api-reference/wss/perps-klines.md @@ -0,0 +1,590 @@ +> ## Documentation Index +> Fetch the complete documentation index at: https://docs.polymarket.com/llms.txt +> Use this file to discover all available pages before exploring further. + +# Klines + +> Perps WebSocket candle updates. + + + +## AsyncAPI + +````yaml asyncapi-perps.json klines +id: klines +title: Klines +description: Real-time kline updates. +servers: + - id: production + protocol: wss + host: ws.perpetuals.polymarket.com + bindings: [] + variables: [] +address: /v1/ws +parameters: [] +bindings: [] +operations: + - &ref_1 + id: KlinesSubscribe + title: Klines subscribe + description: Subscribe to klines + type: receive + messages: + - &ref_6 + id: SubscribeRequest + contentType: application/json + payload: + - name: Subscribe + description: Subscribe to kline updates for an instrument and interval + type: object + properties: + - name: id + type: integer + description: Correlation ID for request-response matching + required: false + - name: req + type: string + description: Request type + enumValues: + - post + - sub + - unsub + required: true + - name: chs + type: array + description: >- + Klines subscription in format "klines::{iid}::{interval}" + (e.g., "klines::1::1m") + required: true + properties: + - name: item + type: string + required: false + headers: [] + jsonPayloadSchema: + type: object + title: Base Request + properties: + id: + type: integer + description: Correlation ID for request-response matching + x-parser-schema-id: + req: + type: string + description: Request type + enum: + - post + - sub + - unsub + x-parser-schema-id: + chs: + type: array + description: >- + Klines subscription in format "klines::{iid}::{interval}" (e.g., + "klines::1::1m") + items: + type: string + pattern: ^klines::\d+::(1m|5m|15m|30m|1h|4h|6h|12h|1d|1w)$ + x-parser-schema-id: + example: + - klines::1::1m + x-parser-schema-id: + required: + - req + - chs + x-parser-schema-id: + title: Subscribe + description: Subscribe to kline updates for an instrument and interval + example: |- + { + "req": "sub", + "chs": [ + "klines::1::1m" + ] + } + bindings: [] + extensions: + - id: x-parser-unique-object-id + value: SubscribeRequest + bindings: [] + extensions: &ref_0 + - id: x-parser-unique-object-id + value: klines + - &ref_3 + id: KlinesSubscribeResponse + title: Klines subscribe response + description: Klines subscribe response + type: send + messages: + - &ref_8 + id: SubscribeResponse + contentType: application/json + payload: + - name: Subscribe Response + description: Response to klines subscribe request + type: object + properties: + - name: id + type: integer + description: Correlation ID for request-response matching + required: false + - name: data + type: array + title: Subscribe Response + required: true + properties: + - name: item + type: object + required: false + properties: + - name: status + type: string + enumValues: + - ok + required: true + - name: status + type: string + enumValues: + - err + required: true + - name: error + type: string + description: >- + Error identifier. For domain rejections and transport + errors (`401`/`404`/`429`/`500`) this is a stable, + machine-readable snake_case identifier that is part of + the API contract and safe to branch on, e.g. + `insufficient_margin`, `insufficient_balance`, + `order_not_found`, `reduce_only_invalid`, + `unauthorized`, `not_found`. For `400` it is a + human-readable validation detail whose wording may + change. See the Error handling guide for the domain + identifiers. (Post-only / Fill-or-Kill outcomes are + order statuses such as `post_only_rejected`, not + rejections.) + required: true + headers: [] + jsonPayloadSchema: + type: object + title: Base Response + properties: + id: + type: integer + description: Correlation ID for request-response matching + x-parser-schema-id: + data: + title: Subscribe Response + type: array + items: + oneOf: + - type: object + required: + - status + properties: + status: + type: string + enum: + - ok + x-parser-schema-id: + x-parser-schema-id: + - type: object + required: + - status + - error + properties: + status: + type: string + enum: + - err + x-parser-schema-id: + error: + type: string + description: >- + Error identifier. For domain rejections and transport + errors (`401`/`404`/`429`/`500`) this is a stable, + machine-readable snake_case identifier that is part of + the API contract and safe to branch on, e.g. + `insufficient_margin`, `insufficient_balance`, + `order_not_found`, `reduce_only_invalid`, + `unauthorized`, `not_found`. For `400` it is a + human-readable validation detail whose wording may + change. See the Error handling guide for the domain + identifiers. (Post-only / Fill-or-Kill outcomes are + order statuses such as `post_only_rejected`, not + rejections.) + example: insufficient_margin + x-parser-schema-id: + x-parser-schema-id: + x-parser-schema-id: + x-parser-schema-id: + required: + - data + x-parser-schema-id: + title: Subscribe Response + description: Response to klines subscribe request + example: |- + { + "data": [] + } + bindings: [] + extensions: + - id: x-parser-unique-object-id + value: SubscribeResponse + bindings: [] + extensions: *ref_0 + - &ref_2 + id: KlinesUnsubscribe + title: Klines unsubscribe + description: Unsubscribe from klines + type: receive + messages: + - &ref_7 + id: UnsubscribeRequest + contentType: application/json + payload: + - name: Unsubscribe + description: Unsubscribe from kline updates + type: object + properties: + - name: id + type: integer + description: Correlation ID for request-response matching + required: false + - name: req + type: string + description: Request type + enumValues: + - post + - sub + - unsub + required: true + - name: chs + type: array + description: >- + Klines subscription in format "klines::{iid}::{interval}" + (e.g., "klines::1::1m") + required: true + properties: + - name: item + type: string + required: false + headers: [] + jsonPayloadSchema: + type: object + title: Base Request + properties: + id: + type: integer + description: Correlation ID for request-response matching + x-parser-schema-id: + req: + type: string + description: Request type + enum: + - post + - sub + - unsub + x-parser-schema-id: + chs: + type: array + description: >- + Klines subscription in format "klines::{iid}::{interval}" (e.g., + "klines::1::1m") + items: + type: string + pattern: ^klines::\d+::(1m|5m|15m|30m|1h|4h|6h|12h|1d|1w)$ + x-parser-schema-id: + example: + - klines::1::1m + x-parser-schema-id: + required: + - req + - chs + x-parser-schema-id: + title: Unsubscribe + description: Unsubscribe from kline updates + example: |- + { + "req": "unsub", + "chs": [ + "klines::1::1m" + ] + } + bindings: [] + extensions: + - id: x-parser-unique-object-id + value: UnsubscribeRequest + bindings: [] + extensions: *ref_0 + - &ref_4 + id: KlinesUnsubscribeResponse + title: Klines unsubscribe response + description: Klines unsubscribe response + type: send + messages: + - &ref_9 + id: UnsubscribeResponse + contentType: application/json + payload: + - name: Unsubscribe Response + description: Response to klines unsubscribe request + type: object + properties: + - name: id + type: integer + description: Correlation ID for request-response matching + required: false + - name: data + type: array + title: Subscribe Response + required: true + properties: + - name: item + type: object + required: false + properties: + - name: status + type: string + enumValues: + - ok + required: true + - name: status + type: string + enumValues: + - err + required: true + - name: error + type: string + description: >- + Error identifier. For domain rejections and transport + errors (`401`/`404`/`429`/`500`) this is a stable, + machine-readable snake_case identifier that is part of + the API contract and safe to branch on, e.g. + `insufficient_margin`, `insufficient_balance`, + `order_not_found`, `reduce_only_invalid`, + `unauthorized`, `not_found`. For `400` it is a + human-readable validation detail whose wording may + change. See the Error handling guide for the domain + identifiers. (Post-only / Fill-or-Kill outcomes are + order statuses such as `post_only_rejected`, not + rejections.) + required: true + headers: [] + jsonPayloadSchema: + type: object + title: Base Response + properties: + id: + type: integer + description: Correlation ID for request-response matching + x-parser-schema-id: + data: + title: Subscribe Response + type: array + items: + oneOf: + - type: object + required: + - status + properties: + status: + type: string + enum: + - ok + x-parser-schema-id: + x-parser-schema-id: + - type: object + required: + - status + - error + properties: + status: + type: string + enum: + - err + x-parser-schema-id: + error: + type: string + description: >- + Error identifier. For domain rejections and transport + errors (`401`/`404`/`429`/`500`) this is a stable, + machine-readable snake_case identifier that is part of + the API contract and safe to branch on, e.g. + `insufficient_margin`, `insufficient_balance`, + `order_not_found`, `reduce_only_invalid`, + `unauthorized`, `not_found`. For `400` it is a + human-readable validation detail whose wording may + change. See the Error handling guide for the domain + identifiers. (Post-only / Fill-or-Kill outcomes are + order statuses such as `post_only_rejected`, not + rejections.) + example: insufficient_margin + x-parser-schema-id: + x-parser-schema-id: + x-parser-schema-id: + x-parser-schema-id: + required: + - data + x-parser-schema-id: + title: Unsubscribe Response + description: Response to klines unsubscribe request + example: |- + { + "data": [] + } + bindings: [] + extensions: + - id: x-parser-unique-object-id + value: UnsubscribeResponse + bindings: [] + extensions: *ref_0 + - &ref_5 + id: KlinesUpdate + title: Klines update + description: Receive kline updates + type: send + messages: + - &ref_10 + id: Update + contentType: application/json + payload: + - name: Update + description: Real-time kline updates for subscribed instruments + type: object + properties: + - name: ch + type: string + description: >- + Channel name for push data. Parameterized channels include the + instrument ID (e.g. "trades::1", "book::1", "klines::1::1m", + "tickers::all"). Private channels use plain names (e.g. + "fills", "orders"). + required: true + - name: ts + type: integer + description: >- + Request timestamp. Unix milliseconds for most operations; Unix + seconds for withdrawals (must match the on-chain EIP-712 + struct verified against block.timestamp). + required: true + - name: sq + type: integer + description: Sequence number + required: true + - name: data + type: array + description: Array of kline arrays + required: true + properties: + - name: item + type: array + description: | + - `1767225600000` - Open time + - `"100.00"` - Open price + - `"105.00"` - High price + - `"99.00"` - Low price + - `"102.00"` - Close price + - `"500.00"` - Volume (base unit) + - `42` - Number of trades + required: false + headers: [] + jsonPayloadSchema: + title: Kline Update + type: object + properties: + ch: + type: string + description: >- + Channel name for push data. Parameterized channels include the + instrument ID (e.g. "trades::1", "book::1", "klines::1::1m", + "tickers::all"). Private channels use plain names (e.g. "fills", + "orders"). + example: trades::1 + x-parser-schema-id: + ts: + type: integer + description: >- + Request timestamp. Unix milliseconds for most operations; Unix + seconds for withdrawals (must match the on-chain EIP-712 struct + verified against block.timestamp). + example: 1767225600000 + x-parser-schema-id: + sq: + type: integer + description: Sequence number + example: 1234567890 + x-parser-schema-id: + data: + type: array + description: Array of kline arrays + items: + type: array + description: | + - `1767225600000` - Open time + - `"100.00"` - Open price + - `"105.00"` - High price + - `"99.00"` - Low price + - `"102.00"` - Close price + - `"500.00"` - Volume (base unit) + - `42` - Number of trades + example: + - 1767225600000 + - '100.00' + - '105.00' + - '99.00' + - '102.00' + - '500.00' + - 42 + x-parser-schema-id: + x-parser-schema-id: + required: + - ch + - ts + - sq + - data + x-parser-schema-id: + title: Update + description: Real-time kline updates for subscribed instruments + example: |- + { + "ch": "klines::1::1m", + "ts": 1767225600000, + "sq": 1234567890, + "data": [ + [ + 1767225600000, + "100.00", + "105.00", + "99.00", + "102.00", + "500.00", + 42 + ] + ] + } + bindings: [] + extensions: + - id: x-parser-unique-object-id + value: Update + bindings: [] + extensions: *ref_0 +sendOperations: + - *ref_1 + - *ref_2 +receiveOperations: + - *ref_3 + - *ref_4 + - *ref_5 +sendMessages: + - *ref_6 + - *ref_7 +receiveMessages: + - *ref_8 + - *ref_9 + - *ref_10 +extensions: + - id: x-parser-unique-object-id + value: klines +securitySchemes: [] + +```` \ No newline at end of file diff --git a/PolymarketDocumentation-main/docs/api-reference/wss/perps-orders.md b/PolymarketDocumentation-main/docs/api-reference/wss/perps-orders.md new file mode 100644 index 00000000..28d71d30 --- /dev/null +++ b/PolymarketDocumentation-main/docs/api-reference/wss/perps-orders.md @@ -0,0 +1,716 @@ +> ## Documentation Index +> Fetch the complete documentation index at: https://docs.polymarket.com/llms.txt +> Use this file to discover all available pages before exploring further. + +# Orders + +> Perps WebSocket private order updates. + + + +## AsyncAPI + +````yaml asyncapi-perps.json orders +id: orders +title: Orders +description: Real-time order updates. Requires authentication, see [Auth](/ws/auth). +servers: + - id: production + protocol: wss + host: ws.perpetuals.polymarket.com + bindings: [] + variables: [] +address: /v1/ws +parameters: [] +bindings: [] +operations: + - &ref_1 + id: OrdersSubscribe + title: Orders subscribe + description: Subscribe to orders + type: receive + messages: + - &ref_6 + id: SubscribeRequest + contentType: application/json + payload: + - name: Subscribe + description: Subscribe to private order updates (requires prior auth) + type: object + properties: + - name: id + type: integer + description: Correlation ID for request-response matching + required: false + - name: req + type: string + description: Request type + enumValues: + - post + - sub + - unsub + required: true + - name: chs + type: array + description: 'Orders private channel: "orders"' + required: true + properties: + - name: item + type: string + enumValues: + - orders + required: false + headers: [] + jsonPayloadSchema: + type: object + title: Base Request + properties: + id: + type: integer + description: Correlation ID for request-response matching + x-parser-schema-id: + req: + type: string + description: Request type + enum: + - post + - sub + - unsub + x-parser-schema-id: + chs: + type: array + description: 'Orders private channel: "orders"' + items: + type: string + enum: + - orders + x-parser-schema-id: + example: + - orders + x-parser-schema-id: + required: + - req + - chs + x-parser-schema-id: + title: Subscribe + description: Subscribe to private order updates (requires prior auth) + example: |- + { + "req": "sub", + "chs": [ + "orders" + ] + } + bindings: [] + extensions: + - id: x-parser-unique-object-id + value: SubscribeRequest + bindings: [] + extensions: &ref_0 + - id: x-parser-unique-object-id + value: orders + - &ref_3 + id: OrdersSubscribeResponse + title: Orders subscribe response + description: Orders subscribe response + type: send + messages: + - &ref_8 + id: SubscribeResponse + contentType: application/json + payload: + - name: Subscribe Response + description: Response to orders subscribe request + type: object + properties: + - name: id + type: integer + description: Correlation ID for request-response matching + required: false + - name: data + type: array + title: Subscribe Response + required: true + properties: + - name: item + type: object + required: false + properties: + - name: status + type: string + enumValues: + - ok + required: true + - name: status + type: string + enumValues: + - err + required: true + - name: error + type: string + description: >- + Error identifier. For domain rejections and transport + errors (`401`/`404`/`429`/`500`) this is a stable, + machine-readable snake_case identifier that is part of + the API contract and safe to branch on, e.g. + `insufficient_margin`, `insufficient_balance`, + `order_not_found`, `reduce_only_invalid`, + `unauthorized`, `not_found`. For `400` it is a + human-readable validation detail whose wording may + change. See the Error handling guide for the domain + identifiers. (Post-only / Fill-or-Kill outcomes are + order statuses such as `post_only_rejected`, not + rejections.) + required: true + headers: [] + jsonPayloadSchema: + type: object + title: Base Response + properties: + id: + type: integer + description: Correlation ID for request-response matching + x-parser-schema-id: + data: + title: Subscribe Response + type: array + items: + oneOf: + - type: object + required: + - status + properties: + status: + type: string + enum: + - ok + x-parser-schema-id: + x-parser-schema-id: + - type: object + required: + - status + - error + properties: + status: + type: string + enum: + - err + x-parser-schema-id: + error: + type: string + description: >- + Error identifier. For domain rejections and transport + errors (`401`/`404`/`429`/`500`) this is a stable, + machine-readable snake_case identifier that is part of + the API contract and safe to branch on, e.g. + `insufficient_margin`, `insufficient_balance`, + `order_not_found`, `reduce_only_invalid`, + `unauthorized`, `not_found`. For `400` it is a + human-readable validation detail whose wording may + change. See the Error handling guide for the domain + identifiers. (Post-only / Fill-or-Kill outcomes are + order statuses such as `post_only_rejected`, not + rejections.) + example: insufficient_margin + x-parser-schema-id: + x-parser-schema-id: + x-parser-schema-id: + x-parser-schema-id: + required: + - data + x-parser-schema-id: + title: Subscribe Response + description: Response to orders subscribe request + example: |- + { + "data": [] + } + bindings: [] + extensions: + - id: x-parser-unique-object-id + value: SubscribeResponse + bindings: [] + extensions: *ref_0 + - &ref_2 + id: OrdersUnsubscribe + title: Orders unsubscribe + description: Unsubscribe from orders + type: receive + messages: + - &ref_7 + id: UnsubscribeRequest + contentType: application/json + payload: + - name: Unsubscribe + description: Unsubscribe from private order updates + type: object + properties: + - name: id + type: integer + description: Correlation ID for request-response matching + required: false + - name: req + type: string + description: Request type + enumValues: + - post + - sub + - unsub + required: true + - name: chs + type: array + description: 'Orders private channel: "orders"' + required: true + properties: + - name: item + type: string + enumValues: + - orders + required: false + headers: [] + jsonPayloadSchema: + type: object + title: Base Request + properties: + id: + type: integer + description: Correlation ID for request-response matching + x-parser-schema-id: + req: + type: string + description: Request type + enum: + - post + - sub + - unsub + x-parser-schema-id: + chs: + type: array + description: 'Orders private channel: "orders"' + items: + type: string + enum: + - orders + x-parser-schema-id: + example: + - orders + x-parser-schema-id: + required: + - req + - chs + x-parser-schema-id: + title: Unsubscribe + description: Unsubscribe from private order updates + example: |- + { + "req": "unsub", + "chs": [ + "orders" + ] + } + bindings: [] + extensions: + - id: x-parser-unique-object-id + value: UnsubscribeRequest + bindings: [] + extensions: *ref_0 + - &ref_4 + id: OrdersUnsubscribeResponse + title: Orders unsubscribe response + description: Orders unsubscribe response + type: send + messages: + - &ref_9 + id: UnsubscribeResponse + contentType: application/json + payload: + - name: Unsubscribe Response + description: Response to orders unsubscribe request + type: object + properties: + - name: id + type: integer + description: Correlation ID for request-response matching + required: false + - name: data + type: array + title: Subscribe Response + required: true + properties: + - name: item + type: object + required: false + properties: + - name: status + type: string + enumValues: + - ok + required: true + - name: status + type: string + enumValues: + - err + required: true + - name: error + type: string + description: >- + Error identifier. For domain rejections and transport + errors (`401`/`404`/`429`/`500`) this is a stable, + machine-readable snake_case identifier that is part of + the API contract and safe to branch on, e.g. + `insufficient_margin`, `insufficient_balance`, + `order_not_found`, `reduce_only_invalid`, + `unauthorized`, `not_found`. For `400` it is a + human-readable validation detail whose wording may + change. See the Error handling guide for the domain + identifiers. (Post-only / Fill-or-Kill outcomes are + order statuses such as `post_only_rejected`, not + rejections.) + required: true + headers: [] + jsonPayloadSchema: + type: object + title: Base Response + properties: + id: + type: integer + description: Correlation ID for request-response matching + x-parser-schema-id: + data: + title: Subscribe Response + type: array + items: + oneOf: + - type: object + required: + - status + properties: + status: + type: string + enum: + - ok + x-parser-schema-id: + x-parser-schema-id: + - type: object + required: + - status + - error + properties: + status: + type: string + enum: + - err + x-parser-schema-id: + error: + type: string + description: >- + Error identifier. For domain rejections and transport + errors (`401`/`404`/`429`/`500`) this is a stable, + machine-readable snake_case identifier that is part of + the API contract and safe to branch on, e.g. + `insufficient_margin`, `insufficient_balance`, + `order_not_found`, `reduce_only_invalid`, + `unauthorized`, `not_found`. For `400` it is a + human-readable validation detail whose wording may + change. See the Error handling guide for the domain + identifiers. (Post-only / Fill-or-Kill outcomes are + order statuses such as `post_only_rejected`, not + rejections.) + example: insufficient_margin + x-parser-schema-id: + x-parser-schema-id: + x-parser-schema-id: + x-parser-schema-id: + required: + - data + x-parser-schema-id: + title: Unsubscribe Response + description: Response to orders unsubscribe request + example: |- + { + "data": [] + } + bindings: [] + extensions: + - id: x-parser-unique-object-id + value: UnsubscribeResponse + bindings: [] + extensions: *ref_0 + - &ref_5 + id: OrdersUpdate + title: Orders update + description: Receive order updates + type: send + messages: + - &ref_10 + id: Update + contentType: application/json + payload: + - name: Update + description: Real-time order updates for authenticated users + type: object + properties: + - name: ch + type: string + description: >- + Channel name for push data. Parameterized channels include the + instrument ID (e.g. "trades::1", "book::1", "klines::1::1m", + "tickers::all"). Private channels use plain names (e.g. + "fills", "orders"). + required: true + - name: ts + type: integer + description: >- + Request timestamp. Unix milliseconds for most operations; Unix + seconds for withdrawals (must match the on-chain EIP-712 + struct verified against block.timestamp). + required: true + - name: sq + type: integer + description: Sequence number + required: true + - name: data + type: object + description: Order object + required: true + properties: + - name: oid + type: integer + description: Order ID + required: true + - name: iid + type: integer + description: Instrument ID + required: true + - name: buy + type: boolean + description: Is buy + required: true + - name: p + type: string + description: Price + required: true + - name: qty + type: string + description: Quantity in no. of contracts + required: true + - name: tif + type: string + description: Time in force + enumValues: + - gtc + - ioc + - fok + required: true + - name: po + type: boolean + description: Post only + required: true + - name: ro + type: boolean + description: Reduce only + required: true + - name: rest + type: string + description: Resting quantity + required: true + - name: fill + type: string + description: Filled quantity + required: true + - name: cts + type: integer + description: Create timestamp in milliseconds + required: true + - name: uts + type: integer + description: Update timestamp in milliseconds + required: true + - name: status + type: string + description: Order status + required: true + - name: coid + type: string + description: Client order ID + required: false + headers: [] + jsonPayloadSchema: + title: Orders Update + type: object + properties: + ch: + type: string + description: >- + Channel name for push data. Parameterized channels include the + instrument ID (e.g. "trades::1", "book::1", "klines::1::1m", + "tickers::all"). Private channels use plain names (e.g. "fills", + "orders"). + example: trades::1 + x-parser-schema-id: + ts: + type: integer + description: >- + Request timestamp. Unix milliseconds for most operations; Unix + seconds for withdrawals (must match the on-chain EIP-712 struct + verified against block.timestamp). + example: 1767225600000 + x-parser-schema-id: + sq: + type: integer + description: Sequence number + example: 1234567890 + x-parser-schema-id: + data: + type: object + description: Order object + properties: + oid: + type: integer + description: Order ID + example: 1234567890 + x-parser-schema-id: + iid: + type: integer + description: Instrument ID + example: 1 + x-parser-schema-id: + buy: + type: boolean + description: Is buy + example: true + x-parser-schema-id: + p: + type: string + description: Price + example: '100.00' + x-parser-schema-id: + qty: + type: string + description: Quantity in no. of contracts + example: '10.00' + x-parser-schema-id: + tif: + type: string + description: Time in force + enum: + - gtc + - ioc + - fok + x-parser-schema-id: + po: + type: boolean + description: Post only + default: false + example: false + x-parser-schema-id: + ro: + type: boolean + description: Reduce only + example: false + default: false + x-parser-schema-id: + rest: + type: string + description: Resting quantity + example: '9.00' + x-parser-schema-id: + fill: + type: string + description: Filled quantity + example: '1.00' + x-parser-schema-id: + cts: + type: integer + description: Create timestamp in milliseconds + example: 1767225600000 + x-parser-schema-id: + uts: + type: integer + description: Update timestamp in milliseconds + example: 1767225600000 + x-parser-schema-id: + status: + type: string + description: Order status + example: open + x-parser-schema-id: + coid: + type: string + description: Client order ID + minLength: 32 + maxLength: 32 + pattern: ^[0-9a-f]{32}$ + example: 550e8400e29b41d4a716446655440000 + x-parser-schema-id: + required: + - oid + - iid + - buy + - p + - qty + - tif + - po + - ro + - status + - rest + - fill + - cts + - uts + x-parser-schema-id: + required: + - ch + - ts + - sq + - data + x-parser-schema-id: + title: Update + description: Real-time order updates for authenticated users + example: |- + { + "ch": "orders", + "ts": 1767225600000, + "sq": 1234567890, + "data": { + "oid": 1234567890, + "iid": 1, + "buy": true, + "p": "100.00", + "qty": "10.00", + "tif": "gtc", + "po": false, + "ro": false, + "rest": "9.00", + "fill": "1.00", + "cts": 1767225600000, + "uts": 1767225600000, + "status": "open", + "coid": "550e8400e29b41d4a716446655440000" + } + } + bindings: [] + extensions: + - id: x-parser-unique-object-id + value: Update + bindings: [] + extensions: *ref_0 +sendOperations: + - *ref_1 + - *ref_2 +receiveOperations: + - *ref_3 + - *ref_4 + - *ref_5 +sendMessages: + - *ref_6 + - *ref_7 +receiveMessages: + - *ref_8 + - *ref_9 + - *ref_10 +extensions: + - id: x-parser-unique-object-id + value: orders +securitySchemes: [] + +```` \ No newline at end of file diff --git a/PolymarketDocumentation-main/docs/api-reference/wss/perps-ping.md b/PolymarketDocumentation-main/docs/api-reference/wss/perps-ping.md new file mode 100644 index 00000000..69930253 --- /dev/null +++ b/PolymarketDocumentation-main/docs/api-reference/wss/perps-ping.md @@ -0,0 +1,222 @@ +> ## Documentation Index +> Fetch the complete documentation index at: https://docs.polymarket.com/llms.txt +> Use this file to discover all available pages before exploring further. + +# Ping + +> Perps WebSocket heartbeat. + + + +## AsyncAPI + +````yaml asyncapi-perps.json ping +id: ping +title: Ping +description: >- + Connections are automatically closed after 60 seconds of inactivity. Send a + ping message periodically to keep the connection alive. +servers: + - id: production + protocol: wss + host: ws.perpetuals.polymarket.com + bindings: [] + variables: [] +address: /v1/ws +parameters: [] +bindings: [] +operations: + - &ref_1 + id: PingSend + title: Ping send + description: Send ping + type: receive + messages: + - &ref_3 + id: Request + contentType: application/json + payload: + - name: Ping + description: Client sends ping to test connection and keep alive + type: object + properties: + - name: id + type: integer + description: Correlation ID for request-response matching + required: false + - name: req + type: string + description: Request type + enumValues: + - post + - sub + - unsub + required: true + - name: op + type: object + required: true + properties: + - name: type + type: string + enumValues: + - ping + required: true + headers: [] + jsonPayloadSchema: + type: object + title: Base Request + properties: + id: + type: integer + description: Correlation ID for request-response matching + x-parser-schema-id: + req: + type: string + description: Request type + enum: + - post + - sub + - unsub + x-parser-schema-id: + op: + type: object + required: + - type + properties: + type: + type: string + enum: + - ping + x-parser-schema-id: + x-parser-schema-id: + required: + - req + - op + x-parser-schema-id: + title: Ping + description: Client sends ping to test connection and keep alive + example: |- + { + "req": "post", + "op": { + "type": "ping" + } + } + bindings: [] + extensions: + - id: x-parser-unique-object-id + value: Request + bindings: [] + extensions: &ref_0 + - id: x-parser-unique-object-id + value: ping + - &ref_2 + id: PingReceive + title: Ping receive + description: Pong response + type: send + messages: + - &ref_4 + id: Response + contentType: application/json + payload: + - name: Pong + description: Server responds with pong including connection info + type: object + properties: + - name: id + type: integer + description: Correlation ID for request-response matching + required: false + - name: data + type: object + required: true + properties: + - name: status + type: string + description: Result status + enumValues: + - ok + - err + required: true + - name: ts + type: integer + description: >- + Request timestamp. Unix milliseconds for most operations; + Unix seconds for withdrawals (must match the on-chain + EIP-712 struct verified against block.timestamp). + required: true + - name: sq + type: integer + description: Sequence number + required: true + headers: [] + jsonPayloadSchema: + type: object + title: Base Response + properties: + id: + type: integer + description: Correlation ID for request-response matching + x-parser-schema-id: + data: + type: object + required: + - status + - ts + - sq + properties: + status: + type: string + enum: + - ok + - err + description: Result status + x-parser-schema-id: + ts: + type: integer + description: >- + Request timestamp. Unix milliseconds for most operations; + Unix seconds for withdrawals (must match the on-chain + EIP-712 struct verified against block.timestamp). + example: 1767225600000 + x-parser-schema-id: + sq: + type: integer + description: Sequence number + example: 1234567890 + x-parser-schema-id: + x-parser-schema-id: + required: + - data + x-parser-schema-id: + title: Pong + description: Server responds with pong including connection info + example: |- + { + "data": { + "status": "ok", + "ts": 1767225600000, + "sq": 1234567890 + } + } + bindings: [] + extensions: + - id: x-parser-unique-object-id + value: Response + bindings: [] + extensions: *ref_0 +sendOperations: + - *ref_1 +receiveOperations: + - *ref_2 +sendMessages: + - *ref_3 +receiveMessages: + - *ref_4 +extensions: + - id: x-parser-unique-object-id + value: ping +securitySchemes: [] + +```` \ No newline at end of file diff --git a/PolymarketDocumentation-main/docs/api-reference/wss/perps-place-orders.md b/PolymarketDocumentation-main/docs/api-reference/wss/perps-place-orders.md new file mode 100644 index 00000000..102c9705 --- /dev/null +++ b/PolymarketDocumentation-main/docs/api-reference/wss/perps-place-orders.md @@ -0,0 +1,478 @@ +> ## Documentation Index +> Fetch the complete documentation index at: https://docs.polymarket.com/llms.txt +> Use this file to discover all available pages before exploring further. + +# Place Orders + +> Perps WebSocket order placement. + + + +## AsyncAPI + +````yaml asyncapi-perps.json placeOrders +id: placeOrders +title: Create Orders +description: | + Create new orders. + Requires proxy signature, see [proxy signing](/http/signing#2-proxy-signing). + + Action Weight: **1 / order** +servers: + - id: production + protocol: wss + host: ws.perpetuals.polymarket.com + bindings: [] + variables: [] +address: /v1/ws +parameters: [] +bindings: [] +operations: + - &ref_1 + id: PlaceOrdersSend + title: Place orders send + description: Submit new orders + type: receive + messages: + - &ref_3 + id: Request + contentType: application/json + payload: + - name: Create Orders Request + description: Client submits a signed order placement request + type: object + properties: + - name: id + type: integer + description: Correlation ID for request-response matching + required: false + - name: req + type: string + description: Request type + enumValues: + - post + - sub + - unsub + required: true + - name: op + type: object + required: true + properties: + - name: type + type: string + enumValues: + - createOrders + required: true + - name: args + type: object + description: Array of orders to create + required: true + properties: + - name: iid + type: integer + description: Instrument ID + required: true + - name: buy + type: boolean + description: Is buy + required: true + - name: p + type: string + description: Price + required: false + - name: qty + type: string + description: Quantity in no. of contracts + required: true + - name: tif + type: string + description: Time in force + enumValues: + - gtc + - ioc + - fok + required: false + - name: po + type: boolean + description: Post only + required: false + - name: ro + type: boolean + description: Reduce only + required: false + - name: c + type: string + description: Client order ID + required: false + - name: tr + type: object + description: Optional trigger attached to this order. + required: false + properties: + - name: market + type: boolean + description: Whether the trigger executes as a market order + required: false + - name: trp + type: string + description: Trigger price + required: false + - name: tpsl + type: string + description: Trigger type + enumValues: + - tp + - sl + required: false + - name: grp + type: string + description: TPSL grouping + enumValues: + - order + - position + required: false + - name: sig + type: string + description: Signature in hex format + required: true + - name: salt + type: integer + description: Salt + required: true + - name: ts + type: integer + description: >- + Request timestamp. Unix milliseconds for most operations; Unix + seconds for withdrawals (must match the on-chain EIP-712 + struct verified against block.timestamp). + required: true + - name: exp + type: integer + description: >- + Command expiry timestamp in Unix milliseconds. If provided, it + must be in the future and within the gateway's default command + timeout. It can shorten request validity but cannot extend it. + This is not an order auto-cancel time. + required: false + headers: [] + jsonPayloadSchema: + type: object + title: Base Request + properties: + id: + type: integer + description: Correlation ID for request-response matching + x-parser-schema-id: + req: + type: string + description: Request type + enum: + - post + - sub + - unsub + x-parser-schema-id: + op: + type: object + required: + - type + - args + properties: + type: + type: string + enum: + - createOrders + x-parser-schema-id: + args: + description: Array of orders to create + type: object + required: + - iid + - buy + - qty + properties: + iid: + type: integer + description: Instrument ID + example: 1 + x-parser-schema-id: + buy: + type: boolean + description: Is buy + example: true + x-parser-schema-id: + p: + type: string + description: Price + example: '100.00' + x-parser-schema-id: + qty: + type: string + description: Quantity in no. of contracts + example: '10.00' + x-parser-schema-id: + tif: + type: string + description: Time in force + enum: + - gtc + - ioc + - fok + x-parser-schema-id: + po: + type: boolean + description: Post only + default: false + example: false + x-parser-schema-id: + ro: + type: boolean + description: Reduce only + example: false + default: false + x-parser-schema-id: + c: + type: string + description: Client order ID + minLength: 32 + maxLength: 32 + pattern: ^[0-9a-f]{32}$ + example: 550e8400e29b41d4a716446655440000 + x-parser-schema-id: + tr: + type: object + description: Optional trigger attached to this order. + properties: + market: + type: boolean + description: Whether the trigger executes as a market order + x-parser-schema-id: + trp: + type: string + description: Trigger price + example: '110.00' + x-parser-schema-id: + tpsl: + type: string + description: Trigger type + enum: + - tp + - sl + x-parser-schema-id: + x-parser-schema-id: + x-parser-schema-id: + grp: + type: string + description: TPSL grouping + enum: + - order + - position + x-parser-schema-id: + x-parser-schema-id: + sig: + type: string + description: Signature in hex format + example: 0x1234567890... + x-parser-schema-id: + salt: + type: integer + description: Salt + example: 1234567890 + x-parser-schema-id: + ts: + type: integer + description: >- + Request timestamp. Unix milliseconds for most operations; Unix + seconds for withdrawals (must match the on-chain EIP-712 struct + verified against block.timestamp). + example: 1767225600000 + x-parser-schema-id: + exp: + type: integer + description: >- + Command expiry timestamp in Unix milliseconds. If provided, it + must be in the future and within the gateway's default command + timeout. It can shorten request validity but cannot extend it. + This is not an order auto-cancel time. + example: 1767225600000 + x-parser-schema-id: + required: + - req + - op + - sig + - salt + - ts + x-parser-schema-id: + title: Create Orders Request + description: Client submits a signed order placement request + example: |- + { + "req": "post", + "op": { + "type": "createOrders", + "args": [ + { + "iid": 1, + "buy": true, + "p": "100.00", + "qty": "10.00", + "tif": "gtc", + "po": false, + "ro": false, + "c": "550e8400e29b41d4a716446655440000", + "tr": { + "trp": "110.00", + "tpsl": "tp" + } + } + ], + "grp": "order" + }, + "sig": "0x1234567890...", + "salt": 1234567890, + "ts": 1767225600000, + "exp": 1767225600000 + } + bindings: [] + extensions: + - id: x-parser-unique-object-id + value: Request + bindings: [] + extensions: &ref_0 + - id: x-parser-unique-object-id + value: placeOrders + - &ref_2 + id: PlaceOrdersReceive + title: Place orders receive + description: Order ACK response + type: send + messages: + - &ref_4 + id: Response + contentType: application/json + payload: + - name: Create Orders Response + description: Server responds with order ACK for each submitted order + type: object + properties: + - name: id + type: integer + description: Correlation ID for request-response matching + required: false + - name: data + type: object + description: Array of order results + required: true + headers: [] + jsonPayloadSchema: + type: object + title: Base Response + properties: + id: + type: integer + description: Correlation ID for request-response matching + x-parser-schema-id: + data: + type: object + description: Array of order results + oneOf: + - type: object + required: + - status + - oid + properties: + status: + type: string + enum: + - ok + x-parser-schema-id: + oid: + type: integer + description: Order ID + example: 1234567890 + x-parser-schema-id: + coid: + type: string + description: Client order ID + minLength: 32 + maxLength: 32 + pattern: ^[0-9a-f]{32}$ + example: 550e8400e29b41d4a716446655440000 + x-parser-schema-id: + x-parser-schema-id: + - type: object + required: + - status + - error + properties: + status: + type: string + enum: + - err + x-parser-schema-id: + error: + type: string + description: >- + Error identifier. For domain rejections and transport + errors (`401`/`404`/`429`/`500`) this is a stable, + machine-readable snake_case identifier that is part of + the API contract and safe to branch on, e.g. + `insufficient_margin`, `insufficient_balance`, + `order_not_found`, `reduce_only_invalid`, + `unauthorized`, `not_found`. For `400` it is a + human-readable validation detail whose wording may + change. See the Error handling guide for the domain + identifiers. (Post-only / Fill-or-Kill outcomes are + order statuses such as `post_only_rejected`, not + rejections.) + example: insufficient_margin + x-parser-schema-id: + oid: + type: integer + description: Order ID + example: 1234567890 + x-parser-schema-id: + coid: + type: string + description: Client order ID + minLength: 32 + maxLength: 32 + pattern: ^[0-9a-f]{32}$ + example: 550e8400e29b41d4a716446655440000 + x-parser-schema-id: + x-parser-schema-id: + x-parser-schema-id: + required: + - data + x-parser-schema-id: + title: Create Orders Response + description: Server responds with order ACK for each submitted order + example: |- + { + "id": 1, + "data": [ + { + "status": "ok", + "oid": 1234567890 + } + ] + } + bindings: [] + extensions: + - id: x-parser-unique-object-id + value: Response + bindings: [] + extensions: *ref_0 +sendOperations: + - *ref_1 +receiveOperations: + - *ref_2 +sendMessages: + - *ref_3 +receiveMessages: + - *ref_4 +extensions: + - id: x-parser-unique-object-id + value: placeOrders +securitySchemes: [] + +```` \ No newline at end of file diff --git a/PolymarketDocumentation-main/docs/api-reference/wss/perps-portfolio.md b/PolymarketDocumentation-main/docs/api-reference/wss/perps-portfolio.md new file mode 100644 index 00000000..ca643063 --- /dev/null +++ b/PolymarketDocumentation-main/docs/api-reference/wss/perps-portfolio.md @@ -0,0 +1,798 @@ +> ## Documentation Index +> Fetch the complete documentation index at: https://docs.polymarket.com/llms.txt +> Use this file to discover all available pages before exploring further. + +# Portfolio + +> Perps WebSocket private portfolio updates. + + + +## AsyncAPI + +````yaml asyncapi-perps.json portfolio +id: portfolio +title: Portfolio +description: >- + Real-time portfolio updates. Pushed every 5 seconds. Requires authentication, + see [Auth](/ws/auth). +servers: + - id: production + protocol: wss + host: ws.perpetuals.polymarket.com + bindings: [] + variables: [] +address: /v1/ws +parameters: [] +bindings: [] +operations: + - &ref_1 + id: PortfolioSubscribe + title: Portfolio subscribe + description: Subscribe to portfolio + type: receive + messages: + - &ref_6 + id: SubscribeRequest + contentType: application/json + payload: + - name: Subscribe + description: Subscribe to private portfolio updates (requires prior auth) + type: object + properties: + - name: id + type: integer + description: Correlation ID for request-response matching + required: false + - name: req + type: string + description: Request type + enumValues: + - post + - sub + - unsub + required: true + - name: chs + type: array + description: 'Portfolio private channel: "portfolio"' + required: true + properties: + - name: item + type: string + enumValues: + - portfolio + required: false + headers: [] + jsonPayloadSchema: + type: object + title: Base Request + properties: + id: + type: integer + description: Correlation ID for request-response matching + x-parser-schema-id: + req: + type: string + description: Request type + enum: + - post + - sub + - unsub + x-parser-schema-id: + chs: + type: array + description: 'Portfolio private channel: "portfolio"' + items: + type: string + enum: + - portfolio + x-parser-schema-id: + example: + - portfolio + x-parser-schema-id: + required: + - req + - chs + x-parser-schema-id: + title: Subscribe + description: Subscribe to private portfolio updates (requires prior auth) + example: |- + { + "req": "sub", + "chs": [ + "portfolio" + ] + } + bindings: [] + extensions: + - id: x-parser-unique-object-id + value: SubscribeRequest + bindings: [] + extensions: &ref_0 + - id: x-parser-unique-object-id + value: portfolio + - &ref_3 + id: PortfolioSubscribeResponse + title: Portfolio subscribe response + description: Portfolio subscribe response + type: send + messages: + - &ref_8 + id: SubscribeResponse + contentType: application/json + payload: + - name: Subscribe Response + description: Response to portfolio subscribe request + type: object + properties: + - name: id + type: integer + description: Correlation ID for request-response matching + required: false + - name: data + type: array + title: Subscribe Response + required: true + properties: + - name: item + type: object + required: false + properties: + - name: status + type: string + enumValues: + - ok + required: true + - name: status + type: string + enumValues: + - err + required: true + - name: error + type: string + description: >- + Error identifier. For domain rejections and transport + errors (`401`/`404`/`429`/`500`) this is a stable, + machine-readable snake_case identifier that is part of + the API contract and safe to branch on, e.g. + `insufficient_margin`, `insufficient_balance`, + `order_not_found`, `reduce_only_invalid`, + `unauthorized`, `not_found`. For `400` it is a + human-readable validation detail whose wording may + change. See the Error handling guide for the domain + identifiers. (Post-only / Fill-or-Kill outcomes are + order statuses such as `post_only_rejected`, not + rejections.) + required: true + headers: [] + jsonPayloadSchema: + type: object + title: Base Response + properties: + id: + type: integer + description: Correlation ID for request-response matching + x-parser-schema-id: + data: + title: Subscribe Response + type: array + items: + oneOf: + - type: object + required: + - status + properties: + status: + type: string + enum: + - ok + x-parser-schema-id: + x-parser-schema-id: + - type: object + required: + - status + - error + properties: + status: + type: string + enum: + - err + x-parser-schema-id: + error: + type: string + description: >- + Error identifier. For domain rejections and transport + errors (`401`/`404`/`429`/`500`) this is a stable, + machine-readable snake_case identifier that is part of + the API contract and safe to branch on, e.g. + `insufficient_margin`, `insufficient_balance`, + `order_not_found`, `reduce_only_invalid`, + `unauthorized`, `not_found`. For `400` it is a + human-readable validation detail whose wording may + change. See the Error handling guide for the domain + identifiers. (Post-only / Fill-or-Kill outcomes are + order statuses such as `post_only_rejected`, not + rejections.) + example: insufficient_margin + x-parser-schema-id: + x-parser-schema-id: + x-parser-schema-id: + x-parser-schema-id: + required: + - data + x-parser-schema-id: + title: Subscribe Response + description: Response to portfolio subscribe request + example: |- + { + "data": [] + } + bindings: [] + extensions: + - id: x-parser-unique-object-id + value: SubscribeResponse + bindings: [] + extensions: *ref_0 + - &ref_2 + id: PortfolioUnsubscribe + title: Portfolio unsubscribe + description: Unsubscribe from portfolio + type: receive + messages: + - &ref_7 + id: UnsubscribeRequest + contentType: application/json + payload: + - name: Unsubscribe + description: Unsubscribe from private portfolio updates + type: object + properties: + - name: id + type: integer + description: Correlation ID for request-response matching + required: false + - name: req + type: string + description: Request type + enumValues: + - post + - sub + - unsub + required: true + - name: chs + type: array + description: 'Portfolio private channel: "portfolio"' + required: true + properties: + - name: item + type: string + enumValues: + - portfolio + required: false + headers: [] + jsonPayloadSchema: + type: object + title: Base Request + properties: + id: + type: integer + description: Correlation ID for request-response matching + x-parser-schema-id: + req: + type: string + description: Request type + enum: + - post + - sub + - unsub + x-parser-schema-id: + chs: + type: array + description: 'Portfolio private channel: "portfolio"' + items: + type: string + enum: + - portfolio + x-parser-schema-id: + example: + - portfolio + x-parser-schema-id: + required: + - req + - chs + x-parser-schema-id: + title: Unsubscribe + description: Unsubscribe from private portfolio updates + example: |- + { + "req": "unsub", + "chs": [ + "portfolio" + ] + } + bindings: [] + extensions: + - id: x-parser-unique-object-id + value: UnsubscribeRequest + bindings: [] + extensions: *ref_0 + - &ref_4 + id: PortfolioUnsubscribeResponse + title: Portfolio unsubscribe response + description: Portfolio unsubscribe response + type: send + messages: + - &ref_9 + id: UnsubscribeResponse + contentType: application/json + payload: + - name: Unsubscribe Response + description: Response to portfolio unsubscribe request + type: object + properties: + - name: id + type: integer + description: Correlation ID for request-response matching + required: false + - name: data + type: array + title: Subscribe Response + required: true + properties: + - name: item + type: object + required: false + properties: + - name: status + type: string + enumValues: + - ok + required: true + - name: status + type: string + enumValues: + - err + required: true + - name: error + type: string + description: >- + Error identifier. For domain rejections and transport + errors (`401`/`404`/`429`/`500`) this is a stable, + machine-readable snake_case identifier that is part of + the API contract and safe to branch on, e.g. + `insufficient_margin`, `insufficient_balance`, + `order_not_found`, `reduce_only_invalid`, + `unauthorized`, `not_found`. For `400` it is a + human-readable validation detail whose wording may + change. See the Error handling guide for the domain + identifiers. (Post-only / Fill-or-Kill outcomes are + order statuses such as `post_only_rejected`, not + rejections.) + required: true + headers: [] + jsonPayloadSchema: + type: object + title: Base Response + properties: + id: + type: integer + description: Correlation ID for request-response matching + x-parser-schema-id: + data: + title: Subscribe Response + type: array + items: + oneOf: + - type: object + required: + - status + properties: + status: + type: string + enum: + - ok + x-parser-schema-id: + x-parser-schema-id: + - type: object + required: + - status + - error + properties: + status: + type: string + enum: + - err + x-parser-schema-id: + error: + type: string + description: >- + Error identifier. For domain rejections and transport + errors (`401`/`404`/`429`/`500`) this is a stable, + machine-readable snake_case identifier that is part of + the API contract and safe to branch on, e.g. + `insufficient_margin`, `insufficient_balance`, + `order_not_found`, `reduce_only_invalid`, + `unauthorized`, `not_found`. For `400` it is a + human-readable validation detail whose wording may + change. See the Error handling guide for the domain + identifiers. (Post-only / Fill-or-Kill outcomes are + order statuses such as `post_only_rejected`, not + rejections.) + example: insufficient_margin + x-parser-schema-id: + x-parser-schema-id: + x-parser-schema-id: + x-parser-schema-id: + required: + - data + x-parser-schema-id: + title: Unsubscribe Response + description: Response to portfolio unsubscribe request + example: |- + { + "data": [] + } + bindings: [] + extensions: + - id: x-parser-unique-object-id + value: UnsubscribeResponse + bindings: [] + extensions: *ref_0 + - &ref_5 + id: PortfolioUpdate + title: Portfolio update + description: Receive portfolio updates + type: send + messages: + - &ref_10 + id: Update + contentType: application/json + payload: + - name: Update + description: Portfolio updates pushed every 5 seconds + type: object + properties: + - name: ch + type: string + description: >- + Channel name for push data. Parameterized channels include the + instrument ID (e.g. "trades::1", "book::1", "klines::1::1m", + "tickers::all"). Private channels use plain names (e.g. + "fills", "orders"). + required: true + - name: ts + type: integer + description: >- + Request timestamp. Unix milliseconds for most operations; Unix + seconds for withdrawals (must match the on-chain EIP-712 + struct verified against block.timestamp). + required: true + - name: sq + type: integer + description: Sequence number + required: true + - name: data + type: object + required: true + properties: + - name: positions + type: array + required: true + properties: + - name: instrument_id + type: integer + description: Instrument ID + required: true + - name: symbol + type: string + description: Instrument symbol + required: true + - name: size + type: string + description: >- + Signed position size in no. of contracts (positive = + long, negative = short) + required: true + - name: entry_price + type: string + description: Average entry price + required: true + - name: leverage + type: integer + description: Leverage + required: true + - name: cross + type: boolean + description: Whether to use cross margin mode + required: true + - name: initial_margin + type: string + description: Initial margin in USD + required: true + - name: maintenance_margin + type: string + description: Maintenance margin amount + required: true + - name: position_value + type: string + description: Notional position value in USD + required: true + - name: liquidation_price + type: string + description: Liquidation price + required: true + - name: unrealized_pnl + type: string + description: Unrealized PnL in USD + required: true + - name: return_on_equity + type: string + description: Return on equity as a decimal + required: true + - name: cumulative_funding + type: string + description: Cumulative funding paid/received in USD + required: true + - name: margin + type: object + required: true + properties: + - name: total_account_value + type: string + description: Total account value in USD (equity + unrealized PnL) + required: true + - name: total_initial_margin + type: string + description: Total initial margin in use across all positions + required: true + - name: total_maintenance_margin + type: string + description: Total maintenance margin across all positions + required: true + - name: total_position_value + type: string + description: Total notional position value in USD + required: true + - name: withdrawable + type: string + description: Withdrawable balance in USD + required: true + - name: in_liquidation + type: boolean + description: Whether the account is currently under liquidation + required: true + - name: timestamp + type: integer + description: Update timestamp in milliseconds + required: true + headers: [] + jsonPayloadSchema: + title: Portfolio Update + type: object + properties: + ch: + type: string + description: >- + Channel name for push data. Parameterized channels include the + instrument ID (e.g. "trades::1", "book::1", "klines::1::1m", + "tickers::all"). Private channels use plain names (e.g. "fills", + "orders"). + example: trades::1 + x-parser-schema-id: + ts: + type: integer + description: >- + Request timestamp. Unix milliseconds for most operations; Unix + seconds for withdrawals (must match the on-chain EIP-712 struct + verified against block.timestamp). + example: 1767225600000 + x-parser-schema-id: + sq: + type: integer + description: Sequence number + example: 1234567890 + x-parser-schema-id: + data: + type: object + required: + - positions + - margin + - withdrawable + - in_liquidation + - timestamp + properties: + positions: + type: array + items: + type: object + required: + - instrument_id + - symbol + - size + - entry_price + - leverage + - cross + - initial_margin + - maintenance_margin + - position_value + - liquidation_price + - unrealized_pnl + - return_on_equity + - cumulative_funding + properties: + instrument_id: + type: integer + description: Instrument ID + x-parser-schema-id: + symbol: + type: string + description: Instrument symbol + example: NVDA-USDC + x-parser-schema-id: + size: + type: string + description: >- + Signed position size in no. of contracts (positive = + long, negative = short) + example: '10.00' + x-parser-schema-id: + entry_price: + type: string + description: Average entry price + example: '2986.30' + x-parser-schema-id: + leverage: + type: integer + description: Leverage + example: 10 + x-parser-schema-id: + cross: + type: boolean + description: Whether to use cross margin mode + x-parser-schema-id: + initial_margin: + type: string + description: Initial margin in USD + example: '10.00' + x-parser-schema-id: + maintenance_margin: + type: string + description: Maintenance margin amount + example: '100.00' + x-parser-schema-id: + position_value: + type: string + description: Notional position value in USD + example: '100.03' + x-parser-schema-id: + liquidation_price: + type: string + description: Liquidation price + example: '2866.27' + x-parser-schema-id: + unrealized_pnl: + type: string + description: Unrealized PnL in USD + example: '-0.01' + x-parser-schema-id: + return_on_equity: + type: string + description: Return on equity as a decimal + example: '-0.0027' + x-parser-schema-id: + cumulative_funding: + type: string + description: Cumulative funding paid/received in USD + example: '514.09' + x-parser-schema-id: + x-parser-schema-id: + x-parser-schema-id: + margin: + type: object + required: + - total_account_value + - total_initial_margin + - total_maintenance_margin + - total_position_value + properties: + total_account_value: + type: string + description: Total account value in USD (equity + unrealized PnL) + example: '13109.48' + x-parser-schema-id: + total_initial_margin: + type: string + description: Total initial margin in use across all positions + example: '4.97' + x-parser-schema-id: + total_maintenance_margin: + type: string + description: Total maintenance margin across all positions + example: '2.49' + x-parser-schema-id: + total_position_value: + type: string + description: Total notional position value in USD + example: '100.03' + x-parser-schema-id: + x-parser-schema-id: + withdrawable: + type: string + description: Withdrawable balance in USD + example: '13104.51' + x-parser-schema-id: + in_liquidation: + type: boolean + description: Whether the account is currently under liquidation + x-parser-schema-id: + timestamp: + type: integer + description: Update timestamp in milliseconds + example: 1767225600000 + x-parser-schema-id: + x-parser-schema-id: + required: + - ch + - ts + - sq + - data + x-parser-schema-id: + title: Update + description: Portfolio updates pushed every 5 seconds + example: |- + { + "ch": "portfolio", + "ts": 1767225600000, + "sq": 1234567890, + "data": { + "positions": [ + { + "symbol": "NVDA-USDC", + "size": "10.00", + "entry_price": "2986.30", + "leverage": 10, + "initial_margin": "10.00", + "maintenance_margin": "100.00", + "position_value": "100.03", + "liquidation_price": "2866.27", + "unrealized_pnl": "-0.01", + "return_on_equity": "-0.0027", + "cumulative_funding": "514.09" + } + ], + "margin": { + "total_account_value": "13109.48", + "total_initial_margin": "4.97", + "total_maintenance_margin": "2.49", + "total_position_value": "100.03" + }, + "withdrawable": "13104.51", + "timestamp": 1767225600000 + } + } + bindings: [] + extensions: + - id: x-parser-unique-object-id + value: Update + bindings: [] + extensions: *ref_0 +sendOperations: + - *ref_1 + - *ref_2 +receiveOperations: + - *ref_3 + - *ref_4 + - *ref_5 +sendMessages: + - *ref_6 + - *ref_7 +receiveMessages: + - *ref_8 + - *ref_9 + - *ref_10 +extensions: + - id: x-parser-unique-object-id + value: portfolio +securitySchemes: [] + +```` \ No newline at end of file diff --git a/PolymarketDocumentation-main/docs/api-reference/wss/perps-statistics.md b/PolymarketDocumentation-main/docs/api-reference/wss/perps-statistics.md new file mode 100644 index 00000000..9f4e1e58 --- /dev/null +++ b/PolymarketDocumentation-main/docs/api-reference/wss/perps-statistics.md @@ -0,0 +1,655 @@ +> ## Documentation Index +> Fetch the complete documentation index at: https://docs.polymarket.com/llms.txt +> Use this file to discover all available pages before exploring further. + +# Statistics + +> Perps WebSocket 24-hour statistics updates. + + + +## AsyncAPI + +````yaml asyncapi-perps.json statistics +id: statistics +title: Statistics +description: 24-hour statistics updates. Pushed every 1 second. +servers: + - id: production + protocol: wss + host: ws.perpetuals.polymarket.com + bindings: [] + variables: [] +address: /v1/ws +parameters: [] +bindings: [] +operations: + - &ref_1 + id: StatisticsSubscribe + title: Statistics subscribe + description: Subscribe to statistics + type: receive + messages: + - &ref_6 + id: SubscribeRequest + contentType: application/json + payload: + - name: Subscribe + description: >- + Subscribe to 24-hour statistics updates for all instruments or a + specific one + type: object + properties: + - name: id + type: integer + description: Correlation ID for request-response matching + required: false + - name: req + type: string + description: Request type + enumValues: + - post + - sub + - unsub + required: true + - name: chs + type: array + description: > + Statistics subscription: `statistics::all` for every active + instrument, + + or `statistics::{iid}` (e.g. `statistics::1`) for a specific + one. + required: true + properties: + - name: item + type: string + required: false + headers: [] + jsonPayloadSchema: + type: object + title: Base Request + properties: + id: + type: integer + description: Correlation ID for request-response matching + x-parser-schema-id: + req: + type: string + description: Request type + enum: + - post + - sub + - unsub + x-parser-schema-id: + chs: + type: array + description: > + Statistics subscription: `statistics::all` for every active + instrument, + + or `statistics::{iid}` (e.g. `statistics::1`) for a specific + one. + items: + type: string + pattern: ^statistics::(\d+|all)$ + x-parser-schema-id: + example: + - statistics::all + x-parser-schema-id: + required: + - req + - chs + x-parser-schema-id: + title: Subscribe + description: >- + Subscribe to 24-hour statistics updates for all instruments or a + specific one + example: |- + { + "req": "sub", + "chs": [ + "statistics::all" + ] + } + bindings: [] + extensions: + - id: x-parser-unique-object-id + value: SubscribeRequest + bindings: [] + extensions: &ref_0 + - id: x-parser-unique-object-id + value: statistics + - &ref_3 + id: StatisticsSubscribeResponse + title: Statistics subscribe response + description: Statistics subscribe response + type: send + messages: + - &ref_8 + id: SubscribeResponse + contentType: application/json + payload: + - name: Subscribe Response + description: Response to statistics subscribe request + type: object + properties: + - name: id + type: integer + description: Correlation ID for request-response matching + required: false + - name: data + type: array + title: Subscribe Response + required: true + properties: + - name: item + type: object + required: false + properties: + - name: status + type: string + enumValues: + - ok + required: true + - name: status + type: string + enumValues: + - err + required: true + - name: error + type: string + description: >- + Error identifier. For domain rejections and transport + errors (`401`/`404`/`429`/`500`) this is a stable, + machine-readable snake_case identifier that is part of + the API contract and safe to branch on, e.g. + `insufficient_margin`, `insufficient_balance`, + `order_not_found`, `reduce_only_invalid`, + `unauthorized`, `not_found`. For `400` it is a + human-readable validation detail whose wording may + change. See the Error handling guide for the domain + identifiers. (Post-only / Fill-or-Kill outcomes are + order statuses such as `post_only_rejected`, not + rejections.) + required: true + headers: [] + jsonPayloadSchema: + type: object + title: Base Response + properties: + id: + type: integer + description: Correlation ID for request-response matching + x-parser-schema-id: + data: + title: Subscribe Response + type: array + items: + oneOf: + - type: object + required: + - status + properties: + status: + type: string + enum: + - ok + x-parser-schema-id: + x-parser-schema-id: + - type: object + required: + - status + - error + properties: + status: + type: string + enum: + - err + x-parser-schema-id: + error: + type: string + description: >- + Error identifier. For domain rejections and transport + errors (`401`/`404`/`429`/`500`) this is a stable, + machine-readable snake_case identifier that is part of + the API contract and safe to branch on, e.g. + `insufficient_margin`, `insufficient_balance`, + `order_not_found`, `reduce_only_invalid`, + `unauthorized`, `not_found`. For `400` it is a + human-readable validation detail whose wording may + change. See the Error handling guide for the domain + identifiers. (Post-only / Fill-or-Kill outcomes are + order statuses such as `post_only_rejected`, not + rejections.) + example: insufficient_margin + x-parser-schema-id: + x-parser-schema-id: + x-parser-schema-id: + x-parser-schema-id: + required: + - data + x-parser-schema-id: + title: Subscribe Response + description: Response to statistics subscribe request + example: |- + { + "data": [] + } + bindings: [] + extensions: + - id: x-parser-unique-object-id + value: SubscribeResponse + bindings: [] + extensions: *ref_0 + - &ref_2 + id: StatisticsUnsubscribe + title: Statistics unsubscribe + description: Unsubscribe from statistics + type: receive + messages: + - &ref_7 + id: UnsubscribeRequest + contentType: application/json + payload: + - name: Unsubscribe + description: Unsubscribe from statistics updates + type: object + properties: + - name: id + type: integer + description: Correlation ID for request-response matching + required: false + - name: req + type: string + description: Request type + enumValues: + - post + - sub + - unsub + required: true + - name: chs + type: array + description: > + Statistics subscription: `statistics::all` for every active + instrument, + + or `statistics::{iid}` (e.g. `statistics::1`) for a specific + one. + required: true + properties: + - name: item + type: string + required: false + headers: [] + jsonPayloadSchema: + type: object + title: Base Request + properties: + id: + type: integer + description: Correlation ID for request-response matching + x-parser-schema-id: + req: + type: string + description: Request type + enum: + - post + - sub + - unsub + x-parser-schema-id: + chs: + type: array + description: > + Statistics subscription: `statistics::all` for every active + instrument, + + or `statistics::{iid}` (e.g. `statistics::1`) for a specific + one. + items: + type: string + pattern: ^statistics::(\d+|all)$ + x-parser-schema-id: + example: + - statistics::all + x-parser-schema-id: + required: + - req + - chs + x-parser-schema-id: + title: Unsubscribe + description: Unsubscribe from statistics updates + example: |- + { + "req": "unsub", + "chs": [ + "statistics::all" + ] + } + bindings: [] + extensions: + - id: x-parser-unique-object-id + value: UnsubscribeRequest + bindings: [] + extensions: *ref_0 + - &ref_4 + id: StatisticsUnsubscribeResponse + title: Statistics unsubscribe response + description: Statistics unsubscribe response + type: send + messages: + - &ref_9 + id: UnsubscribeResponse + contentType: application/json + payload: + - name: Unsubscribe Response + description: Response to statistics unsubscribe request + type: object + properties: + - name: id + type: integer + description: Correlation ID for request-response matching + required: false + - name: data + type: array + title: Subscribe Response + required: true + properties: + - name: item + type: object + required: false + properties: + - name: status + type: string + enumValues: + - ok + required: true + - name: status + type: string + enumValues: + - err + required: true + - name: error + type: string + description: >- + Error identifier. For domain rejections and transport + errors (`401`/`404`/`429`/`500`) this is a stable, + machine-readable snake_case identifier that is part of + the API contract and safe to branch on, e.g. + `insufficient_margin`, `insufficient_balance`, + `order_not_found`, `reduce_only_invalid`, + `unauthorized`, `not_found`. For `400` it is a + human-readable validation detail whose wording may + change. See the Error handling guide for the domain + identifiers. (Post-only / Fill-or-Kill outcomes are + order statuses such as `post_only_rejected`, not + rejections.) + required: true + headers: [] + jsonPayloadSchema: + type: object + title: Base Response + properties: + id: + type: integer + description: Correlation ID for request-response matching + x-parser-schema-id: + data: + title: Subscribe Response + type: array + items: + oneOf: + - type: object + required: + - status + properties: + status: + type: string + enum: + - ok + x-parser-schema-id: + x-parser-schema-id: + - type: object + required: + - status + - error + properties: + status: + type: string + enum: + - err + x-parser-schema-id: + error: + type: string + description: >- + Error identifier. For domain rejections and transport + errors (`401`/`404`/`429`/`500`) this is a stable, + machine-readable snake_case identifier that is part of + the API contract and safe to branch on, e.g. + `insufficient_margin`, `insufficient_balance`, + `order_not_found`, `reduce_only_invalid`, + `unauthorized`, `not_found`. For `400` it is a + human-readable validation detail whose wording may + change. See the Error handling guide for the domain + identifiers. (Post-only / Fill-or-Kill outcomes are + order statuses such as `post_only_rejected`, not + rejections.) + example: insufficient_margin + x-parser-schema-id: + x-parser-schema-id: + x-parser-schema-id: + x-parser-schema-id: + required: + - data + x-parser-schema-id: + title: Unsubscribe Response + description: Response to statistics unsubscribe request + example: |- + { + "data": [] + } + bindings: [] + extensions: + - id: x-parser-unique-object-id + value: UnsubscribeResponse + bindings: [] + extensions: *ref_0 + - &ref_5 + id: StatisticsUpdate + title: Statistics update + description: Receive statistics updates + type: send + messages: + - &ref_10 + id: Update + contentType: application/json + payload: + - name: Update + description: 24-hour statistics for subscribed instruments + type: object + properties: + - name: ch + type: string + description: >- + Channel name for push data. Parameterized channels include the + instrument ID (e.g. "trades::1", "book::1", "klines::1::1m", + "tickers::all"). Private channels use plain names (e.g. + "fills", "orders"). + required: true + - name: ts + type: integer + description: >- + Request timestamp. Unix milliseconds for most operations; Unix + seconds for withdrawals (must match the on-chain EIP-712 + struct verified against block.timestamp). + required: true + - name: sq + type: integer + description: Sequence number + required: true + - name: data + type: object + description: Array of statistics objects + required: true + properties: + - name: iid + type: integer + description: Instrument ID + required: true + - name: vol + type: string + description: 24-hour trading volume in contracts + required: true + - name: open + type: string + description: Opening price from 24 hours ago + required: true + - name: klines + type: array + description: Last 24-hour kline data + required: true + properties: + - name: item + type: array + description: | + - `1767225600000` - Open time + - `"100.00"` - Open price + - `"105.00"` - High price + - `"99.00"` - Low price + - `"102.00"` - Close price + - `"500.00"` - Volume (base unit) + - `42` - Number of trades + required: false + headers: [] + jsonPayloadSchema: + title: Statistics Update + type: object + properties: + ch: + type: string + description: >- + Channel name for push data. Parameterized channels include the + instrument ID (e.g. "trades::1", "book::1", "klines::1::1m", + "tickers::all"). Private channels use plain names (e.g. "fills", + "orders"). + example: trades::1 + x-parser-schema-id: + ts: + type: integer + description: >- + Request timestamp. Unix milliseconds for most operations; Unix + seconds for withdrawals (must match the on-chain EIP-712 struct + verified against block.timestamp). + example: 1767225600000 + x-parser-schema-id: + sq: + type: integer + description: Sequence number + example: 1234567890 + x-parser-schema-id: + data: + type: object + description: Array of statistics objects + properties: + iid: + type: integer + description: Instrument ID + example: 1 + x-parser-schema-id: + vol: + type: string + description: 24-hour trading volume in contracts + example: '1000.00' + x-parser-schema-id: + open: + type: string + description: Opening price from 24 hours ago + example: '100.50' + x-parser-schema-id: + klines: + type: array + items: + type: array + description: | + - `1767225600000` - Open time + - `"100.00"` - Open price + - `"105.00"` - High price + - `"99.00"` - Low price + - `"102.00"` - Close price + - `"500.00"` - Volume (base unit) + - `42` - Number of trades + example: + - 1767225600000 + - '100.00' + - '105.00' + - '99.00' + - '102.00' + - '500.00' + - 42 + x-parser-schema-id: + description: Last 24-hour kline data + x-parser-schema-id: + required: + - iid + - vol + - open + - klines + x-parser-schema-id: + required: + - ch + - ts + - sq + - data + x-parser-schema-id: + title: Update + description: 24-hour statistics for subscribed instruments + example: |- + { + "ch": "statistics::all", + "ts": 1767225600000, + "sq": 1234567890, + "data": [ + { + "iid": 1, + "vol": "1000.00", + "open": "100.50", + "klines": [ + [ + 1767225600000, + "100.00", + "105.00", + "99.00", + "102.00", + "500.00", + 42 + ] + ] + } + ] + } + bindings: [] + extensions: + - id: x-parser-unique-object-id + value: Update + bindings: [] + extensions: *ref_0 +sendOperations: + - *ref_1 + - *ref_2 +receiveOperations: + - *ref_3 + - *ref_4 + - *ref_5 +sendMessages: + - *ref_6 + - *ref_7 +receiveMessages: + - *ref_8 + - *ref_9 + - *ref_10 +extensions: + - id: x-parser-unique-object-id + value: statistics +securitySchemes: [] + +```` \ No newline at end of file diff --git a/PolymarketDocumentation-main/docs/api-reference/wss/perps-tickers.md b/PolymarketDocumentation-main/docs/api-reference/wss/perps-tickers.md new file mode 100644 index 00000000..58c32785 --- /dev/null +++ b/PolymarketDocumentation-main/docs/api-reference/wss/perps-tickers.md @@ -0,0 +1,647 @@ +> ## Documentation Index +> Fetch the complete documentation index at: https://docs.polymarket.com/llms.txt +> Use this file to discover all available pages before exploring further. + +# Tickers + +> Perps WebSocket ticker updates. + + + +## AsyncAPI + +````yaml asyncapi-perps.json tickers +id: tickers +title: Tickers +description: Ticker updates. Pushed every 100ms. +servers: + - id: production + protocol: wss + host: ws.perpetuals.polymarket.com + bindings: [] + variables: [] +address: /v1/ws +parameters: [] +bindings: [] +operations: + - &ref_1 + id: TickersSubscribe + title: Tickers subscribe + description: Subscribe to tickers + type: receive + messages: + - &ref_6 + id: SubscribeRequest + contentType: application/json + payload: + - name: Subscribe + description: Subscribe to ticker updates for all instruments or a specific one + type: object + properties: + - name: id + type: integer + description: Correlation ID for request-response matching + required: false + - name: req + type: string + description: Request type + enumValues: + - post + - sub + - unsub + required: true + - name: chs + type: array + description: > + Ticker subscription: `tickers::all` for every active + instrument, + + or `tickers::{iid}` (e.g. `tickers::1`) for a specific one. + required: true + properties: + - name: item + type: string + required: false + headers: [] + jsonPayloadSchema: + type: object + title: Base Request + properties: + id: + type: integer + description: Correlation ID for request-response matching + x-parser-schema-id: + req: + type: string + description: Request type + enum: + - post + - sub + - unsub + x-parser-schema-id: + chs: + type: array + description: | + Ticker subscription: `tickers::all` for every active instrument, + or `tickers::{iid}` (e.g. `tickers::1`) for a specific one. + items: + type: string + pattern: ^tickers::(\d+|all)$ + x-parser-schema-id: + example: + - tickers::all + x-parser-schema-id: + required: + - req + - chs + x-parser-schema-id: + title: Subscribe + description: Subscribe to ticker updates for all instruments or a specific one + example: |- + { + "req": "sub", + "chs": [ + "tickers::all" + ] + } + bindings: [] + extensions: + - id: x-parser-unique-object-id + value: SubscribeRequest + bindings: [] + extensions: &ref_0 + - id: x-parser-unique-object-id + value: tickers + - &ref_3 + id: TickersSubscribeResponse + title: Tickers subscribe response + description: Tickers subscribe response + type: send + messages: + - &ref_8 + id: SubscribeResponse + contentType: application/json + payload: + - name: Subscribe Response + description: Response to tickers subscribe request + type: object + properties: + - name: id + type: integer + description: Correlation ID for request-response matching + required: false + - name: data + type: array + title: Subscribe Response + required: true + properties: + - name: item + type: object + required: false + properties: + - name: status + type: string + enumValues: + - ok + required: true + - name: status + type: string + enumValues: + - err + required: true + - name: error + type: string + description: >- + Error identifier. For domain rejections and transport + errors (`401`/`404`/`429`/`500`) this is a stable, + machine-readable snake_case identifier that is part of + the API contract and safe to branch on, e.g. + `insufficient_margin`, `insufficient_balance`, + `order_not_found`, `reduce_only_invalid`, + `unauthorized`, `not_found`. For `400` it is a + human-readable validation detail whose wording may + change. See the Error handling guide for the domain + identifiers. (Post-only / Fill-or-Kill outcomes are + order statuses such as `post_only_rejected`, not + rejections.) + required: true + headers: [] + jsonPayloadSchema: + type: object + title: Base Response + properties: + id: + type: integer + description: Correlation ID for request-response matching + x-parser-schema-id: + data: + title: Subscribe Response + type: array + items: + oneOf: + - type: object + required: + - status + properties: + status: + type: string + enum: + - ok + x-parser-schema-id: + x-parser-schema-id: + - type: object + required: + - status + - error + properties: + status: + type: string + enum: + - err + x-parser-schema-id: + error: + type: string + description: >- + Error identifier. For domain rejections and transport + errors (`401`/`404`/`429`/`500`) this is a stable, + machine-readable snake_case identifier that is part of + the API contract and safe to branch on, e.g. + `insufficient_margin`, `insufficient_balance`, + `order_not_found`, `reduce_only_invalid`, + `unauthorized`, `not_found`. For `400` it is a + human-readable validation detail whose wording may + change. See the Error handling guide for the domain + identifiers. (Post-only / Fill-or-Kill outcomes are + order statuses such as `post_only_rejected`, not + rejections.) + example: insufficient_margin + x-parser-schema-id: + x-parser-schema-id: + x-parser-schema-id: + x-parser-schema-id: + required: + - data + x-parser-schema-id: + title: Subscribe Response + description: Response to tickers subscribe request + example: |- + { + "data": [] + } + bindings: [] + extensions: + - id: x-parser-unique-object-id + value: SubscribeResponse + bindings: [] + extensions: *ref_0 + - &ref_2 + id: TickersUnsubscribe + title: Tickers unsubscribe + description: Unsubscribe from tickers + type: receive + messages: + - &ref_7 + id: UnsubscribeRequest + contentType: application/json + payload: + - name: Unsubscribe + description: Unsubscribe from ticker updates + type: object + properties: + - name: id + type: integer + description: Correlation ID for request-response matching + required: false + - name: req + type: string + description: Request type + enumValues: + - post + - sub + - unsub + required: true + - name: chs + type: array + description: > + Ticker subscription: `tickers::all` for every active + instrument, + + or `tickers::{iid}` (e.g. `tickers::1`) for a specific one. + required: true + properties: + - name: item + type: string + required: false + headers: [] + jsonPayloadSchema: + type: object + title: Base Request + properties: + id: + type: integer + description: Correlation ID for request-response matching + x-parser-schema-id: + req: + type: string + description: Request type + enum: + - post + - sub + - unsub + x-parser-schema-id: + chs: + type: array + description: | + Ticker subscription: `tickers::all` for every active instrument, + or `tickers::{iid}` (e.g. `tickers::1`) for a specific one. + items: + type: string + pattern: ^tickers::(\d+|all)$ + x-parser-schema-id: + example: + - tickers::all + x-parser-schema-id: + required: + - req + - chs + x-parser-schema-id: + title: Unsubscribe + description: Unsubscribe from ticker updates + example: |- + { + "req": "unsub", + "chs": [ + "tickers::all" + ] + } + bindings: [] + extensions: + - id: x-parser-unique-object-id + value: UnsubscribeRequest + bindings: [] + extensions: *ref_0 + - &ref_4 + id: TickersUnsubscribeResponse + title: Tickers unsubscribe response + description: Tickers unsubscribe response + type: send + messages: + - &ref_9 + id: UnsubscribeResponse + contentType: application/json + payload: + - name: Unsubscribe Response + description: Response to tickers unsubscribe request + type: object + properties: + - name: id + type: integer + description: Correlation ID for request-response matching + required: false + - name: data + type: array + title: Subscribe Response + required: true + properties: + - name: item + type: object + required: false + properties: + - name: status + type: string + enumValues: + - ok + required: true + - name: status + type: string + enumValues: + - err + required: true + - name: error + type: string + description: >- + Error identifier. For domain rejections and transport + errors (`401`/`404`/`429`/`500`) this is a stable, + machine-readable snake_case identifier that is part of + the API contract and safe to branch on, e.g. + `insufficient_margin`, `insufficient_balance`, + `order_not_found`, `reduce_only_invalid`, + `unauthorized`, `not_found`. For `400` it is a + human-readable validation detail whose wording may + change. See the Error handling guide for the domain + identifiers. (Post-only / Fill-or-Kill outcomes are + order statuses such as `post_only_rejected`, not + rejections.) + required: true + headers: [] + jsonPayloadSchema: + type: object + title: Base Response + properties: + id: + type: integer + description: Correlation ID for request-response matching + x-parser-schema-id: + data: + title: Subscribe Response + type: array + items: + oneOf: + - type: object + required: + - status + properties: + status: + type: string + enum: + - ok + x-parser-schema-id: + x-parser-schema-id: + - type: object + required: + - status + - error + properties: + status: + type: string + enum: + - err + x-parser-schema-id: + error: + type: string + description: >- + Error identifier. For domain rejections and transport + errors (`401`/`404`/`429`/`500`) this is a stable, + machine-readable snake_case identifier that is part of + the API contract and safe to branch on, e.g. + `insufficient_margin`, `insufficient_balance`, + `order_not_found`, `reduce_only_invalid`, + `unauthorized`, `not_found`. For `400` it is a + human-readable validation detail whose wording may + change. See the Error handling guide for the domain + identifiers. (Post-only / Fill-or-Kill outcomes are + order statuses such as `post_only_rejected`, not + rejections.) + example: insufficient_margin + x-parser-schema-id: + x-parser-schema-id: + x-parser-schema-id: + x-parser-schema-id: + required: + - data + x-parser-schema-id: + title: Unsubscribe Response + description: Response to tickers unsubscribe request + example: |- + { + "data": [] + } + bindings: [] + extensions: + - id: x-parser-unique-object-id + value: UnsubscribeResponse + bindings: [] + extensions: *ref_0 + - &ref_5 + id: TickersUpdate + title: Tickers update + description: Receive ticker updates + type: send + messages: + - &ref_10 + id: Update + contentType: application/json + payload: + - name: Update + description: Real-time ticker updates for subscribed instruments + type: object + properties: + - name: ch + type: string + description: >- + Channel name for push data. Parameterized channels include the + instrument ID (e.g. "trades::1", "book::1", "klines::1::1m", + "tickers::all"). Private channels use plain names (e.g. + "fills", "orders"). + required: true + - name: ts + type: integer + description: >- + Request timestamp. Unix milliseconds for most operations; Unix + seconds for withdrawals (must match the on-chain EIP-712 + struct verified against block.timestamp). + required: true + - name: sq + type: integer + description: Sequence number + required: true + - name: data + type: object + description: Array of ticker objects + required: true + properties: + - name: iid + type: integer + description: Instrument ID + required: true + - name: idx + type: string + description: Index price + required: true + - name: mark + type: string + description: Mark price + required: true + - name: last + type: string + description: Last traded price + required: true + - name: mid + type: string + description: Mid price + required: true + - name: oi + type: string + description: Open interest in number of contracts + required: true + - name: fr + type: string + description: Funding rate + required: true + - name: nxf + type: integer + description: Next funding timestamp in milliseconds + required: true + headers: [] + jsonPayloadSchema: + title: Ticker Update + type: object + properties: + ch: + type: string + description: >- + Channel name for push data. Parameterized channels include the + instrument ID (e.g. "trades::1", "book::1", "klines::1::1m", + "tickers::all"). Private channels use plain names (e.g. "fills", + "orders"). + example: trades::1 + x-parser-schema-id: + ts: + type: integer + description: >- + Request timestamp. Unix milliseconds for most operations; Unix + seconds for withdrawals (must match the on-chain EIP-712 struct + verified against block.timestamp). + example: 1767225600000 + x-parser-schema-id: + sq: + type: integer + description: Sequence number + example: 1234567890 + x-parser-schema-id: + data: + type: object + description: Array of ticker objects + properties: + iid: + type: integer + description: Instrument ID + example: 1 + x-parser-schema-id: + idx: + type: string + description: Index price + example: '100.00' + x-parser-schema-id: + mark: + type: string + description: Mark price + example: '100.00' + x-parser-schema-id: + last: + type: string + description: Last traded price + example: '100.00' + x-parser-schema-id: + mid: + type: string + description: Mid price + example: '100.00' + x-parser-schema-id: + oi: + type: string + description: Open interest in number of contracts + example: '10.00' + x-parser-schema-id: + fr: + type: string + description: Funding rate + example: '0.0001' + x-parser-schema-id: + nxf: + type: integer + description: Next funding timestamp in milliseconds + example: 1767225600000 + x-parser-schema-id: + required: + - iid + - idx + - mark + - last + - mid + - oi + - fr + - nxf + x-parser-schema-id: + required: + - ch + - ts + - sq + - data + x-parser-schema-id: + title: Update + description: Real-time ticker updates for subscribed instruments + example: |- + { + "ch": "tickers::all", + "ts": 1767225600000, + "sq": 1234567890, + "data": [ + { + "iid": 1, + "idx": "100.00", + "mark": "100.00", + "last": "100.00", + "mid": "100.00", + "oi": "10.00", + "fr": "0.0001", + "nxf": 1767225600000 + } + ] + } + bindings: [] + extensions: + - id: x-parser-unique-object-id + value: Update + bindings: [] + extensions: *ref_0 +sendOperations: + - *ref_1 + - *ref_2 +receiveOperations: + - *ref_3 + - *ref_4 + - *ref_5 +sendMessages: + - *ref_6 + - *ref_7 +receiveMessages: + - *ref_8 + - *ref_9 + - *ref_10 +extensions: + - id: x-parser-unique-object-id + value: tickers +securitySchemes: [] + +```` \ No newline at end of file diff --git a/PolymarketDocumentation-main/docs/api-reference/wss/perps-trades.md b/PolymarketDocumentation-main/docs/api-reference/wss/perps-trades.md new file mode 100644 index 00000000..d1942228 --- /dev/null +++ b/PolymarketDocumentation-main/docs/api-reference/wss/perps-trades.md @@ -0,0 +1,647 @@ +> ## Documentation Index +> Fetch the complete documentation index at: https://docs.polymarket.com/llms.txt +> Use this file to discover all available pages before exploring further. + +# Trades + +> Perps WebSocket public trade updates. + + + +## AsyncAPI + +````yaml asyncapi-perps.json trades +id: trades +title: Trades +description: Real-time trade stream. +servers: + - id: production + protocol: wss + host: ws.perpetuals.polymarket.com + bindings: [] + variables: [] +address: /v1/ws +parameters: [] +bindings: [] +operations: + - &ref_1 + id: TradesSubscribe + title: Trades subscribe + description: Subscribe to trades + type: receive + messages: + - &ref_6 + id: SubscribeRequest + contentType: application/json + payload: + - name: Subscribe + description: Subscribe to public trade updates for an instrument + type: object + properties: + - name: id + type: integer + description: Correlation ID for request-response matching + required: false + - name: req + type: string + description: Request type + enumValues: + - post + - sub + - unsub + required: true + - name: chs + type: array + description: >- + Trades subscription in format "trades::{iid}" (e.g., + "trades::1") + required: true + properties: + - name: item + type: string + required: false + headers: [] + jsonPayloadSchema: + type: object + title: Base Request + properties: + id: + type: integer + description: Correlation ID for request-response matching + x-parser-schema-id: + req: + type: string + description: Request type + enum: + - post + - sub + - unsub + x-parser-schema-id: + chs: + type: array + description: >- + Trades subscription in format "trades::{iid}" (e.g., + "trades::1") + items: + type: string + pattern: ^trades::\d+$ + x-parser-schema-id: + example: + - trades::1 + x-parser-schema-id: + required: + - req + - chs + x-parser-schema-id: + title: Subscribe + description: Subscribe to public trade updates for an instrument + example: |- + { + "req": "sub", + "chs": [ + "trades::1" + ] + } + bindings: [] + extensions: + - id: x-parser-unique-object-id + value: SubscribeRequest + bindings: [] + extensions: &ref_0 + - id: x-parser-unique-object-id + value: trades + - &ref_3 + id: TradesSubscribeResponse + title: Trades subscribe response + description: Trades subscribe response + type: send + messages: + - &ref_8 + id: SubscribeResponse + contentType: application/json + payload: + - name: Subscribe Response + description: Response to trades subscribe request + type: object + properties: + - name: id + type: integer + description: Correlation ID for request-response matching + required: false + - name: data + type: array + title: Subscribe Response + required: true + properties: + - name: item + type: object + required: false + properties: + - name: status + type: string + enumValues: + - ok + required: true + - name: status + type: string + enumValues: + - err + required: true + - name: error + type: string + description: >- + Error identifier. For domain rejections and transport + errors (`401`/`404`/`429`/`500`) this is a stable, + machine-readable snake_case identifier that is part of + the API contract and safe to branch on, e.g. + `insufficient_margin`, `insufficient_balance`, + `order_not_found`, `reduce_only_invalid`, + `unauthorized`, `not_found`. For `400` it is a + human-readable validation detail whose wording may + change. See the Error handling guide for the domain + identifiers. (Post-only / Fill-or-Kill outcomes are + order statuses such as `post_only_rejected`, not + rejections.) + required: true + headers: [] + jsonPayloadSchema: + type: object + title: Base Response + properties: + id: + type: integer + description: Correlation ID for request-response matching + x-parser-schema-id: + data: + title: Subscribe Response + type: array + items: + oneOf: + - type: object + required: + - status + properties: + status: + type: string + enum: + - ok + x-parser-schema-id: + x-parser-schema-id: + - type: object + required: + - status + - error + properties: + status: + type: string + enum: + - err + x-parser-schema-id: + error: + type: string + description: >- + Error identifier. For domain rejections and transport + errors (`401`/`404`/`429`/`500`) this is a stable, + machine-readable snake_case identifier that is part of + the API contract and safe to branch on, e.g. + `insufficient_margin`, `insufficient_balance`, + `order_not_found`, `reduce_only_invalid`, + `unauthorized`, `not_found`. For `400` it is a + human-readable validation detail whose wording may + change. See the Error handling guide for the domain + identifiers. (Post-only / Fill-or-Kill outcomes are + order statuses such as `post_only_rejected`, not + rejections.) + example: insufficient_margin + x-parser-schema-id: + x-parser-schema-id: + x-parser-schema-id: + x-parser-schema-id: + required: + - data + x-parser-schema-id: + title: Subscribe Response + description: Response to trades subscribe request + example: |- + { + "data": [] + } + bindings: [] + extensions: + - id: x-parser-unique-object-id + value: SubscribeResponse + bindings: [] + extensions: *ref_0 + - &ref_2 + id: TradesUnsubscribe + title: Trades unsubscribe + description: Unsubscribe from trades + type: receive + messages: + - &ref_7 + id: UnsubscribeRequest + contentType: application/json + payload: + - name: Unsubscribe + description: Unsubscribe from public trade updates + type: object + properties: + - name: id + type: integer + description: Correlation ID for request-response matching + required: false + - name: req + type: string + description: Request type + enumValues: + - post + - sub + - unsub + required: true + - name: chs + type: array + description: >- + Trades subscription in format "trades::{iid}" (e.g., + "trades::1") + required: true + properties: + - name: item + type: string + required: false + headers: [] + jsonPayloadSchema: + type: object + title: Base Request + properties: + id: + type: integer + description: Correlation ID for request-response matching + x-parser-schema-id: + req: + type: string + description: Request type + enum: + - post + - sub + - unsub + x-parser-schema-id: + chs: + type: array + description: >- + Trades subscription in format "trades::{iid}" (e.g., + "trades::1") + items: + type: string + pattern: ^trades::\d+$ + x-parser-schema-id: + example: + - trades::1 + x-parser-schema-id: + required: + - req + - chs + x-parser-schema-id: + title: Unsubscribe + description: Unsubscribe from public trade updates + example: |- + { + "req": "unsub", + "chs": [ + "trades::1" + ] + } + bindings: [] + extensions: + - id: x-parser-unique-object-id + value: UnsubscribeRequest + bindings: [] + extensions: *ref_0 + - &ref_4 + id: TradesUnsubscribeResponse + title: Trades unsubscribe response + description: Trades unsubscribe response + type: send + messages: + - &ref_9 + id: UnsubscribeResponse + contentType: application/json + payload: + - name: Unsubscribe Response + description: Response to trades unsubscribe request + type: object + properties: + - name: id + type: integer + description: Correlation ID for request-response matching + required: false + - name: data + type: array + title: Subscribe Response + required: true + properties: + - name: item + type: object + required: false + properties: + - name: status + type: string + enumValues: + - ok + required: true + - name: status + type: string + enumValues: + - err + required: true + - name: error + type: string + description: >- + Error identifier. For domain rejections and transport + errors (`401`/`404`/`429`/`500`) this is a stable, + machine-readable snake_case identifier that is part of + the API contract and safe to branch on, e.g. + `insufficient_margin`, `insufficient_balance`, + `order_not_found`, `reduce_only_invalid`, + `unauthorized`, `not_found`. For `400` it is a + human-readable validation detail whose wording may + change. See the Error handling guide for the domain + identifiers. (Post-only / Fill-or-Kill outcomes are + order statuses such as `post_only_rejected`, not + rejections.) + required: true + headers: [] + jsonPayloadSchema: + type: object + title: Base Response + properties: + id: + type: integer + description: Correlation ID for request-response matching + x-parser-schema-id: + data: + title: Subscribe Response + type: array + items: + oneOf: + - type: object + required: + - status + properties: + status: + type: string + enum: + - ok + x-parser-schema-id: + x-parser-schema-id: + - type: object + required: + - status + - error + properties: + status: + type: string + enum: + - err + x-parser-schema-id: + error: + type: string + description: >- + Error identifier. For domain rejections and transport + errors (`401`/`404`/`429`/`500`) this is a stable, + machine-readable snake_case identifier that is part of + the API contract and safe to branch on, e.g. + `insufficient_margin`, `insufficient_balance`, + `order_not_found`, `reduce_only_invalid`, + `unauthorized`, `not_found`. For `400` it is a + human-readable validation detail whose wording may + change. See the Error handling guide for the domain + identifiers. (Post-only / Fill-or-Kill outcomes are + order statuses such as `post_only_rejected`, not + rejections.) + example: insufficient_margin + x-parser-schema-id: + x-parser-schema-id: + x-parser-schema-id: + x-parser-schema-id: + required: + - data + x-parser-schema-id: + title: Unsubscribe Response + description: Response to trades unsubscribe request + example: |- + { + "data": [] + } + bindings: [] + extensions: + - id: x-parser-unique-object-id + value: UnsubscribeResponse + bindings: [] + extensions: *ref_0 + - &ref_5 + id: TradesUpdate + title: Trades update + description: Receive trade updates + type: send + messages: + - &ref_10 + id: Update + contentType: application/json + payload: + - name: Update + description: Real-time trade updates for subscribed instruments + type: object + properties: + - name: ch + type: string + description: >- + Channel name for push data. Parameterized channels include the + instrument ID (e.g. "trades::1", "book::1", "klines::1::1m", + "tickers::all"). Private channels use plain names (e.g. + "fills", "orders"). + required: true + - name: ts + type: integer + description: >- + Request timestamp. Unix milliseconds for most operations; Unix + seconds for withdrawals (must match the on-chain EIP-712 + struct verified against block.timestamp). + required: true + - name: sq + type: integer + description: Sequence number + required: true + - name: data + type: object + title: TradeResponse + description: Array of trade objects + required: true + properties: + - name: tid + type: integer + description: Trade ID + required: true + - name: iid + type: integer + description: Instrument ID + required: true + - name: side + type: string + description: Side + enumValues: + - long + - short + required: true + - name: p + type: string + description: Price + required: true + - name: qty + type: string + description: Quantity in no. of contracts + required: true + - name: ts + type: integer + description: >- + Request timestamp. Unix milliseconds for most operations; + Unix seconds for withdrawals (must match the on-chain + EIP-712 struct verified against block.timestamp). + required: true + - name: hash + type: string + description: On-chain transaction hash, "0x" if not yet mined + required: true + headers: [] + jsonPayloadSchema: + title: Trades Update + type: object + properties: + ch: + type: string + description: >- + Channel name for push data. Parameterized channels include the + instrument ID (e.g. "trades::1", "book::1", "klines::1::1m", + "tickers::all"). Private channels use plain names (e.g. "fills", + "orders"). + example: trades::1 + x-parser-schema-id: + ts: + type: integer + description: >- + Request timestamp. Unix milliseconds for most operations; Unix + seconds for withdrawals (must match the on-chain EIP-712 struct + verified against block.timestamp). + example: 1767225600000 + x-parser-schema-id: + sq: + type: integer + description: Sequence number + example: 1234567890 + x-parser-schema-id: + data: + type: object + description: Array of trade objects + title: TradeResponse + properties: + tid: + type: integer + description: Trade ID + example: 1 + x-parser-schema-id: + iid: + type: integer + description: Instrument ID + example: 1 + x-parser-schema-id: + side: + type: string + description: Side + enum: + - long + - short + x-parser-schema-id: + p: + type: string + description: Price + example: '100.00' + x-parser-schema-id: + qty: + type: string + description: Quantity in no. of contracts + example: '10.00' + x-parser-schema-id: + ts: + type: integer + description: >- + Request timestamp. Unix milliseconds for most operations; + Unix seconds for withdrawals (must match the on-chain + EIP-712 struct verified against block.timestamp). + example: 1767225600000 + x-parser-schema-id: + hash: + type: string + description: On-chain transaction hash, "0x" if not yet mined + default: 0x + example: >- + 0x1234567890abcdef1234567890abcdef1234567890abcdef1234567890abcdef + x-parser-schema-id: + required: + - tid + - iid + - side + - p + - qty + - ts + - hash + x-parser-schema-id: + required: + - ch + - ts + - sq + - data + x-parser-schema-id: + title: Update + description: Real-time trade updates for subscribed instruments + example: |- + { + "ch": "trades::1", + "ts": 1767225600000, + "sq": 1234567890, + "data": [ + { + "tid": 1, + "iid": 1, + "side": "long", + "p": "100.00", + "qty": "10.00", + "ts": 1767225600000, + "hash": "0x1234567890abcdef1234567890abcdef1234567890abcdef1234567890abcdef" + } + ] + } + bindings: [] + extensions: + - id: x-parser-unique-object-id + value: Update + bindings: [] + extensions: *ref_0 +sendOperations: + - *ref_1 + - *ref_2 +receiveOperations: + - *ref_3 + - *ref_4 + - *ref_5 +sendMessages: + - *ref_6 + - *ref_7 +receiveMessages: + - *ref_8 + - *ref_9 + - *ref_10 +extensions: + - id: x-parser-unique-object-id + value: trades +securitySchemes: [] + +```` \ No newline at end of file diff --git a/PolymarketDocumentation-main/docs/api-reference/wss/perps-update-leverage.md b/PolymarketDocumentation-main/docs/api-reference/wss/perps-update-leverage.md new file mode 100644 index 00000000..84142540 --- /dev/null +++ b/PolymarketDocumentation-main/docs/api-reference/wss/perps-update-leverage.md @@ -0,0 +1,325 @@ +> ## Documentation Index +> Fetch the complete documentation index at: https://docs.polymarket.com/llms.txt +> Use this file to discover all available pages before exploring further. + +# Update Leverage + +> Perps WebSocket leverage updates. + + + +## AsyncAPI + +````yaml asyncapi-perps.json updateLeverage +id: updateLeverage +title: Update Leverage +description: | + Set leverage and margin type for an instrument. + Requires proxy signature, see [proxy signing](/http/signing#2-proxy-signing). + + Action Weight: **1** +servers: + - id: production + protocol: wss + host: ws.perpetuals.polymarket.com + bindings: [] + variables: [] +address: /v1/ws +parameters: [] +bindings: [] +operations: + - &ref_1 + id: UpdateLeverageSend + title: Update leverage send + description: Update leverage + type: receive + messages: + - &ref_3 + id: Request + contentType: application/json + payload: + - name: Update Leverage Request + description: Client submits a signed leverage update request + type: object + properties: + - name: id + type: integer + description: Correlation ID for request-response matching + required: false + - name: req + type: string + description: Request type + enumValues: + - post + - sub + - unsub + required: true + - name: op + type: object + required: true + properties: + - name: type + type: string + enumValues: + - updateLeverage + required: true + - name: args + type: object + required: true + properties: + - name: iid + type: integer + description: Instrument ID + required: true + - name: lev + type: integer + description: Leverage + required: true + - name: cross + type: boolean + description: Whether to use cross margin mode + required: true + - name: sig + type: string + description: Signature in hex format + required: true + - name: salt + type: integer + description: Salt + required: true + - name: ts + type: integer + description: >- + Request timestamp. Unix milliseconds for most operations; Unix + seconds for withdrawals (must match the on-chain EIP-712 + struct verified against block.timestamp). + required: true + headers: [] + jsonPayloadSchema: + type: object + title: Base Request + properties: + id: + type: integer + description: Correlation ID for request-response matching + x-parser-schema-id: + req: + type: string + description: Request type + enum: + - post + - sub + - unsub + x-parser-schema-id: + op: + type: object + required: + - type + - args + properties: + type: + type: string + enum: + - updateLeverage + x-parser-schema-id: + args: + type: object + required: + - iid + - lev + - cross + properties: + iid: + type: integer + description: Instrument ID + example: 1 + x-parser-schema-id: + lev: + type: integer + description: Leverage + example: 10 + x-parser-schema-id: + cross: + type: boolean + description: Whether to use cross margin mode + x-parser-schema-id: + x-parser-schema-id: + x-parser-schema-id: + sig: + type: string + description: Signature in hex format + example: 0x1234567890... + x-parser-schema-id: + salt: + type: integer + description: Salt + example: 1234567890 + x-parser-schema-id: + ts: + type: integer + description: >- + Request timestamp. Unix milliseconds for most operations; Unix + seconds for withdrawals (must match the on-chain EIP-712 struct + verified against block.timestamp). + example: 1767225600000 + x-parser-schema-id: + required: + - req + - op + - sig + - salt + - ts + x-parser-schema-id: + title: Update Leverage Request + description: Client submits a signed leverage update request + example: |- + { + "req": "post", + "op": { + "type": "updateLeverage", + "args": { + "iid": 1, + "lev": 10 + } + }, + "sig": "0x1234567890...", + "salt": 1234567890, + "ts": 1767225600000 + } + bindings: [] + extensions: + - id: x-parser-unique-object-id + value: Request + bindings: [] + extensions: &ref_0 + - id: x-parser-unique-object-id + value: updateLeverage + - &ref_2 + id: UpdateLeverageReceive + title: Update leverage receive + description: Update leverage response + type: send + messages: + - &ref_4 + id: Response + contentType: application/json + payload: + - name: Update Leverage Response + description: Server responds with leverage update result + type: object + properties: + - name: id + type: integer + description: Correlation ID for request-response matching + required: false + - name: data + type: object + required: true + properties: + - name: status + type: string + enumValues: + - ok + required: true + - name: status + type: string + enumValues: + - err + required: true + - name: error + type: string + description: >- + Error identifier. For domain rejections and transport + errors (`401`/`404`/`429`/`500`) this is a stable, + machine-readable snake_case identifier that is part of the + API contract and safe to branch on, e.g. + `insufficient_margin`, `insufficient_balance`, + `order_not_found`, `reduce_only_invalid`, `unauthorized`, + `not_found`. For `400` it is a human-readable validation + detail whose wording may change. See the Error handling + guide for the domain identifiers. (Post-only / + Fill-or-Kill outcomes are order statuses such as + `post_only_rejected`, not rejections.) + required: true + headers: [] + jsonPayloadSchema: + type: object + title: Base Response + properties: + id: + type: integer + description: Correlation ID for request-response matching + x-parser-schema-id: + data: + oneOf: + - type: object + required: + - status + properties: + status: + type: string + enum: + - ok + x-parser-schema-id: + x-parser-schema-id: + - type: object + required: + - status + - error + properties: + status: + type: string + enum: + - err + x-parser-schema-id: + error: + type: string + description: >- + Error identifier. For domain rejections and transport + errors (`401`/`404`/`429`/`500`) this is a stable, + machine-readable snake_case identifier that is part of + the API contract and safe to branch on, e.g. + `insufficient_margin`, `insufficient_balance`, + `order_not_found`, `reduce_only_invalid`, + `unauthorized`, `not_found`. For `400` it is a + human-readable validation detail whose wording may + change. See the Error handling guide for the domain + identifiers. (Post-only / Fill-or-Kill outcomes are + order statuses such as `post_only_rejected`, not + rejections.) + example: insufficient_margin + x-parser-schema-id: + x-parser-schema-id: + x-parser-schema-id: + required: + - data + x-parser-schema-id: + title: Update Leverage Response + description: Server responds with leverage update result + example: |- + { + "id": 6, + "data": { + "status": "ok" + } + } + bindings: [] + extensions: + - id: x-parser-unique-object-id + value: Response + bindings: [] + extensions: *ref_0 +sendOperations: + - *ref_1 +receiveOperations: + - *ref_2 +sendMessages: + - *ref_3 +receiveMessages: + - *ref_4 +extensions: + - id: x-parser-unique-object-id + value: updateLeverage +securitySchemes: [] + +```` \ No newline at end of file diff --git a/PolymarketDocumentation-main/docs/api-reference/wss/perps-withdrawals.md b/PolymarketDocumentation-main/docs/api-reference/wss/perps-withdrawals.md new file mode 100644 index 00000000..9214d207 --- /dev/null +++ b/PolymarketDocumentation-main/docs/api-reference/wss/perps-withdrawals.md @@ -0,0 +1,647 @@ +> ## Documentation Index +> Fetch the complete documentation index at: https://docs.polymarket.com/llms.txt +> Use this file to discover all available pages before exploring further. + +# Withdrawals + +> Perps WebSocket private withdrawal updates. + + + +## AsyncAPI + +````yaml asyncapi-perps.json withdrawals +id: withdrawals +title: Withdrawals +description: >- + Real-time withdrawal status updates. Requires authentication, see + [Auth](/ws/auth). +servers: + - id: production + protocol: wss + host: ws.perpetuals.polymarket.com + bindings: [] + variables: [] +address: /v1/ws +parameters: [] +bindings: [] +operations: + - &ref_1 + id: WithdrawalsSubscribe + title: Withdrawals subscribe + description: Subscribe to withdrawals + type: receive + messages: + - &ref_6 + id: SubscribeRequest + contentType: application/json + payload: + - name: Subscribe + description: Subscribe to private withdrawal updates (requires prior auth) + type: object + properties: + - name: id + type: integer + description: Correlation ID for request-response matching + required: false + - name: req + type: string + description: Request type + enumValues: + - post + - sub + - unsub + required: true + - name: chs + type: array + description: 'Withdrawals private channel: "withdrawals"' + required: true + properties: + - name: item + type: string + enumValues: + - withdrawals + required: false + headers: [] + jsonPayloadSchema: + type: object + title: Base Request + properties: + id: + type: integer + description: Correlation ID for request-response matching + x-parser-schema-id: + req: + type: string + description: Request type + enum: + - post + - sub + - unsub + x-parser-schema-id: + chs: + type: array + description: 'Withdrawals private channel: "withdrawals"' + items: + type: string + enum: + - withdrawals + x-parser-schema-id: + example: + - withdrawals + x-parser-schema-id: + required: + - req + - chs + x-parser-schema-id: + title: Subscribe + description: Subscribe to private withdrawal updates (requires prior auth) + example: |- + { + "req": "sub", + "chs": [ + "withdrawals" + ] + } + bindings: [] + extensions: + - id: x-parser-unique-object-id + value: SubscribeRequest + bindings: [] + extensions: &ref_0 + - id: x-parser-unique-object-id + value: withdrawals + - &ref_3 + id: WithdrawalsSubscribeResponse + title: Withdrawals subscribe response + description: Withdrawals subscribe response + type: send + messages: + - &ref_8 + id: SubscribeResponse + contentType: application/json + payload: + - name: Subscribe Response + description: Response to withdrawals subscribe request + type: object + properties: + - name: id + type: integer + description: Correlation ID for request-response matching + required: false + - name: data + type: array + title: Subscribe Response + required: true + properties: + - name: item + type: object + required: false + properties: + - name: status + type: string + enumValues: + - ok + required: true + - name: status + type: string + enumValues: + - err + required: true + - name: error + type: string + description: >- + Error identifier. For domain rejections and transport + errors (`401`/`404`/`429`/`500`) this is a stable, + machine-readable snake_case identifier that is part of + the API contract and safe to branch on, e.g. + `insufficient_margin`, `insufficient_balance`, + `order_not_found`, `reduce_only_invalid`, + `unauthorized`, `not_found`. For `400` it is a + human-readable validation detail whose wording may + change. See the Error handling guide for the domain + identifiers. (Post-only / Fill-or-Kill outcomes are + order statuses such as `post_only_rejected`, not + rejections.) + required: true + headers: [] + jsonPayloadSchema: + type: object + title: Base Response + properties: + id: + type: integer + description: Correlation ID for request-response matching + x-parser-schema-id: + data: + title: Subscribe Response + type: array + items: + oneOf: + - type: object + required: + - status + properties: + status: + type: string + enum: + - ok + x-parser-schema-id: + x-parser-schema-id: + - type: object + required: + - status + - error + properties: + status: + type: string + enum: + - err + x-parser-schema-id: + error: + type: string + description: >- + Error identifier. For domain rejections and transport + errors (`401`/`404`/`429`/`500`) this is a stable, + machine-readable snake_case identifier that is part of + the API contract and safe to branch on, e.g. + `insufficient_margin`, `insufficient_balance`, + `order_not_found`, `reduce_only_invalid`, + `unauthorized`, `not_found`. For `400` it is a + human-readable validation detail whose wording may + change. See the Error handling guide for the domain + identifiers. (Post-only / Fill-or-Kill outcomes are + order statuses such as `post_only_rejected`, not + rejections.) + example: insufficient_margin + x-parser-schema-id: + x-parser-schema-id: + x-parser-schema-id: + x-parser-schema-id: + required: + - data + x-parser-schema-id: + title: Subscribe Response + description: Response to withdrawals subscribe request + example: |- + { + "data": [] + } + bindings: [] + extensions: + - id: x-parser-unique-object-id + value: SubscribeResponse + bindings: [] + extensions: *ref_0 + - &ref_2 + id: WithdrawalsUnsubscribe + title: Withdrawals unsubscribe + description: Unsubscribe from withdrawals + type: receive + messages: + - &ref_7 + id: UnsubscribeRequest + contentType: application/json + payload: + - name: Unsubscribe + description: Unsubscribe from private withdrawal updates + type: object + properties: + - name: id + type: integer + description: Correlation ID for request-response matching + required: false + - name: req + type: string + description: Request type + enumValues: + - post + - sub + - unsub + required: true + - name: chs + type: array + description: 'Withdrawals private channel: "withdrawals"' + required: true + properties: + - name: item + type: string + enumValues: + - withdrawals + required: false + headers: [] + jsonPayloadSchema: + type: object + title: Base Request + properties: + id: + type: integer + description: Correlation ID for request-response matching + x-parser-schema-id: + req: + type: string + description: Request type + enum: + - post + - sub + - unsub + x-parser-schema-id: + chs: + type: array + description: 'Withdrawals private channel: "withdrawals"' + items: + type: string + enum: + - withdrawals + x-parser-schema-id: + example: + - withdrawals + x-parser-schema-id: + required: + - req + - chs + x-parser-schema-id: + title: Unsubscribe + description: Unsubscribe from private withdrawal updates + example: |- + { + "req": "unsub", + "chs": [ + "withdrawals" + ] + } + bindings: [] + extensions: + - id: x-parser-unique-object-id + value: UnsubscribeRequest + bindings: [] + extensions: *ref_0 + - &ref_4 + id: WithdrawalsUnsubscribeResponse + title: Withdrawals unsubscribe response + description: Withdrawals unsubscribe response + type: send + messages: + - &ref_9 + id: UnsubscribeResponse + contentType: application/json + payload: + - name: Unsubscribe Response + description: Response to withdrawals unsubscribe request + type: object + properties: + - name: id + type: integer + description: Correlation ID for request-response matching + required: false + - name: data + type: array + title: Subscribe Response + required: true + properties: + - name: item + type: object + required: false + properties: + - name: status + type: string + enumValues: + - ok + required: true + - name: status + type: string + enumValues: + - err + required: true + - name: error + type: string + description: >- + Error identifier. For domain rejections and transport + errors (`401`/`404`/`429`/`500`) this is a stable, + machine-readable snake_case identifier that is part of + the API contract and safe to branch on, e.g. + `insufficient_margin`, `insufficient_balance`, + `order_not_found`, `reduce_only_invalid`, + `unauthorized`, `not_found`. For `400` it is a + human-readable validation detail whose wording may + change. See the Error handling guide for the domain + identifiers. (Post-only / Fill-or-Kill outcomes are + order statuses such as `post_only_rejected`, not + rejections.) + required: true + headers: [] + jsonPayloadSchema: + type: object + title: Base Response + properties: + id: + type: integer + description: Correlation ID for request-response matching + x-parser-schema-id: + data: + title: Subscribe Response + type: array + items: + oneOf: + - type: object + required: + - status + properties: + status: + type: string + enum: + - ok + x-parser-schema-id: + x-parser-schema-id: + - type: object + required: + - status + - error + properties: + status: + type: string + enum: + - err + x-parser-schema-id: + error: + type: string + description: >- + Error identifier. For domain rejections and transport + errors (`401`/`404`/`429`/`500`) this is a stable, + machine-readable snake_case identifier that is part of + the API contract and safe to branch on, e.g. + `insufficient_margin`, `insufficient_balance`, + `order_not_found`, `reduce_only_invalid`, + `unauthorized`, `not_found`. For `400` it is a + human-readable validation detail whose wording may + change. See the Error handling guide for the domain + identifiers. (Post-only / Fill-or-Kill outcomes are + order statuses such as `post_only_rejected`, not + rejections.) + example: insufficient_margin + x-parser-schema-id: + x-parser-schema-id: + x-parser-schema-id: + x-parser-schema-id: + required: + - data + x-parser-schema-id: + title: Unsubscribe Response + description: Response to withdrawals unsubscribe request + example: |- + { + "data": [] + } + bindings: [] + extensions: + - id: x-parser-unique-object-id + value: UnsubscribeResponse + bindings: [] + extensions: *ref_0 + - &ref_5 + id: WithdrawalsUpdate + title: Withdrawals update + description: Receive withdrawal updates + type: send + messages: + - &ref_10 + id: Update + contentType: application/json + payload: + - name: Update + description: Withdrawal status updates for authenticated users + type: object + properties: + - name: ch + type: string + description: >- + Channel name for push data. Parameterized channels include the + instrument ID (e.g. "trades::1", "book::1", "klines::1::1m", + "tickers::all"). Private channels use plain names (e.g. + "fills", "orders"). + required: true + - name: ts + type: integer + description: >- + Request timestamp. Unix milliseconds for most operations; Unix + seconds for withdrawals (must match the on-chain EIP-712 + struct verified against block.timestamp). + required: true + - name: sq + type: integer + description: Sequence number + required: true + - name: data + type: object + description: Array of withdrawal objects + required: true + properties: + - name: withdraw_id + type: integer + description: Withdraw ID + required: true + - name: asset + type: string + description: Asset name + required: true + - name: amount + type: string + description: >- + Raw token amount including decimals. For withdrawals this + matches the uint256 amount in the EIP-712 signature (e.g. + "100000000" for 100 USDC with 6 decimals). + required: true + - name: fee + type: string + description: Withdrawal transaction fee in decimalized asset units + required: true + - name: to + type: string + description: Destination address in hex format + required: true + - name: status + type: string + description: Withdrawal status + enumValues: + - pending + - confirmed + - removed + - failed + required: true + - name: hash + type: string + description: On-chain transaction hash, "0x" if not yet mined + required: true + headers: [] + jsonPayloadSchema: + title: Withdrawals Update + type: object + properties: + ch: + type: string + description: >- + Channel name for push data. Parameterized channels include the + instrument ID (e.g. "trades::1", "book::1", "klines::1::1m", + "tickers::all"). Private channels use plain names (e.g. "fills", + "orders"). + example: trades::1 + x-parser-schema-id: + ts: + type: integer + description: >- + Request timestamp. Unix milliseconds for most operations; Unix + seconds for withdrawals (must match the on-chain EIP-712 struct + verified against block.timestamp). + example: 1767225600000 + x-parser-schema-id: + sq: + type: integer + description: Sequence number + example: 1234567890 + x-parser-schema-id: + data: + type: object + description: Array of withdrawal objects + properties: + withdraw_id: + type: integer + description: Withdraw ID + x-parser-schema-id: + asset: + type: string + description: Asset name + example: USDC + x-parser-schema-id: + amount: + type: string + description: >- + Raw token amount including decimals. For withdrawals this + matches the uint256 amount in the EIP-712 signature (e.g. + "100000000" for 100 USDC with 6 decimals). + example: '100000000' + x-parser-schema-id: + fee: + type: string + description: Withdrawal transaction fee in decimalized asset units + example: '5.00' + x-parser-schema-id: + to: + type: string + description: Destination address in hex format + example: '0x1234567890abcdef1234567890abcdef12345678' + x-parser-schema-id: + status: + type: string + description: Withdrawal status + enum: + - pending + - confirmed + - removed + - failed + x-parser-schema-id: + hash: + type: string + description: On-chain transaction hash, "0x" if not yet mined + default: 0x + example: >- + 0x1234567890abcdef1234567890abcdef1234567890abcdef1234567890abcdef + x-parser-schema-id: + required: + - withdraw_id + - asset + - amount + - fee + - to + - status + - hash + x-parser-schema-id: + required: + - ch + - ts + - sq + - data + x-parser-schema-id: + title: Update + description: Withdrawal status updates for authenticated users + example: |- + { + "ch": "withdrawals", + "ts": 1767225600000, + "sq": 1234567890, + "data": [ + { + "asset": "USDC", + "amount": "100000000", + "fee": "5.00", + "to": "0x1234567890abcdef1234567890abcdef12345678", + "status": "pending", + "hash": "0x1234567890abcdef1234567890abcdef1234567890abcdef1234567890abcdef" + } + ] + } + bindings: [] + extensions: + - id: x-parser-unique-object-id + value: Update + bindings: [] + extensions: *ref_0 +sendOperations: + - *ref_1 + - *ref_2 +receiveOperations: + - *ref_3 + - *ref_4 + - *ref_5 +sendMessages: + - *ref_6 + - *ref_7 +receiveMessages: + - *ref_8 + - *ref_9 + - *ref_10 +extensions: + - id: x-parser-unique-object-id + value: withdrawals +securitySchemes: [] + +```` \ No newline at end of file diff --git a/PolymarketDocumentation-main/docs/api-reference/wss/rfq.md b/PolymarketDocumentation-main/docs/api-reference/wss/rfq.md new file mode 100644 index 00000000..6ba83928 --- /dev/null +++ b/PolymarketDocumentation-main/docs/api-reference/wss/rfq.md @@ -0,0 +1,1593 @@ +> ## Documentation Index +> Fetch the complete documentation index at: https://docs.polymarket.com/llms.txt +> Use this file to discover all available pages before exploring further. + +# Quoter Gateway + +> Authenticated WebSocket for combinatorial RFQ quoters — receive requests, submit quotes, confirm last look, and track execution. + + + +## AsyncAPI + +````yaml asyncapi-rfq.json quoter +id: quoter +title: Quoter Gateway +description: >- + Authenticated quoter channel. Send the `auth` message as the first message + within 30 seconds. The gateway broadcasts active RFQ requests, accepts signed + quotes and cancellations, issues last-look confirmation requests, streams + execution updates, and sends confirmed trade broadcasts. +servers: + - id: production + protocol: wss + host: combos-rfq-gateway-quoter.polymarket.com + bindings: [] + variables: [] +address: /ws/rfq +parameters: [] +bindings: [] +operations: + - &ref_4 + id: authenticate + title: Authenticate + description: Authenticate the connection (send as the first message) + type: receive + messages: + - &ref_17 + id: auth + contentType: application/json + payload: + - name: Auth + description: Authenticate the connection + type: object + properties: + - name: type + type: string + description: auth + required: true + - name: auth + type: object + description: CLOB API credentials. + required: true + properties: + - name: apiKey + type: string + description: CLOB API key. + required: true + - name: secret + type: string + description: CLOB API secret. + required: true + - name: passphrase + type: string + description: CLOB API passphrase. + required: true + - name: identity + type: object + description: Signer/maker identity used for RFQ orders. + required: true + properties: + - name: signer_address + type: string + description: Address that signs orders. + required: true + - name: maker_address + type: string + description: Wallet that funds orders. + required: true + - name: signature_type + type: integer + description: >- + CLOB signature type: 0 EOA, 1 POLY_PROXY, 2 GNOSIS_SAFE, 3 + POLY_1271. + enumValues: + - 0 + - 1 + - 2 + - 3 + required: true + headers: [] + jsonPayloadSchema: + type: object + description: Authentication message. Must be the first message after connecting. + required: + - type + - auth + - identity + properties: + type: + type: string + const: auth + x-parser-schema-id: + auth: + type: object + description: CLOB API credentials. + required: + - apiKey + - secret + - passphrase + properties: + apiKey: + type: string + description: CLOB API key. + x-parser-schema-id: + secret: + type: string + description: CLOB API secret. + x-parser-schema-id: + passphrase: + type: string + description: CLOB API passphrase. + x-parser-schema-id: + x-parser-schema-id: + identity: + type: object + description: Signer/maker identity used for RFQ orders. + required: + - signer_address + - maker_address + - signature_type + properties: + signer_address: + type: string + description: Address that signs orders. + x-parser-schema-id: + maker_address: + type: string + description: Wallet that funds orders. + x-parser-schema-id: + signature_type: &ref_1 + type: integer + description: >- + CLOB signature type: 0 EOA, 1 POLY_PROXY, 2 GNOSIS_SAFE, 3 + POLY_1271. + enum: + - 0 + - 1 + - 2 + - 3 + x-parser-schema-id: SignatureType + x-parser-schema-id: + x-parser-schema-id: AuthMessage + title: Auth + description: Authenticate the connection + example: |- + { + "type": "auth", + "auth": { + "apiKey": "YOUR_API_KEY", + "secret": "YOUR_API_SECRET", + "passphrase": "YOUR_API_PASSPHRASE" + }, + "identity": { + "signer_address": "0xYourSigner", + "maker_address": "0xYourQuoterWallet", + "signature_type": 0 + } + } + bindings: [] + extensions: + - id: x-parser-unique-object-id + value: auth + bindings: [] + extensions: &ref_0 + - id: x-parser-unique-object-id + value: quoter + - &ref_8 + id: authResult + title: Auth Result + description: Gateway response to the auth message + type: send + messages: + - &ref_21 + id: authResponse + contentType: application/json + payload: + - name: Auth Response + description: Gateway response to the auth message + type: object + properties: + - name: type + type: string + description: auth + required: true + - name: success + type: boolean + required: true + - name: address + type: string + description: Authenticated address, present on success. + required: false + - name: error + type: string + description: Error detail, present on failure. + required: false + headers: [] + jsonPayloadSchema: + type: object + description: Gateway response to the auth message. + required: + - type + - success + properties: + type: + type: string + const: auth + x-parser-schema-id: + success: + type: boolean + x-parser-schema-id: + address: + type: string + description: Authenticated address, present on success. + x-parser-schema-id: + error: + type: string + description: Error detail, present on failure. + x-parser-schema-id: + x-parser-schema-id: AuthResponse + title: Auth Response + description: Gateway response to the auth message + example: |- + { + "type": "auth", + "success": true, + "address": "0xAuthenticatedAddress" + } + bindings: [] + extensions: + - id: x-parser-unique-object-id + value: authResponse + bindings: [] + extensions: *ref_0 + - &ref_9 + id: receiveRfqRequest + title: RFQ Request + description: Broadcast of an active RFQ request to quote + type: send + messages: + - &ref_22 + id: rfqRequest + contentType: application/json + payload: + - name: RFQ_REQUEST + description: Broadcast of an active RFQ request + type: object + properties: + - name: type + type: string + description: RFQ_REQUEST + required: true + - name: rfq_id + type: string + description: Server-assigned RFQ ID. + required: true + - name: requestor_public_id + type: string + description: Opaque public ID for the RFQ source. + required: true + - name: leg_position_ids + type: array + description: Canonical leg position IDs in the combo. + required: true + properties: + - name: item + type: string + required: false + - name: condition_id + type: string + description: Derived combinatorial condition ID. + required: true + - name: yes_position_id + type: string + description: Derived YES combo position ID. + required: true + - name: no_position_id + type: string + description: Derived NO combo position ID. + required: true + - name: direction + type: string + description: Requester trade direction. + enumValues: + - BUY + - SELL + required: true + - name: side + type: string + description: Combinatorial position side. Currently only YES is supported. + enumValues: + - 'YES' + - 'NO' + required: true + - name: requested_size + type: object + description: Requested RFQ size and unit. + required: true + properties: + - name: unit + type: string + description: >- + `notional` for requester BUY RFQs and `shares` for + requester SELL RFQs. + enumValues: + - notional + - shares + required: true + - name: value_e6 + type: string + description: Six-decimal fixed-point value encoded as a string. + required: true + - name: submission_deadline + type: integer + description: Quote submission deadline in Unix milliseconds. + required: true + headers: [] + jsonPayloadSchema: + type: object + description: Broadcast of an active RFQ request. + required: + - type + - rfq_id + - requestor_public_id + - leg_position_ids + - condition_id + - yes_position_id + - no_position_id + - direction + - side + - requested_size + - submission_deadline + properties: + type: + type: string + const: RFQ_REQUEST + x-parser-schema-id: + rfq_id: + type: string + description: Server-assigned RFQ ID. + x-parser-schema-id: + requestor_public_id: + type: string + description: Opaque public ID for the RFQ source. + x-parser-schema-id: + leg_position_ids: + type: array + description: Canonical leg position IDs in the combo. + items: + type: string + x-parser-schema-id: + x-parser-schema-id: + condition_id: + type: string + description: Derived combinatorial condition ID. + x-parser-schema-id: + yes_position_id: + type: string + description: Derived YES combo position ID. + x-parser-schema-id: + no_position_id: + type: string + description: Derived NO combo position ID. + x-parser-schema-id: + direction: &ref_2 + type: string + description: Requester trade direction. + enum: + - BUY + - SELL + x-parser-schema-id: Direction + side: &ref_3 + type: string + description: Combinatorial position side. Currently only YES is supported. + enum: + - 'YES' + - 'NO' + x-parser-schema-id: Side + requested_size: + type: object + description: Requested RFQ size and unit. + required: + - unit + - value_e6 + properties: + unit: + type: string + description: >- + `notional` for requester BUY RFQs and `shares` for requester + SELL RFQs. + enum: + - notional + - shares + x-parser-schema-id: + value_e6: + type: string + description: Six-decimal fixed-point value encoded as a string. + x-parser-schema-id: + x-parser-schema-id: RequestedSize + submission_deadline: + type: integer + format: int64 + description: Quote submission deadline in Unix milliseconds. + x-parser-schema-id: + x-parser-schema-id: RfqRequest + title: RFQ_REQUEST + description: Broadcast of an active RFQ request + example: |- + { + "type": "RFQ_REQUEST", + "rfq_id": "rfq_", + "requestor_public_id": "req_", + "leg_position_ids": [ + "", + "" + ], + "condition_id": "0x", + "yes_position_id": "", + "no_position_id": "", + "direction": "BUY", + "side": "YES", + "requested_size": { + "unit": "notional", + "value_e6": "1000000" + }, + "submission_deadline": 1780575184000 + } + bindings: [] + extensions: + - id: x-parser-unique-object-id + value: rfqRequest + bindings: [] + extensions: *ref_0 + - &ref_5 + id: submitQuote + title: Submit Quote + description: Submit a signed maker quote before the submission deadline + type: receive + messages: + - &ref_18 + id: rfqQuote + contentType: application/json + payload: + - name: RFQ_QUOTE + description: Submit a signed maker quote + type: object + properties: + - name: type + type: string + description: RFQ_QUOTE + required: true + - name: rfq_id + type: string + description: RFQ ID from RFQ_REQUEST. + required: true + - name: price_e6 + type: string + description: Quote price in six-decimal fixed-point units. + required: true + - name: size_e6 + type: string + description: Fillable share count in six-decimal fixed-point units. + required: true + - name: signed_order + type: object + description: Signed Exchange v3 order. + required: true + properties: + - name: salt + type: string + description: Order salt (uint256 as a decimal string). + required: true + - name: maker + type: string + description: Wallet that funds the order. + required: true + - name: signer + type: string + description: Address that signs the order. + required: true + - name: tokenId + type: string + description: YES or NO combo position ID (uint256 as a decimal string). + required: true + - name: makerAmount + type: string + description: Amount the maker pays, in six-decimal base units. + required: true + - name: takerAmount + type: string + description: Amount the maker receives, in six-decimal base units. + required: true + - name: side + type: integer + description: Order side — 0 BUY, 1 SELL. + enumValues: + - 0 + - 1 + required: true + - name: signatureType + type: integer + description: >- + CLOB signature type: 0 EOA, 1 POLY_PROXY, 2 GNOSIS_SAFE, 3 + POLY_1271. + enumValues: + - 0 + - 1 + - 2 + - 3 + required: true + - name: timestamp + type: string + description: Order timestamp in Unix seconds (as a string). + required: true + - name: metadata + type: string + description: 32-byte hex field; defaults to the zero value. + required: false + - name: builder + type: string + description: 32-byte hex field; defaults to the zero value. + required: false + - name: signature + type: string + description: EIP-712 signature over the order. + required: true + headers: [] + jsonPayloadSchema: + type: object + description: Submit a signed maker quote before the submission deadline. + required: + - type + - rfq_id + - price_e6 + - size_e6 + - signed_order + properties: + type: + type: string + const: RFQ_QUOTE + x-parser-schema-id: + rfq_id: + type: string + description: RFQ ID from RFQ_REQUEST. + x-parser-schema-id: + price_e6: + type: string + description: Quote price in six-decimal fixed-point units. + x-parser-schema-id: + size_e6: + type: string + description: Fillable share count in six-decimal fixed-point units. + x-parser-schema-id: + signed_order: + type: object + description: Signed Exchange v3 order. + required: + - salt + - maker + - signer + - tokenId + - makerAmount + - takerAmount + - side + - signatureType + - timestamp + - signature + properties: + salt: + type: string + description: Order salt (uint256 as a decimal string). + x-parser-schema-id: + maker: + type: string + description: Wallet that funds the order. + x-parser-schema-id: + signer: + type: string + description: Address that signs the order. + x-parser-schema-id: + tokenId: + type: string + description: YES or NO combo position ID (uint256 as a decimal string). + x-parser-schema-id: + makerAmount: + type: string + description: Amount the maker pays, in six-decimal base units. + x-parser-schema-id: + takerAmount: + type: string + description: Amount the maker receives, in six-decimal base units. + x-parser-schema-id: + side: + type: integer + description: Order side — 0 BUY, 1 SELL. + enum: + - 0 + - 1 + x-parser-schema-id: + signatureType: *ref_1 + timestamp: + type: string + description: Order timestamp in Unix seconds (as a string). + x-parser-schema-id: + metadata: + type: string + description: 32-byte hex field; defaults to the zero value. + x-parser-schema-id: + builder: + type: string + description: 32-byte hex field; defaults to the zero value. + x-parser-schema-id: + signature: + type: string + description: EIP-712 signature over the order. + x-parser-schema-id: + x-parser-schema-id: ExchangeV3Order + x-parser-schema-id: RfqQuote + title: RFQ_QUOTE + description: Submit a signed maker quote + example: |- + { + "type": "RFQ_QUOTE", + "rfq_id": "rfq_", + "price_e6": "450000", + "size_e6": "1000000", + "signed_order": { + "salt": "", + "maker": "0xYourQuoterWallet", + "signer": "0xYourSigner", + "tokenId": "", + "makerAmount": "", + "takerAmount": "", + "side": 0, + "signatureType": 0, + "timestamp": "", + "metadata": "0x0000000000000000000000000000000000000000000000000000000000000000", + "builder": "0x0000000000000000000000000000000000000000000000000000000000000000", + "signature": "0x..." + } + } + bindings: [] + extensions: + - id: x-parser-unique-object-id + value: rfqQuote + bindings: [] + extensions: *ref_0 + - &ref_10 + id: acknowledgeQuote + title: Quote Ack + description: Returns the server-generated quote ID + type: send + messages: + - &ref_23 + id: ackRfqQuote + contentType: application/json + payload: + - name: ACK_RFQ_QUOTE + description: Returns the server-generated quote ID + type: object + properties: + - name: type + type: string + description: ACK_RFQ_QUOTE + required: true + - name: rfq_id + type: string + required: true + - name: quote_id + type: string + description: Server-generated quote ID. + required: true + headers: [] + jsonPayloadSchema: + type: object + description: Returns the server-generated quote ID. + required: + - type + - rfq_id + - quote_id + properties: + type: + type: string + const: ACK_RFQ_QUOTE + x-parser-schema-id: + rfq_id: + type: string + x-parser-schema-id: + quote_id: + type: string + description: Server-generated quote ID. + x-parser-schema-id: + x-parser-schema-id: AckRfqQuote + title: ACK_RFQ_QUOTE + description: Returns the server-generated quote ID + example: |- + { + "type": "ACK_RFQ_QUOTE", + "rfq_id": "rfq_", + "quote_id": "quote_" + } + bindings: [] + extensions: + - id: x-parser-unique-object-id + value: ackRfqQuote + bindings: [] + extensions: *ref_0 + - &ref_6 + id: cancelQuote + title: Cancel Quote + description: Cancel an active maker quote before it is selected + type: receive + messages: + - &ref_19 + id: rfqQuoteCancel + contentType: application/json + payload: + - name: RFQ_QUOTE_CANCEL + description: Cancel an active maker quote + type: object + properties: + - name: type + type: string + description: RFQ_QUOTE_CANCEL + required: true + - name: rfq_id + type: string + required: true + - name: quote_id + type: string + description: Server-generated quote ID. + required: true + - name: signer_address + type: string + description: Must match the authenticated signer_address. + required: true + - name: maker_address + type: string + description: Must match the authenticated maker_address. + required: true + headers: [] + jsonPayloadSchema: + type: object + description: Cancel an active maker quote before it is selected. + required: + - type + - rfq_id + - quote_id + - signer_address + - maker_address + properties: + type: + type: string + const: RFQ_QUOTE_CANCEL + x-parser-schema-id: + rfq_id: + type: string + x-parser-schema-id: + quote_id: + type: string + description: Server-generated quote ID. + x-parser-schema-id: + signer_address: + type: string + description: Must match the authenticated signer_address. + x-parser-schema-id: + maker_address: + type: string + description: Must match the authenticated maker_address. + x-parser-schema-id: + x-parser-schema-id: RfqQuoteCancel + title: RFQ_QUOTE_CANCEL + description: Cancel an active maker quote + example: |- + { + "type": "RFQ_QUOTE_CANCEL", + "rfq_id": "rfq_", + "quote_id": "quote_", + "signer_address": "0xYourSigner", + "maker_address": "0xYourQuoterWallet" + } + bindings: [] + extensions: + - id: x-parser-unique-object-id + value: rfqQuoteCancel + bindings: [] + extensions: *ref_0 + - &ref_11 + id: acknowledgeQuoteCancel + title: Quote Cancel Ack + description: Confirms quote cancellation + type: send + messages: + - &ref_24 + id: ackRfqQuoteCancel + contentType: application/json + payload: + - name: ACK_RFQ_QUOTE_CANCEL + description: Confirms quote cancellation + type: object + properties: + - name: type + type: string + description: ACK_RFQ_QUOTE_CANCEL + required: true + - name: rfq_id + type: string + required: true + - name: quote_id + type: string + required: true + headers: [] + jsonPayloadSchema: + type: object + description: Confirms quote cancellation. + required: + - type + - rfq_id + - quote_id + properties: + type: + type: string + const: ACK_RFQ_QUOTE_CANCEL + x-parser-schema-id: + rfq_id: + type: string + x-parser-schema-id: + quote_id: + type: string + x-parser-schema-id: + x-parser-schema-id: AckRfqQuoteCancel + title: ACK_RFQ_QUOTE_CANCEL + description: Confirms quote cancellation + example: |- + { + "type": "ACK_RFQ_QUOTE_CANCEL", + "rfq_id": "rfq_", + "quote_id": "quote_" + } + bindings: [] + extensions: + - id: x-parser-unique-object-id + value: ackRfqQuoteCancel + bindings: [] + extensions: *ref_0 + - &ref_12 + id: receiveConfirmationRequest + title: Confirmation Request + description: Last-look confirmation request for a selected quote + type: send + messages: + - &ref_25 + id: rfqConfirmationRequest + contentType: application/json + payload: + - name: RFQ_CONFIRMATION_REQUEST + description: Last-look confirmation request for a selected quote + type: object + properties: + - name: type + type: string + description: RFQ_CONFIRMATION_REQUEST + required: true + - name: rfq_id + type: string + required: true + - name: quote_id + type: string + description: Selected quote ID. + required: true + - name: signer_address + type: string + required: true + - name: maker_address + type: string + required: true + - name: signature_type + type: integer + description: >- + CLOB signature type: 0 EOA, 1 POLY_PROXY, 2 GNOSIS_SAFE, 3 + POLY_1271. + enumValues: + - 0 + - 1 + - 2 + - 3 + required: true + - name: leg_position_ids + type: array + required: true + properties: + - name: item + type: string + required: false + - name: condition_id + type: string + required: true + - name: yes_position_id + type: string + required: true + - name: no_position_id + type: string + required: true + - name: direction + type: string + description: Requester trade direction. + enumValues: + - BUY + - SELL + required: true + - name: side + type: string + description: Combinatorial position side. Currently only YES is supported. + enumValues: + - 'YES' + - 'NO' + required: true + - name: fill_size_e6 + type: string + description: Selected fill size in six-decimal fixed-point units. + required: true + - name: price_e6 + type: string + description: Selected quote price in six-decimal fixed-point units. + required: true + - name: confirm_by + type: integer + description: Confirmation deadline in Unix milliseconds. + required: true + headers: [] + jsonPayloadSchema: + type: object + description: Last-look confirmation request for a selected quote. + required: + - type + - rfq_id + - quote_id + - signer_address + - maker_address + - signature_type + - leg_position_ids + - condition_id + - yes_position_id + - no_position_id + - direction + - side + - fill_size_e6 + - price_e6 + - confirm_by + properties: + type: + type: string + const: RFQ_CONFIRMATION_REQUEST + x-parser-schema-id: + rfq_id: + type: string + x-parser-schema-id: + quote_id: + type: string + description: Selected quote ID. + x-parser-schema-id: + signer_address: + type: string + x-parser-schema-id: + maker_address: + type: string + x-parser-schema-id: + signature_type: *ref_1 + leg_position_ids: + type: array + items: + type: string + x-parser-schema-id: + x-parser-schema-id: + condition_id: + type: string + x-parser-schema-id: + yes_position_id: + type: string + x-parser-schema-id: + no_position_id: + type: string + x-parser-schema-id: + direction: *ref_2 + side: *ref_3 + fill_size_e6: + type: string + description: Selected fill size in six-decimal fixed-point units. + x-parser-schema-id: + price_e6: + type: string + description: Selected quote price in six-decimal fixed-point units. + x-parser-schema-id: + confirm_by: + type: integer + format: int64 + description: Confirmation deadline in Unix milliseconds. + x-parser-schema-id: + x-parser-schema-id: RfqConfirmationRequest + title: RFQ_CONFIRMATION_REQUEST + description: Last-look confirmation request for a selected quote + example: |- + { + "type": "RFQ_CONFIRMATION_REQUEST", + "rfq_id": "rfq_", + "quote_id": "quote_", + "signer_address": "0xYourSigner", + "maker_address": "0xYourQuoterWallet", + "signature_type": 0, + "leg_position_ids": [ + "", + "" + ], + "condition_id": "0x", + "yes_position_id": "", + "no_position_id": "", + "direction": "BUY", + "side": "YES", + "fill_size_e6": "1000000", + "price_e6": "450000", + "confirm_by": 1780575184000 + } + bindings: [] + extensions: + - id: x-parser-unique-object-id + value: rfqConfirmationRequest + bindings: [] + extensions: *ref_0 + - &ref_7 + id: respondConfirmation + title: Confirmation Response + description: Confirm or decline a selected quote during last look + type: receive + messages: + - &ref_20 + id: rfqConfirmationResponse + contentType: application/json + payload: + - name: RFQ_CONFIRMATION_RESPONSE + description: Confirm or decline a selected quote + type: object + properties: + - name: type + type: string + description: RFQ_CONFIRMATION_RESPONSE + required: true + - name: rfq_id + type: string + required: true + - name: quote_id + type: string + description: Selected quote ID. + required: true + - name: decision + type: string + enumValues: + - CONFIRM + - DECLINE + required: true + headers: [] + jsonPayloadSchema: + type: object + description: >- + Confirm or decline a selected quote. Identity is applied from the + authenticated session. + required: + - type + - rfq_id + - quote_id + - decision + properties: + type: + type: string + const: RFQ_CONFIRMATION_RESPONSE + x-parser-schema-id: + rfq_id: + type: string + x-parser-schema-id: + quote_id: + type: string + description: Selected quote ID. + x-parser-schema-id: + decision: + type: string + enum: + - CONFIRM + - DECLINE + x-parser-schema-id: + x-parser-schema-id: RfqConfirmationResponse + title: RFQ_CONFIRMATION_RESPONSE + description: Confirm or decline a selected quote + example: |- + { + "type": "RFQ_CONFIRMATION_RESPONSE", + "rfq_id": "rfq_", + "quote_id": "quote_", + "decision": "CONFIRM" + } + bindings: [] + extensions: + - id: x-parser-unique-object-id + value: rfqConfirmationResponse + bindings: [] + extensions: *ref_0 + - &ref_13 + id: acknowledgeConfirmation + title: Confirmation Ack + description: Confirms the maker's last-look response + type: send + messages: + - &ref_26 + id: ackRfqConfirmationResponse + contentType: application/json + payload: + - name: ACK_RFQ_CONFIRMATION_RESPONSE + description: Confirms the maker's last-look response + type: object + properties: + - name: type + type: string + description: ACK_RFQ_CONFIRMATION_RESPONSE + required: true + - name: rfq_id + type: string + required: true + - name: quote_id + type: string + required: true + - name: decision + type: string + enumValues: + - CONFIRM + - DECLINE + required: true + headers: [] + jsonPayloadSchema: + type: object + description: Confirms the maker's last-look response. + required: + - type + - rfq_id + - quote_id + - decision + properties: + type: + type: string + const: ACK_RFQ_CONFIRMATION_RESPONSE + x-parser-schema-id: + rfq_id: + type: string + x-parser-schema-id: + quote_id: + type: string + x-parser-schema-id: + decision: + type: string + enum: + - CONFIRM + - DECLINE + x-parser-schema-id: + x-parser-schema-id: AckRfqConfirmationResponse + title: ACK_RFQ_CONFIRMATION_RESPONSE + description: Confirms the maker's last-look response + example: |- + { + "type": "ACK_RFQ_CONFIRMATION_RESPONSE", + "rfq_id": "rfq_", + "quote_id": "quote_", + "decision": "CONFIRM" + } + bindings: [] + extensions: + - id: x-parser-unique-object-id + value: ackRfqConfirmationResponse + bindings: [] + extensions: *ref_0 + - &ref_14 + id: receiveExecutionUpdate + title: Execution Update + description: Execution progress for selected makers + type: send + messages: + - &ref_27 + id: rfqExecutionUpdate + contentType: application/json + payload: + - name: RFQ_EXECUTION_UPDATE + description: Execution progress for selected makers + type: object + properties: + - name: type + type: string + description: RFQ_EXECUTION_UPDATE + required: true + - name: rfq_id + type: string + required: true + - name: status + type: string + enumValues: + - MATCHED + - MINED + - RETRYING + - CONFIRMED + - FAILED + required: true + - name: tx_hash + type: string + description: Transaction hash, when available. + required: false + headers: [] + jsonPayloadSchema: + type: object + description: >- + Reports execution progress for selected makers. CONFIRMED and FAILED + are terminal. + required: + - type + - rfq_id + - status + properties: + type: + type: string + const: RFQ_EXECUTION_UPDATE + x-parser-schema-id: + rfq_id: + type: string + x-parser-schema-id: + status: + type: string + enum: + - MATCHED + - MINED + - RETRYING + - CONFIRMED + - FAILED + x-parser-schema-id: + tx_hash: + type: string + description: Transaction hash, when available. + x-parser-schema-id: + x-parser-schema-id: RfqExecutionUpdate + title: RFQ_EXECUTION_UPDATE + description: Execution progress for selected makers + example: |- + { + "type": "RFQ_EXECUTION_UPDATE", + "rfq_id": "rfq_", + "status": "MINED", + "tx_hash": "0x" + } + bindings: [] + extensions: + - id: x-parser-unique-object-id + value: rfqExecutionUpdate + bindings: [] + extensions: *ref_0 + - &ref_15 + id: receiveTradeBroadcast + title: Trade Broadcast + description: Confirmed Combo RFQ trade broadcast + type: send + messages: + - &ref_28 + id: rfqTrade + contentType: application/json + payload: + - name: RFQ_TRADE + description: Confirmed Combo RFQ trade broadcast + type: object + properties: + - name: type + type: string + description: RFQ_TRADE + required: true + - name: rfq_id + type: string + description: RFQ ID for deduplication and reconciliation. + required: true + - name: requester_id + type: string + description: Opaque public ID for the RFQ source. + required: true + - name: condition_id + type: string + description: Derived combinatorial condition ID. + required: true + - name: leg_position_ids + type: array + description: Canonical leg position IDs in the combo. + required: true + properties: + - name: item + type: string + required: false + - name: direction + type: string + description: Requester trade direction. + enumValues: + - BUY + - SELL + required: true + - name: side + type: string + description: Combinatorial position side. Currently only YES is supported. + enumValues: + - 'YES' + - 'NO' + required: true + - name: price_e6 + type: string + description: Accepted blended price in six-decimal fixed-point units. + required: true + - name: size_e6 + type: string + description: Matched Combo share size in six-decimal fixed-point units. + required: true + - name: executed_at + type: integer + description: Execution timestamp in Unix milliseconds. + required: true + headers: [] + jsonPayloadSchema: + type: object + description: >- + Confirmed Combo RFQ trade broadcast. Excludes maker identity and + per-maker fill allocations. + required: + - type + - rfq_id + - requester_id + - condition_id + - leg_position_ids + - direction + - side + - price_e6 + - size_e6 + - executed_at + properties: + type: + type: string + const: RFQ_TRADE + x-parser-schema-id: + rfq_id: + type: string + description: RFQ ID for deduplication and reconciliation. + x-parser-schema-id: + requester_id: + type: string + description: Opaque public ID for the RFQ source. + x-parser-schema-id: + condition_id: + type: string + description: Derived combinatorial condition ID. + x-parser-schema-id: + leg_position_ids: + type: array + description: Canonical leg position IDs in the combo. + items: + type: string + x-parser-schema-id: + x-parser-schema-id: + direction: *ref_2 + side: *ref_3 + price_e6: + type: string + description: Accepted blended price in six-decimal fixed-point units. + x-parser-schema-id: + size_e6: + type: string + description: Matched Combo share size in six-decimal fixed-point units. + x-parser-schema-id: + executed_at: + type: integer + format: int64 + description: Execution timestamp in Unix milliseconds. + x-parser-schema-id: + x-parser-schema-id: RfqTrade + title: RFQ_TRADE + description: Confirmed Combo RFQ trade broadcast + example: |- + { + "type": "RFQ_TRADE", + "rfq_id": "rfq_", + "requester_id": "req_", + "condition_id": "0x", + "leg_position_ids": [ + "", + "" + ], + "direction": "BUY", + "side": "YES", + "price_e6": "125000", + "size_e6": "800000", + "executed_at": 1780854786039 + } + bindings: [] + extensions: + - id: x-parser-unique-object-id + value: rfqTrade + bindings: [] + extensions: *ref_0 + - &ref_16 + id: receiveError + title: Error + description: Sent when a command fails validation or cannot be applied + type: send + messages: + - &ref_29 + id: rfqError + contentType: application/json + payload: + - name: RFQ_ERROR + description: Sent when a command fails validation or cannot be applied + type: object + properties: + - name: type + type: string + description: RFQ_ERROR + required: true + - name: request_type + type: string + description: Inbound command that failed, when parsed. + required: false + - name: rfq_id + type: string + description: RFQ ID, when present on the failed command. + required: false + - name: quote_id + type: string + description: Quote ID, when present on the failed command. + required: false + - name: code + type: string + description: Stable machine-readable error code. + enumValues: + - ADDRESS_MISMATCH + - ALLOWANCE_VALIDATION_FAILED + - BALANCE_VALIDATION_FAILED + - CONTRADICTORY_LEGS + - EXPIRED_RFQ + - INVALID_ACCEPTANCE + - INVALID_CONFIRMATION + - INVALID_EXECUTION_RESULT + - INVALID_IDENTITY + - INVALID_MESSAGE + - INVALID_QUOTE + - INVALID_RFQ + - INVALID_RFQ_STATE + - INVALID_ROLE + - LEG_METADATA_UNAVAILABLE + - MAKER_ALREADY_RESPONDED + - MAKER_NOT_REQUIRED + - PRE_EXECUTION_BALANCE_RESERVATION_FAILED + - QUOTE_MISMATCH + - QUOTE_UNAVAILABLE + - RATE_LIMITED + - REQUEST_FAILED + - SERVICE_UNAVAILABLE + - SUBMISSION_WINDOW_CLOSED + - TRADE_SUBMISSION_FAILED + - UNAUTHENTICATED + - UNAUTHORIZED_ROLE + - UNKNOWN_RFQ + required: true + - name: error + type: string + description: Human-readable error detail for logging and debugging. + required: true + headers: [] + jsonPayloadSchema: + type: object + description: Sent when a command fails validation or cannot be applied. + required: + - type + - code + - error + properties: + type: + type: string + const: RFQ_ERROR + x-parser-schema-id: + request_type: + type: string + description: Inbound command that failed, when parsed. + x-parser-schema-id: + rfq_id: + type: string + description: RFQ ID, when present on the failed command. + x-parser-schema-id: + quote_id: + type: string + description: Quote ID, when present on the failed command. + x-parser-schema-id: + code: + type: string + description: Stable machine-readable error code. + enum: + - ADDRESS_MISMATCH + - ALLOWANCE_VALIDATION_FAILED + - BALANCE_VALIDATION_FAILED + - CONTRADICTORY_LEGS + - EXPIRED_RFQ + - INVALID_ACCEPTANCE + - INVALID_CONFIRMATION + - INVALID_EXECUTION_RESULT + - INVALID_IDENTITY + - INVALID_MESSAGE + - INVALID_QUOTE + - INVALID_RFQ + - INVALID_RFQ_STATE + - INVALID_ROLE + - LEG_METADATA_UNAVAILABLE + - MAKER_ALREADY_RESPONDED + - MAKER_NOT_REQUIRED + - PRE_EXECUTION_BALANCE_RESERVATION_FAILED + - QUOTE_MISMATCH + - QUOTE_UNAVAILABLE + - RATE_LIMITED + - REQUEST_FAILED + - SERVICE_UNAVAILABLE + - SUBMISSION_WINDOW_CLOSED + - TRADE_SUBMISSION_FAILED + - UNAUTHENTICATED + - UNAUTHORIZED_ROLE + - UNKNOWN_RFQ + x-parser-schema-id: + error: + type: string + description: Human-readable error detail for logging and debugging. + x-parser-schema-id: + x-parser-schema-id: RfqError + title: RFQ_ERROR + description: Sent when a command fails validation or cannot be applied + example: |- + { + "type": "RFQ_ERROR", + "request_type": "RFQ_QUOTE", + "rfq_id": "rfq_", + "code": "SUBMISSION_WINDOW_CLOSED", + "error": "submission window closed" + } + bindings: [] + extensions: + - id: x-parser-unique-object-id + value: rfqError + bindings: [] + extensions: *ref_0 +sendOperations: + - *ref_4 + - *ref_5 + - *ref_6 + - *ref_7 +receiveOperations: + - *ref_8 + - *ref_9 + - *ref_10 + - *ref_11 + - *ref_12 + - *ref_13 + - *ref_14 + - *ref_15 + - *ref_16 +sendMessages: + - *ref_17 + - *ref_18 + - *ref_19 + - *ref_20 +receiveMessages: + - *ref_21 + - *ref_22 + - *ref_23 + - *ref_24 + - *ref_25 + - *ref_26 + - *ref_27 + - *ref_28 + - *ref_29 +extensions: + - id: x-parser-unique-object-id + value: quoter +securitySchemes: [] + +```` \ No newline at end of file diff --git a/PolymarketDocumentation-main/docs/api-reference/wss/sports.md b/PolymarketDocumentation-main/docs/api-reference/wss/sports.md new file mode 100644 index 00000000..ae13adb8 --- /dev/null +++ b/PolymarketDocumentation-main/docs/api-reference/wss/sports.md @@ -0,0 +1,240 @@ +> ## Documentation Index +> Fetch the complete documentation index at: https://docs.polymarket.com/llms.txt +> Use this file to discover all available pages before exploring further. + +# Sports Channel + +> Public WebSocket for real-time sports match results. + + + +## AsyncAPI + +````yaml asyncapi-sports.json sports +id: sports +title: Sports Channel +description: >- + Public channel broadcasting live sports results. No subscription message + required — connect and immediately start receiving updates for all active + events. The server sends a ping every 5 seconds; respond with pong within 10 + seconds to stay connected. +servers: + - id: production + protocol: wss + host: sports-api.polymarket.com + bindings: [] + variables: [] +address: /ws +parameters: [] +bindings: [] +operations: + - &ref_2 + id: ping + title: Ping + description: Server sends ping every 5 seconds — respond with pong within 10 seconds + type: send + messages: + - &ref_5 + id: ping + contentType: text/plain + payload: + - type: string + const: ping + x-parser-schema-id: + name: Ping + description: Server heartbeat sent every 5 seconds + headers: [] + jsonPayloadSchema: + type: string + const: ping + x-parser-schema-id: + title: Ping + description: Server heartbeat sent every 5 seconds + example: '{}' + bindings: [] + extensions: + - id: x-parser-unique-object-id + value: ping + bindings: [] + extensions: &ref_0 + - id: x-parser-unique-object-id + value: sports + - &ref_1 + id: pong + title: Pong + description: Client responds to server ping + type: receive + messages: + - &ref_4 + id: pong + contentType: text/plain + payload: + - type: string + const: pong + x-parser-schema-id: + name: Pong + description: Client heartbeat response — must be sent within 10 seconds + headers: [] + jsonPayloadSchema: + type: string + const: pong + x-parser-schema-id: + title: Pong + description: Client heartbeat response — must be sent within 10 seconds + example: '{}' + bindings: [] + extensions: + - id: x-parser-unique-object-id + value: pong + bindings: [] + extensions: *ref_0 + - &ref_3 + id: receiveSportsUpdate + title: Sports Update + description: Live match update broadcast to all connected clients + type: send + messages: + - &ref_6 + id: sportsUpdate + contentType: application/json + payload: + - name: Sports Result Update + description: Real-time sports match update + type: object + properties: + - name: slug + type: string + description: Unique match identifier (e.g., 'mci-liv-2025-02-03') + required: true + - name: live + type: boolean + description: Whether the match is currently in progress + required: false + - name: ended + type: boolean + description: Whether the match has ended + required: false + - name: score + type: string + description: Current score (e.g., '2-1' for soccer, '14-7' for football) + required: false + - name: period + type: string + description: >- + Current period. Soccer: '1H', '2H', 'HT', 'FT', 'PEN'. NFL: + 'Q1'–'Q4', 'HT', 'OT', 'FT'. NBA/CBB: 'Q1'–'Q4', 'HT', 'OT', + 'FT'. MLB: 'Top 1st', 'Bot 1st', ... Ice Hockey: 'P1', 'P2', + 'P3', 'OT', 'PEN', 'FT'. Cricket: '1H', '1A', '2H', '2A', + 'SO', 'FT'. Other: 'CAN', 'POST', 'INT', 'AB'. + required: false + - name: elapsed + type: string + description: >- + Elapsed time in the current period in 'MM:SS' format. Empty + string if not applicable. + required: false + - name: last_update + type: string + description: ISO 8601 timestamp of the last update + required: false + - name: finished_timestamp + type: string + description: >- + ISO 8601 timestamp when the match ended. Only present for + ended matches. + required: false + - name: turn + type: string + description: Team abbreviation with ball possession. NFL only. + required: false + headers: [] + jsonPayloadSchema: + type: object + description: >- + Real-time sports match update. Only slug is required; all other + fields may be omitted if not applicable. + required: + - slug + properties: + slug: + type: string + description: Unique match identifier (e.g., 'mci-liv-2025-02-03') + x-parser-schema-id: + live: + type: boolean + description: Whether the match is currently in progress + x-parser-schema-id: + ended: + type: boolean + description: Whether the match has ended + x-parser-schema-id: + score: + type: string + description: Current score (e.g., '2-1' for soccer, '14-7' for football) + x-parser-schema-id: + period: + type: string + description: >- + Current period. Soccer: '1H', '2H', 'HT', 'FT', 'PEN'. NFL: + 'Q1'–'Q4', 'HT', 'OT', 'FT'. NBA/CBB: 'Q1'–'Q4', 'HT', 'OT', + 'FT'. MLB: 'Top 1st', 'Bot 1st', ... Ice Hockey: 'P1', 'P2', + 'P3', 'OT', 'PEN', 'FT'. Cricket: '1H', '1A', '2H', '2A', 'SO', + 'FT'. Other: 'CAN', 'POST', 'INT', 'AB'. + x-parser-schema-id: + elapsed: + type: string + description: >- + Elapsed time in the current period in 'MM:SS' format. Empty + string if not applicable. + x-parser-schema-id: + last_update: + type: string + format: date-time + description: ISO 8601 timestamp of the last update + x-parser-schema-id: + finished_timestamp: + type: string + format: date-time + description: >- + ISO 8601 timestamp when the match ended. Only present for ended + matches. + x-parser-schema-id: + turn: + type: string + description: Team abbreviation with ball possession. NFL only. + x-parser-schema-id: + x-parser-schema-id: SportResult + title: Sports Result Update + description: Real-time sports match update + example: |- + { + "slug": "mci-liv-2025-02-03", + "live": true, + "ended": false, + "score": "1-0", + "period": "1H", + "elapsed": "32:15", + "last_update": "2025-02-03T19:50:16.939Z" + } + bindings: [] + extensions: + - id: x-parser-unique-object-id + value: sportsUpdate + bindings: [] + extensions: *ref_0 +sendOperations: + - *ref_1 +receiveOperations: + - *ref_2 + - *ref_3 +sendMessages: + - *ref_4 +receiveMessages: + - *ref_5 + - *ref_6 +extensions: + - id: x-parser-unique-object-id + value: sports +securitySchemes: [] + +```` \ No newline at end of file diff --git a/PolymarketDocumentation-main/docs/api-reference/wss/user.md b/PolymarketDocumentation-main/docs/api-reference/wss/user.md new file mode 100644 index 00000000..338bebe9 --- /dev/null +++ b/PolymarketDocumentation-main/docs/api-reference/wss/user.md @@ -0,0 +1,834 @@ +> ## Documentation Index +> Fetch the complete documentation index at: https://docs.polymarket.com/llms.txt +> Use this file to discover all available pages before exploring further. + +# User Channel + +> Authenticated WebSocket for real-time order and trade updates. + + + +## AsyncAPI + +````yaml asyncapi-user.json user +id: user +title: User Channel +description: >- + Authenticated channel for real-time order and trade updates. Send API + credentials in the initial subscription message. Optionally filter by market + condition IDs. +servers: + - id: production + protocol: wss + host: ws-subscriptions-clob.polymarket.com + bindings: [] + variables: [] +address: /ws/user +parameters: [] +bindings: [] +operations: + - &ref_1 + id: subscribe + title: Subscribe + description: Send authenticated subscription request + type: receive + messages: + - &ref_7 + id: userSubscriptionRequest + contentType: application/json + payload: + - name: Subscription Request + description: Authenticated subscription message sent after connecting + type: object + properties: + - name: auth + type: object + description: CLOB API credentials for authentication + required: true + properties: + - name: apiKey + type: string + description: CLOB API key (UUID format) + required: true + - name: secret + type: string + description: CLOB API secret + required: true + - name: passphrase + type: string + description: CLOB API passphrase + required: true + - name: type + type: string + description: Must be 'user' + required: true + - name: markets + type: array + description: >- + Optional condition IDs to filter events. If omitted, receives + events for all markets. + required: false + properties: + - name: item + type: string + required: false + headers: [] + jsonPayloadSchema: + type: object + description: Authenticated subscription request for the user channel + required: + - auth + - type + properties: + auth: + type: object + description: CLOB API credentials for authentication + required: + - apiKey + - secret + - passphrase + properties: + apiKey: + type: string + description: CLOB API key (UUID format) + x-parser-schema-id: + secret: + type: string + description: CLOB API secret + x-parser-schema-id: + passphrase: + type: string + description: CLOB API passphrase + x-parser-schema-id: + x-parser-schema-id: WebSocketAuth + type: + type: string + const: user + description: Must be 'user' + x-parser-schema-id: + markets: + type: array + description: >- + Optional condition IDs to filter events. If omitted, receives + events for all markets. + items: + type: string + x-parser-schema-id: + x-parser-schema-id: + x-parser-schema-id: UserSubscriptionRequest + title: Subscription Request + description: Authenticated subscription message sent after connecting + example: |- + { + "auth": { + "apiKey": "your-api-key-uuid", + "secret": "your-api-secret", + "passphrase": "your-passphrase" + }, + "type": "user" + } + bindings: [] + extensions: + - id: x-parser-unique-object-id + value: userSubscriptionRequest + bindings: [] + extensions: &ref_0 + - id: x-parser-unique-object-id + value: user + - &ref_2 + id: updateSubscription + title: Update Subscription + description: Dynamically subscribe or unsubscribe from markets without reconnecting + type: receive + messages: + - &ref_8 + id: userSubscriptionRequestUpdate + contentType: application/json + payload: + - name: Subscription Update + description: Subscribe or unsubscribe from markets without reconnecting + type: object + properties: + - name: operation + type: string + enumValues: + - subscribe + - unsubscribe + required: true + - name: markets + type: array + description: Condition IDs to subscribe to or unsubscribe from + required: true + properties: + - name: item + type: string + required: false + headers: [] + jsonPayloadSchema: + type: object + description: Dynamically update market subscriptions + required: + - operation + - markets + properties: + operation: + type: string + enum: + - subscribe + - unsubscribe + x-parser-schema-id: + markets: + type: array + description: Condition IDs to subscribe to or unsubscribe from + items: + type: string + x-parser-schema-id: + x-parser-schema-id: + x-parser-schema-id: UserSubscriptionRequestUpdate + title: Subscription Update + description: Subscribe or unsubscribe from markets without reconnecting + example: |- + { + "operation": "subscribe", + "markets": [ + "0x5f65177b394277fd294cd75650044e32ba009a95022d88a0c1d565897d72f8f1" + ] + } + bindings: [] + extensions: + - id: x-parser-unique-object-id + value: userSubscriptionRequestUpdate + bindings: [] + extensions: *ref_0 + - &ref_3 + id: ping + title: Ping + description: Send PING every 10 seconds to keep the connection alive + type: receive + messages: + - &ref_9 + id: ping + contentType: text/plain + payload: + - type: string + const: PING + x-parser-schema-id: + name: Ping + description: Client heartbeat — send every 10 seconds + headers: [] + jsonPayloadSchema: + type: string + const: PING + x-parser-schema-id: + title: Ping + description: Client heartbeat — send every 10 seconds + example: '{}' + bindings: [] + extensions: + - id: x-parser-unique-object-id + value: ping + bindings: [] + extensions: *ref_0 + - &ref_4 + id: pong + title: Pong + description: Server responds to PING with PONG + type: send + messages: + - &ref_10 + id: pong + contentType: text/plain + payload: + - type: string + const: PONG + x-parser-schema-id: + name: Pong + description: Server heartbeat response + headers: [] + jsonPayloadSchema: + type: string + const: PONG + x-parser-schema-id: + title: Pong + description: Server heartbeat response + example: '{}' + bindings: [] + extensions: + - id: x-parser-unique-object-id + value: pong + bindings: [] + extensions: *ref_0 + - &ref_5 + id: receiveOrder + title: Order Event + description: Order placement, update, or cancellation event for the authenticated user + type: send + messages: + - &ref_11 + id: order + contentType: application/json + payload: + - name: Order Event + description: Order placement, update, or cancellation + type: object + properties: + - name: event_type + type: string + description: order + required: true + - name: id + type: string + description: Order ID (hash) + required: true + - name: owner + type: string + description: API key of the order owner + required: true + - name: market + type: string + description: Condition ID of the market + required: true + - name: asset_id + type: string + description: Asset ID (token ID) + required: true + - name: side + type: string + enumValues: + - BUY + - SELL + required: true + - name: order_owner + type: string + required: false + - name: original_size + type: string + description: Original order size + required: true + - name: size_matched + type: string + description: Amount matched so far + required: true + - name: price + type: string + required: true + - name: associate_trades + type: array + description: Trade IDs this order has been matched in + required: false + properties: + - name: item + type: string + required: false + - name: outcome + type: string + description: e.g. 'YES', 'NO' + required: false + - name: type + type: string + enumValues: + - PLACEMENT + - UPDATE + - CANCELLATION + required: true + - name: created_at + type: string + required: false + - name: expiration + type: string + description: For GTD orders + required: false + - name: order_type + type: string + enumValues: + - GTC + - GTD + - FOK + required: false + - name: status + type: string + description: e.g. 'LIVE', 'MATCHED', 'CANCELED' + required: false + - name: maker_address + type: string + required: false + - name: timestamp + type: string + description: Event timestamp in milliseconds + required: true + headers: [] + jsonPayloadSchema: + type: object + description: Order placement, update, or cancellation event + required: + - event_type + - id + - owner + - market + - asset_id + - side + - original_size + - size_matched + - price + - type + - timestamp + properties: + event_type: + type: string + const: order + x-parser-schema-id: + id: + type: string + description: Order ID (hash) + x-parser-schema-id: + owner: + type: string + description: API key of the order owner + x-parser-schema-id: + market: + type: string + description: Condition ID of the market + x-parser-schema-id: + asset_id: + type: string + description: Asset ID (token ID) + x-parser-schema-id: + side: + type: string + enum: + - BUY + - SELL + x-parser-schema-id: + order_owner: + type: string + x-parser-schema-id: + original_size: + type: string + description: Original order size + x-parser-schema-id: + size_matched: + type: string + description: Amount matched so far + x-parser-schema-id: + price: + type: string + x-parser-schema-id: + associate_trades: + type: array + items: + type: string + x-parser-schema-id: + nullable: true + description: Trade IDs this order has been matched in + x-parser-schema-id: + outcome: + type: string + description: e.g. 'YES', 'NO' + x-parser-schema-id: + type: + type: string + enum: + - PLACEMENT + - UPDATE + - CANCELLATION + x-parser-schema-id: + created_at: + type: string + x-parser-schema-id: + expiration: + type: string + description: For GTD orders + x-parser-schema-id: + order_type: + type: string + enum: + - GTC + - GTD + - FOK + x-parser-schema-id: + status: + type: string + description: e.g. 'LIVE', 'MATCHED', 'CANCELED' + x-parser-schema-id: + maker_address: + type: string + x-parser-schema-id: + timestamp: + type: string + description: Event timestamp in milliseconds + x-parser-schema-id: + x-parser-schema-id: OrderEvent + title: Order Event + description: Order placement, update, or cancellation + example: |- + { + "event_type": "order", + "id": "0xff354cd7ca7539dfa9c28d90943ab5779a4eac34b9b37a757d7b32bdfb11790b", + "owner": "9180014b-33c8-9240-a14b-bdca11c0a465", + "market": "0xbd31dc8a20211944f6b70f31557f1001557b59905b7738480ca09bd4532f84af", + "asset_id": "52114319501245915516055106046884209969926127482827954674443846427813813222426", + "side": "SELL", + "order_owner": "9180014b-33c8-9240-a14b-bdca11c0a465", + "original_size": "10", + "size_matched": "0", + "price": "0.57", + "associate_trades": null, + "outcome": "YES", + "type": "PLACEMENT", + "created_at": "1672290687", + "expiration": "1234567", + "order_type": "GTD", + "status": "LIVE", + "maker_address": "0x1234...", + "timestamp": "1672290687" + } + bindings: [] + extensions: + - id: x-parser-unique-object-id + value: order + bindings: [] + extensions: *ref_0 + - &ref_6 + id: receiveTrade + title: Trade Event + description: Trade match or status change event for the authenticated user + type: send + messages: + - &ref_12 + id: trade + contentType: application/json + payload: + - name: Trade Event + description: Trade match, confirmation, or status change + type: object + properties: + - name: event_type + type: string + description: trade + required: true + - name: type + type: string + description: TRADE + required: true + - name: id + type: string + description: Trade ID + required: true + - name: taker_order_id + type: string + required: true + - name: market + type: string + description: Condition ID + required: true + - name: asset_id + type: string + required: true + - name: side + type: string + description: From taker's perspective + enumValues: + - BUY + - SELL + required: true + - name: size + type: string + required: true + - name: price + type: string + required: true + - name: fee_rate_bps + type: string + required: false + - name: status + type: string + enumValues: + - MATCHED + - MINED + - CONFIRMED + - RETRYING + - FAILED + required: true + - name: match_time + type: string + required: false + - name: last_update + type: string + required: false + - name: outcome + type: string + required: false + - name: owner + type: string + description: API key of the taker + required: true + - name: trade_owner + type: string + required: false + - name: maker_address + type: string + required: false + - name: transaction_hash + type: string + required: false + - name: bucket_index + type: integer + required: false + - name: maker_orders + type: array + required: false + properties: + - name: order_id + type: string + required: true + - name: owner + type: string + required: true + - name: maker_address + type: string + required: false + - name: matched_amount + type: string + required: true + - name: price + type: string + required: true + - name: fee_rate_bps + type: string + required: false + - name: asset_id + type: string + required: true + - name: outcome + type: string + required: false + - name: side + type: string + enumValues: + - BUY + - SELL + required: false + - name: trader_side + type: string + description: Whether the receiving user was TAKER or MAKER + enumValues: + - TAKER + - MAKER + required: false + - name: timestamp + type: string + description: Event timestamp in milliseconds + required: true + headers: [] + jsonPayloadSchema: + type: object + description: Trade match, confirmation, or status change event + required: + - event_type + - type + - id + - taker_order_id + - market + - asset_id + - side + - size + - price + - status + - owner + - timestamp + properties: + event_type: + type: string + const: trade + x-parser-schema-id: + type: + type: string + const: TRADE + x-parser-schema-id: + id: + type: string + description: Trade ID + x-parser-schema-id: + taker_order_id: + type: string + x-parser-schema-id: + market: + type: string + description: Condition ID + x-parser-schema-id: + asset_id: + type: string + x-parser-schema-id: + side: + type: string + enum: + - BUY + - SELL + description: From taker's perspective + x-parser-schema-id: + size: + type: string + x-parser-schema-id: + price: + type: string + x-parser-schema-id: + fee_rate_bps: + type: string + x-parser-schema-id: + status: + type: string + enum: + - MATCHED + - MINED + - CONFIRMED + - RETRYING + - FAILED + x-parser-schema-id: + match_time: + type: string + x-parser-schema-id: + last_update: + type: string + x-parser-schema-id: + outcome: + type: string + x-parser-schema-id: + owner: + type: string + description: API key of the taker + x-parser-schema-id: + trade_owner: + type: string + x-parser-schema-id: + maker_address: + type: string + x-parser-schema-id: + transaction_hash: + type: string + x-parser-schema-id: + bucket_index: + type: integer + x-parser-schema-id: + maker_orders: + type: array + items: + type: object + description: Maker order details within a trade + required: + - order_id + - owner + - matched_amount + - price + - asset_id + properties: + order_id: + type: string + x-parser-schema-id: + owner: + type: string + x-parser-schema-id: + maker_address: + type: string + x-parser-schema-id: + matched_amount: + type: string + x-parser-schema-id: + price: + type: string + x-parser-schema-id: + fee_rate_bps: + type: string + x-parser-schema-id: + asset_id: + type: string + x-parser-schema-id: + outcome: + type: string + x-parser-schema-id: + side: + type: string + enum: + - BUY + - SELL + x-parser-schema-id: + x-parser-schema-id: TradeMakerOrder + x-parser-schema-id: + trader_side: + type: string + enum: + - TAKER + - MAKER + description: Whether the receiving user was TAKER or MAKER + x-parser-schema-id: + timestamp: + type: string + description: Event timestamp in milliseconds + x-parser-schema-id: + x-parser-schema-id: TradeEvent + title: Trade Event + description: Trade match, confirmation, or status change + example: |- + { + "event_type": "trade", + "type": "TRADE", + "id": "28c4d2eb-bbea-40e7-a9f0-b2fdb56b2c2e", + "taker_order_id": "0x06bc63e346ed4ceddce9efd6b3af37c8f8f440c92fe7da6b2d0f9e4ccbc50c42", + "market": "0xbd31dc8a20211944f6b70f31557f1001557b59905b7738480ca09bd4532f84af", + "asset_id": "52114319501245915516055106046884209969926127482827954674443846427813813222426", + "side": "BUY", + "size": "10", + "price": "0.57", + "fee_rate_bps": "0", + "status": "MATCHED", + "match_time": "1672290701", + "last_update": "1672290701", + "outcome": "YES", + "owner": "9180014b-33c8-9240-a14b-bdca11c0a465", + "trade_owner": "9180014b-33c8-9240-a14b-bdca11c0a465", + "maker_address": "0x1234...", + "transaction_hash": "", + "bucket_index": 0, + "maker_orders": [ + { + "order_id": "0xff354cd7ca7539dfa9c28d90943ab5779a4eac34b9b37a757d7b32bdfb11790b", + "owner": "9180014b-33c8-9240-a14b-bdca11c0a465", + "maker_address": "0x5678...", + "matched_amount": "10", + "price": "0.57", + "fee_rate_bps": "0", + "asset_id": "52114319501245915516055106046884209969926127482827954674443846427813813222426", + "outcome": "YES", + "side": "SELL" + } + ], + "trader_side": "TAKER", + "timestamp": "1672290701" + } + bindings: [] + extensions: + - id: x-parser-unique-object-id + value: trade + bindings: [] + extensions: *ref_0 +sendOperations: + - *ref_1 + - *ref_2 + - *ref_3 +receiveOperations: + - *ref_4 + - *ref_5 + - *ref_6 +sendMessages: + - *ref_7 + - *ref_8 + - *ref_9 +receiveMessages: + - *ref_10 + - *ref_11 + - *ref_12 +extensions: + - id: x-parser-unique-object-id + value: user +securitySchemes: [] + +```` \ No newline at end of file diff --git a/PolymarketDocumentation-main/docs/builders/api-keys.md b/PolymarketDocumentation-main/docs/builders/api-keys.md new file mode 100644 index 00000000..8a7495a7 --- /dev/null +++ b/PolymarketDocumentation-main/docs/builders/api-keys.md @@ -0,0 +1,144 @@ +> ## Documentation Index +> Fetch the complete documentation index at: https://docs.polymarket.com/llms.txt +> Use this file to discover all available pages before exploring further. + +# Builder Code + +> Your builder code for order attribution + +Your **Builder Code** is a `bytes32` identifier that attributes orders routed through your application to your builder profile. Attach it to every order you submit — no additional authentication is required. + +## Accessing Your Builder Profile + + + + Go to + [polymarket.com/settings?tab=builder](https://polymarket.com/settings?tab=builder) + + + Click your profile image → Select "Builders" + + +## Getting Your Builder Code + +In the **Builder Code** section of your profile, copy the `bytes32` value. It looks like: + +``` +0x0000000000000000000000000000000000000000000000000000000000000001 +``` + +Store it in your environment variables or a secrets manager. + + + Builder codes are public identifiers — they appear onchain in the `builder` + field of every order you attribute. Only you control which orders include + your code, so keep it scoped to the apps you own. + + +## Profile Settings + +Your builder profile includes customizable settings: + +| Setting | Description | +| ------------------- | ----------------------------------------------------------------------- | +| **Profile Picture** | Displayed on the [Builder Leaderboard](https://builders.polymarket.com) | +| **Builder Name** | Public name shown on the leaderboard | +| **Builder Address** | Your unique builder identifier (read-only) | +| **Builder Code** | The `bytes32` code you attach to orders | +| **Current Tier** | Your rate limit tier: Unverified, Verified, or Partner | + +## Environment Variables + +Store your builder code as an environment variable: + + + + ```bash .env theme={null} + POLY_BUILDER_CODE=0x0000000000000000000000000000000000000000000000000000000000000001 + ``` + + + + ```typescript theme={null} + const builderCode = process.env.POLY_BUILDER_CODE!; + ``` + + + + ```python theme={null} + import os + + builder_code = os.environ["POLY_BUILDER_CODE"] + ``` + + + +## Using Your Builder Code + +Pass `builderCode` on every order to attribute it to your builder profile: + + + ```typescript TypeScript theme={null} + const response = await client.createAndPostOrder( + { + tokenID: "0x...", + price: 0.55, + size: 100, + side: Side.BUY, + builderCode: process.env.POLY_BUILDER_CODE!, + }, + { tickSize: "0.01", negRisk: false }, + ); + ``` + + ```python Python theme={null} + from py_clob_client_v2 import OrderArgs, PartialCreateOrderOptions + from py_clob_client_v2.order_builder.constants import BUY + + response = client.create_and_post_order( + OrderArgs( + token_id="0x...", + price=0.55, + size=100, + side=BUY, + builder_code=os.environ["POLY_BUILDER_CODE"], + ), + options=PartialCreateOrderOptions(tick_size="0.01", neg_risk=False), + ) + ``` + + +See [Order Attribution](/trading/orders/attribution) for full details. + +## Troubleshooting + + + + **Cause:** You've exceeded your tier's daily transaction limit. + + **Solution:** + + * Wait until the daily limit resets + * [Contact Polymarket](/builders/tiers#contact) to upgrade your tier + + + + **Cause:** You haven't created a builder profile yet. + + **Solution:** Go to + [polymarket.com/settings?tab=builder](https://polymarket.com/settings?tab=builder) + and set up your profile to get a builder code. + + + +## Next Steps + + + + Attach your builder code to orders for volume credit. + + + + Learn about rate limits and how to upgrade. + + diff --git a/PolymarketDocumentation-main/docs/builders/fees.md b/PolymarketDocumentation-main/docs/builders/fees.md new file mode 100644 index 00000000..fbc6b53d --- /dev/null +++ b/PolymarketDocumentation-main/docs/builders/fees.md @@ -0,0 +1,268 @@ +> ## Documentation Index +> Fetch the complete documentation index at: https://docs.polymarket.com/llms.txt +> Use this file to discover all available pages before exploring further. + +# Builder Fees + +> How builders earn fees on orders routed through their applications, and how to integrate. + +CLOB V2 introduces a fee layer that lets builders earn a fee on every order routed through their application. When a builder attaches their unique **builder code** to an order and that order matches, a **builder fee** is collected alongside any platform fee. + +Builder fees are flat percentages of trade notional, configured by each builder within enforced limits. They're additive — they stack on top of platform fees, never replace them. + + + New to the Builder Program? Start with [Builder Program](/builders/overview). This page covers the fee layer specifically. + + +*** + +## How it works + + + + + + + +Builder fees and platform fees are independent. What the user pays depends on the market config and whether a builder code is attached: + +| Market | Builder code attached | User pays | +| -------------------- | --------------------- | -------------------------- | +| No platform fee | No | Nothing | +| No platform fee | Yes | Builder fee only | +| Platform fee enabled | No | Platform fee only | +| Platform fee enabled | Yes | Platform fee + builder fee | + +Builder fees never replace platform fees — they're always additive. + + + Polymarket reserves the right to revoke your ability to charge a builder fee in its sole discretion, for any reason or no reason, including but not limited to instances where fees are determined to have been collected through fraudulent, deceptive, misleading, automated, self-referred, or other non-bona fide trading activity. + + +*** + +## Registration + +Register for a builder code through your Polymarket account. + + + + Go to [polymarket.com/settings?tab=builder](https://polymarket.com/settings?tab=builder) and set up your builder profile. + + + + Configure two rates on your profile: + + * `builder_taker_fee_bps` — charged on taker orders routed through your app + * `builder_maker_fee_bps` — charged on maker orders routed through your app + + + + Your profile is assigned a `bytes32` builder code. Attach it to every order you submit. + + + +### Fee rate limits + +| Parameter | Default | Maximum | +| -------------- | ---------- | ------------- | +| Taker fee rate | 0 bps (0%) | 100 bps (1%) | +| Maker fee rate | 0 bps (0%) | 50 bps (0.5%) | +| Granularity | — | 1 bp (0.01%) | + +### Rate change policy + +Fee rate changes are gated so users can see them coming: + +* **Cooldown.** One rate change per 7 days. +* **Advance notice.** Changes take effect 3 days after being scheduled. +* **One pending change at a time.** You can't queue multiple changes — wait for the current one to take effect (or cancel it) before scheduling another. + +*** + +## SDK integration + +The V2 SDK handles builder codes natively — no separate signing library, no extra headers. + +### Install + + + ```bash TypeScript theme={null} + npm install @polymarket/clob-client-v2 viem + ``` + + ```bash Python theme={null} + pip install py-clob-client-v2 + ``` + + + + Coming from the old `@polymarket/builder-signing-sdk` + HMAC header flow? That's gone in V2 — see [Migrating to CLOB V2](/v2-migration#builder-program) for the full upgrade path. + + +### Attach your builder code + +Pass `builderCode` on every order your application submits. This is how trades are attributed to your profile. + +**Limit order:** + +```typescript theme={null} +const response = await client.createAndPostOrder( + { + tokenID: "0x123...", + price: 0.55, + size: 100, + side: Side.BUY, + expiration: 1714000000, + builderCode: process.env.POLY_BUILDER_CODE, + }, + { tickSize: "0.01", negRisk: false }, + OrderType.GTC, +); +``` + +**Market order:** + +```typescript theme={null} +const response = await client.createAndPostMarketOrder( + { + tokenID: "0x123...", + side: Side.BUY, + amount: 500, + price: 0.5, // worst-price limit (slippage protection) + userUSDCBalance: 1000, // optional — enables fee-aware fill calculations + builderCode: process.env.POLY_BUILDER_CODE, + }, + { tickSize: "0.01", negRisk: false }, + OrderType.FOK, +); +``` + +If `builderCode` is omitted, no builder fee is charged. + + + You can also pass `builderConfig: { builderCode }` once at client construction and every order inherits it. See [Migrating to CLOB V2](/v2-migration#builder-program) for both patterns. + + +### Query fee parameters + +`getClobMarketInfo()` returns both platform and builder fee parameters for a market: + +```typescript theme={null} +const info = await client.getClobMarketInfo(conditionID); + +// Platform fee +// info.fd.r — fee rate +// info.fd.e — fee exponent +// info.fd.to — taker-only flag + +// Builder fee +// info.mbf — builder maker fee rate +// info.tbf — builder taker fee rate +``` + +*** + +## Fee calculation + +### Platform fees + +Platform fees use a dynamic per-market formula: + +``` +platform_fee = C × feeRate × p × (1 - p) +``` + +Where `C` is the trade size, `p` is the order price, and `feeRate` is a per-market parameter. Platform fees are currently taker-only and are not configurable by builders. + +### Builder fees + +Builder fees are a flat percentage of notional: + +``` +builder_fee = notional × builder_fee_rate_bps / 10000 +``` + +**Example.** A 1,000 pUSD taker buy routed through a builder charging 100 bps (1%) taker fee: + +``` +builder_fee = 1000 × 100 / 10000 = 10 pUSD +``` + +The maker and taker sides of a single trade can have different builder codes and different rates. If Builder A (0.3% maker) posts the resting order and Builder B (0.8% taker) submits the matching order, each earns their respective fee from their respective side. + +### Balance checks + +The CLOB's balance checker accounts for all applicable fees (platform + builder) when validating an order. Users must have enough pUSD to cover the trade plus the maximum possible fees. + +For market buy orders, pass `userUSDCBalance` and the SDK computes fee-adjusted fill amounts automatically. + +*** + +## Onchain attribution + +Builder attribution is part of the signed V2 order struct — not an offchain label. The `builder` field appears in every `OrderFilled` event emitted by the CTF Exchange V2 contract. + +### V2 order struct + +``` +salt, maker, signer, tokenId, makerAmount, takerAmount, +side, signatureType, timestamp, metadata, builder +``` + +The `builder` field is a `bytes32` matching your registered builder code. + +### EIP-712 domain + +The Exchange domain version is `"2"` in V2 (up from `"1"`). If you construct EIP-712 typed data manually rather than via the SDK, update your domain separator — see [For API users](/v2-migration#for-api-users) in the migration guide. + +*** + +## Fee processing and payouts + +When a user places an order with your `builderCode` attached: + +1. The CLOB validates the order and the builder code. +2. At match time, the Fees Service computes the platform and builder fees for each side. +3. The trade settles onchain via `CTFExchangeV2.matchOrders()`, emitting `OrderFilled` events. +4. The Builders Service indexes those events, joins onchain attribution with your builder profile, and accrues your earned fees. + +Collected builder fees are distributed to the wallet associated with your builder profile. + +*** + +## Program policies + +### Disabled codes + +Polymarket may disable a builder code at any time — for violations of the Builder Program terms, abusive fee practices, or platform integrity concerns. Orders carrying a disabled code will be rejected by the CLOB. + +### Public visibility + +Builder profiles and fee rates are publicly queryable. This is intentional — it lets users and third parties see what a builder charges before using their app. + +### Existing builders + +Builders with V1 integrations have builder code entities provisioned automatically. No action is required beyond upgrading to the V2 SDK and attaching your builder code to orders. See [Migrating to CLOB V2](/v2-migration) for the full upgrade path. + +*** + +## Next steps + + + + Overview of the Builder Program and benefits + + + + SDK methods for querying your builder trades and orders + + + + Details on attaching builder codes to orders + + + + Full V2 migration guide + + diff --git a/PolymarketDocumentation-main/docs/builders/overview.md b/PolymarketDocumentation-main/docs/builders/overview.md new file mode 100644 index 00000000..9234e8d8 --- /dev/null +++ b/PolymarketDocumentation-main/docs/builders/overview.md @@ -0,0 +1,229 @@ +> ## Documentation Index +> Fetch the complete documentation index at: https://docs.polymarket.com/llms.txt +> Use this file to discover all available pages before exploring further. + +# Builder Program + +> Build applications that route orders through Polymarket + +A **builder** is a person, group, or organization that routes orders from users to Polymarket. If you've created a platform that allows users to trade on Polymarket through your system, this program is for you. + +## Program Benefits + + + + All onchain operations are gas-free through our relayer + + + + Get credit for orders and compete for grants on the Builder Leaderboard + + + +### What You Get + +| Benefit | Description | +| ------------------- | ------------------------------------------------------------------------------- | +| **Relayer Access** | Gas-free wallet deployment, approvals, order execution and CTF operations | +| **Volume Tracking** | All orders attributed to your builder profile | +| **Leaderboard** | Public visibility on [builders.polymarket.com](https://builders.polymarket.com) | +| **Support** | Telegram channel and engineering support (Verified+) | + + + EOA wallets do not have relayer access. Users trading directly from an EOA pay + their own gas fees. + + +## How It Works + + + + User places an order through your application. + + + + Your app adds your `builderCode` to the order struct. + + + + Order is submitted to Polymarket's CLOB — the builder code is serialized + onchain as part of the signed order. + + + + Polymarket matches the order and covers gas fees for onchain operations. + + + + Volume is credited to your builder account for every matched trade where + your code is attached. + + + +## Getting Started + + + + Go to + [polymarket.com/settings?tab=builder](https://polymarket.com/settings?tab=builder) + and copy your builder code. + + + + Pass `builderCode` on every order you submit — see [Order + Attribution](/trading/orders/attribution). + + + + Use the Relayer Client for gas-free wallet deployment and onchain + operations. + + + + Monitor your volume on the [Builder + Leaderboard](https://builders.polymarket.com). + + + + + Bridging user funds in or out via the Bridge API? Also pass your code via the + optional `X-Builder-Code` header on [`/deposit`](/trading/bridge/deposit) and + [`/withdraw`](/trading/bridge/withdraw) so bridge traffic is attributed to your + integration. + + +## SDKs and Libraries + + + + Place orders with builder attribution + + + + Place orders with builder attribution + + + + Gasless onchain transactions + + + + Gasless onchain transactions + + + + Place orders with builder attribution + + + +## Examples + +These open-source demo applications show how to integrate Polymarket's CLOB Client and Builder Relayer Client for gasless trading with builder order attribution. + + + + Multiple wallet providers + + + + Deposit wallet support for new API users + + + + Orders, positions, CTF ops + + + +### Deposit Wallet Integrations + +New API users should use deposit wallets. Use the Builder Relayer Client to +deploy deposit wallets and execute signed wallet batches, then place CLOB +orders with `POLY_1271`. + +See the [Deposit Wallet Guide](/trading/deposit-wallets) for TypeScript, +Python, Rust, and direct API integration details. + +### Existing Safe Wallet Examples + +Existing Safe integrations can continue using Gnosis Safe wallets: + + + + MetaMask, Phantom, Rabby, and other browser wallets + + + + Privy embedded wallets + + + + Magic Link email/social authentication + + + + Turnkey embedded wallets + + + +### Existing Proxy Wallet Examples + +For existing Magic Link users from Polymarket.com: + + + + Auto-deploying proxy wallets for Polymarket.com Magic users + + + +### What Each Demo Covers + + + +
    +
  • User sign-in via wallet provider
  • +
  • User API credential derivation (L2 auth)
  • +
  • Builder config with remote signing
  • +
  • Signature types for Deposit Wallet, Safe, and Proxy wallets
  • +
+
+ + +
    +
  • Deposit wallet deployment via Relayer
  • +
  • Batch token approvals (pUSD + outcome tokens)
  • +
  • CTF operations (split, merge, redeem)
  • +
  • Transaction monitoring
  • +
+
+ + +
    +
  • CLOB client initialization
  • +
  • Order placement with builder attribution
  • +
  • Position and order management
  • +
  • Market discovery via Gamma API
  • +
+
+
+ +*** + +## Next Steps + + + + Create and manage your Builder API credentials. + + + + Learn about rate limits and how to upgrade. + + + + Configure your client to credit trades to your account. + + + + Set up gasless transactions for your users. + + diff --git a/PolymarketDocumentation-main/docs/builders/tiers.md b/PolymarketDocumentation-main/docs/builders/tiers.md new file mode 100644 index 00000000..64a7086c --- /dev/null +++ b/PolymarketDocumentation-main/docs/builders/tiers.md @@ -0,0 +1,170 @@ +> ## Documentation Index +> Fetch the complete documentation index at: https://docs.polymarket.com/llms.txt +> Use this file to discover all available pages before exploring further. + +# Tiers + +> Rate limits, rewards, and how to upgrade + +The Builder Program uses a tiered system to manage rate limits while rewarding high-performing integrations. Higher tiers unlock increased limits, weekly rewards, and priority support. + +## Feature Definitions + +| Feature | Description | +| --------------------------- | ------------------------------------------------------------------------------------------ | +| **Daily Relayer Txn Limit** | Maximum Relayer transactions per day for deposit wallet, Safe, and Proxy wallet operations | +| **API Rate Limits** | Rate limits for non-relayer endpoints (CLOB, Gamma, etc.) | +| **Gasless Trading** | Gas fees subsidized for supported smart-wallet operations | +| **Order Attribution** | Orders tracked and attributed to your Builder profile | +| **Builder Fees** | Builders who route orders can charge fees and monetize on flow | +| **Leaderboard Visibility** | Visibility on the [Builder Leaderboard](https://builders.polymarket.com/) | +| **Telegram Channel** | Private Builders channel for announcements and support | +| **Engineering Support** | Direct access to engineering team | +| **Marketing Support** | Promotion via official Polymarket social accounts | +| **Priority Access** | Early access to new features and products | + +*** + +## Tier Comparison + +| Feature | Unverified | Verified | Partner | +| --------------------------- | :--------: | :--------: | :-------: | +| **Daily Relayer Txn Limit** | 100/day | 10,000/day | Unlimited | +| **API Rate Limits** | Standard | Standard | Highest | +| **Gasless Trading\*** | Yes | Yes | Yes | +| **Order Attribution** | Yes | Yes | Yes | +| **Builder Fees** | Yes | Yes | Yes | +| **Leaderboard Visibility** | — | Yes | Yes | +| **Telegram Channel** | — | Yes | Yes | +| **Engineering Support** | — | Standard | Elevated | +| **Marketing Support** | — | Standard | Elevated | +| **Priority Access** | — | — | Yes | + +*** + +## Unverified + + + The default tier for all new builders. Start immediately with no approval + required. + + +**How to get started:** + +1. Go to [polymarket.com/settings?tab=builder](https://polymarket.com/settings?tab=builder) +2. Create a builder profile +3. Click **"+ Create New"** to generate API keys +4. Attach your [builder code](/trading/orders/attribution) to CLOB orders for attribution; use a Relayer API key for gasless wallet operations + +**What's included:** + +* Gasless trading through deposit wallets for new API users and existing Safe/Proxy wallets +* Gas subsidized on all Relayer transactions up to the daily limit +* Access to all client libraries and documentation + +*** + +## Verified + + + For builders who need higher throughput. Requires manual approval. + + +**How to upgrade:** + +Contact us at [builder@polymarket.com](mailto:builder@polymarket.com) with: + +* Your Builder API Key +* Use case description +* Expected volume +* Other relevant information (links, docs, decks, etc.) + +**Unlocks over Unverified:** + +* 100x daily Relayer transaction limit +* Monetize with Builder fees +* Leaderboard visibility at [builders.polymarket.com](https://builders.polymarket.com) +* Private Telegram channel for announcements and support +* Weekly USDC rewards based on volume (subject to approval) +* Grants (subject to approval) + +*** + +## Partner + + + Enterprise tier for high-volume integrations and strategic partners. + + +**Unlocks over Verified:** + +* Unlimited Relayer transactions +* Highest API rate limits +* Elevated engineering support +* Elevated and coordinated marketing support +* Priority access to new features and products + +*** + +## How to Upgrade + + + + Start with the Unverified tier and build your integration. + + + + Route orders through Polymarket and demonstrate consistent usage. + + + + Email [builder@polymarket.com](mailto:builder@polymarket.com) with your + builder key and use case. + + + + The Polymarket team reviews applications and responds within a few business + days. + + + +## Contact + +Ready to upgrade or have questions? + + + Email us with your Builder API Key and use case details. + + +## FAQ + + + + Verification is displayed in your [Builder Profile](https://polymarket.com/settings?tab=builder) settings. + + + + Relayer requests beyond your daily limit will be rate-limited and return an + error. Consider upgrading to Verified or Partner tier if you're hitting + limits. + + + + If you're not routing orders for other users (wallets), you can get unlimited + daily Relay transactions by obtaining a [Relayer API key](https://polymarket.com/settings?tab=api-keys). + + + +*** + +## Next Steps + + + + Create your Builder API credentials. + + + + Configure your client to credit trades to your account. + + diff --git a/PolymarketDocumentation-main/docs/changelog/changelog.md b/PolymarketDocumentation-main/docs/changelog/changelog.md new file mode 100644 index 00000000..1fce57e0 --- /dev/null +++ b/PolymarketDocumentation-main/docs/changelog/changelog.md @@ -0,0 +1,267 @@ +> ## Documentation Index +> Fetch the complete documentation index at: https://docs.polymarket.com/llms.txt +> Use this file to discover all available pages before exploring further. + +# Polymarket Changelog + +> Welcome to the Polymarket Changelog. Here you will find any important changes to Polymarket, including but not limited to CLOB, API, UI and Mobile Applications. + + + * **Sports fee coefficient**: The sports taker fee rate increases from `0.03` to `0.05` at midnight UTC. + * **Sports maker rebate**: The sports maker rebate decreases from 25% to 15% of collected taker fees. + * **Updated documentation**: [Fees](/trading/fees) and [Maker Rebates Program](/market-makers/maker-rebates). + + + + * **Finer tick size for World Cup markets**: All World Cup *to advance*, *moneyline*, *spreads*, and *totals* markets are now decimalized to a **0.0025 (0.25¢)** tick size. This lets you execute at smaller ticks and tighter spreads for the most competitive prices. Applies only to those World Cup markets — see [Tick Sizes](/trading/orders/overview#tick-sizes). + + + + * **New optional header**: `POST /deposit` and `POST /withdraw` now accept an `X-Builder-Code` header (bytes32 hex) for builder attribution. Without it, requests still succeed but return a `missing_builder_code` warning; a malformed code returns `400`. See [Deposit](/trading/bridge/deposit) and [Withdraw](/trading/bridge/withdraw). + + + + * **`DELETE /orders` limit**: The maximum number of order IDs per cancel request is now `1000`. Split larger cancellation batches across multiple requests. + + + + Raised burst and sustained rate limits for several CLOB trading endpoints. + + * CLOB POST /order - 120000 every 10 minutes (200/s) - (SUSTAINED) + * CLOB DELETE /order - 120000 every 10 minutes (200/s) - (SUSTAINED) + * CLOB POST /orders - 2000 every 10s (200/s) - (BURST) + * CLOB DELETE /orders - 2000 every 10s (200/s) - (BURST) + + See [Rate Limits](/api-reference/rate-limits) for the full table. + + + + * **New field**: Both `GET /v1/builders/leaderboard` and `GET /v1/builders/volume` now include a `builderCode` string on each entry — the builder's onchain attribution code as attached to orders via `builderCode` (see [Migrating to CLOB V2](/v2-migration)). + * **Additive change**: existing clients are unaffected. Legacy builders without a registered code return an empty string. + + + + * **`GET /markets/keyset` limit**: The maximum `limit` value is now `100`. Requests should use `after_cursor`/`next_cursor` to paginate through larger result sets. + + + + Polymarket's CLOB V2 upgrade is live on `https://clob.polymarket.com`. + + * **Production URL unchanged**: V2 now runs on the standard CLOB host. New integrations should use `https://clob.polymarket.com`. + * **No V1 compatibility**: Legacy V1 SDKs and V1-signed orders are no longer supported on production. + * **Open orders wiped**: Resting orders from before the cutover did not migrate and must be re-created with V2 signing. + * **Migration guide**: See [Migrating to CLOB V2](/v2-migration) for the SDK, raw order signing, pUSD, and builder attribution changes. + + + + * **Faster `POST /submit` responses**: The Relayer's `POST /submit` endpoint now returns immediately with just `{ transactionID, state: "STATE_NEW" }`. The `transactionHash` field has been removed from the submit response to improve performance. + * **How to get the hash**: Poll [`GET /transaction`](/api-reference/relayer/get-a-transaction-by-id) with the returned `transactionID` to retrieve the onchain `transactionHash` once the transaction has been broadcast. + + + + Polymarket is shipping a coordinated upgrade: **new Exchange contracts, a rewritten CLOB backend, and a new collateral token (pUSD)**. + + **Exchange upgrades go live April 28, 2026 at \~11:00 UTC with \~1 hour of downtime.** All integrations must migrate to the V2 SDK before the cutover — there will be no backward compatibility after go-live. + + **Full walkthrough:** [Migrating to CLOB V2](/v2-migration). Follow [Discord](https://discord.gg/polymarket), Telegram, and [status.polymarket.com](https://status.polymarket.com) for the exact start time. + + **Historical pre-cutover note:** before go-live, integrations could test against `https://clob-v2.polymarket.com`. As of April 28, V2 runs on `https://clob.polymarket.com`. + + **What's changing** + + * New Exchange contracts (CTF Exchange V2 + Neg Risk CTF Exchange V2) + * **pUSD** replaces USDC.e as the collateral token (standard ERC-20 on Polygon, backed by USDC, backing enforced onchain) + * Order struct: `nonce`, `feeRateBps`, `taker` removed — `timestamp` (ms), `metadata`, `builder` added + * Fees are now set at match time — no more `feeRateBps` on orders + * Builder attribution is native via `builderCode` on orders (no more `builder-signing-sdk`) + * EIP-712 Exchange domain version bumps from `"1"` to `"2"` (ClobAuth stays at `"1"`) + + **What you need to do** + + * Install the V2 SDK — [`@polymarket/clob-client-v2`](https://www.npmjs.com/package/@polymarket/clob-client-v2) or [`py-clob-client-v2`](https://pypi.org/project/py-clob-client-v2/) — and remove the legacy `clob-client` / `py-clob-client` packages + * Update constructor from positional args to options object; rename `chainId` → `chain` + * Remove `feeRateBps`, `nonce`, and `taker` from your order creation code + * If you're a builder, copy your code from [Settings → Builder](https://polymarket.com/settings?tab=builder) and attach it to orders + * If you sign orders without the SDK, update the `verifyingContract` and the signed Order fields — see [For API users](/v2-migration#for-api-users) + * Plan for all open orders to be wiped at cutover + + **During the window:** Trading will be paused for \~1 hour on April 28 starting around 11:00 UTC. The SDK's hot-swap mechanism will auto-refresh the client when V2 goes live — no manual action needed if you're on the latest SDK. + + + + * **Support contact**: Added a link to [our Bridge API provider's support](https://intercom.help/funxyz/en/articles/10732578-contact-us) (Fun.xyz) for failed, stuck, or compliance-held bridge transactions. See [Deposit Status](/trading/bridge/status). + + + + * **New endpoints**: Added `GET /markets/keyset` and `GET /events/keyset` for cursor-based pagination, replacing offset-based `GET /markets` and `GET /events`. + * **How it works**: These use an opaque `after_cursor`/`next_cursor` token instead of `offset`, providing stable and efficient paging through large result sets. Same filters, same response shape per item — the only differences are the wrapper response (`{ "markets": [...], "next_cursor": "..." }`) and the rejection of `offset`. + * **Migration**: The existing `GET /markets` and `GET /events` endpoints remain available but will be deprecated in a future release. New integrations should use the keyset variants. + + + + * **`closed` default change**: The `closed` query parameter on `GET /markets` now defaults to `false`. Closed markets are excluded from results unless you explicitly pass `closed=true`. + + + + Increased burst and sustained rate limits for several CLOB trading endpoints. + + * CLOB POST /order - 5000 every 10s (500/s) - (BURST) + * CLOB POST /order - 48000 every 10 minutes (80/s) + * CLOB DELETE /order - 5000 every 10s (500/s) - (BURST) + * CLOB DELETE /order - 48000 every 10 minutes (80/s) + * CLOB POST /orders - 1500 every 10s (150/s) - (BURST) + * CLOB POST /orders - 21000 every 10 minutes (35/s) + * CLOB DELETE /cancel-market-orders - 1500 every 10s (150/s) - (BURST) + * CLOB DELETE /cancel-market-orders - 21000 every 10 minutes (35/s) + + See [Rate Limits](/api-reference/rate-limits) for the full table. + + + + * **Fee calculation source**: Fees should now be calculated using the `feeSchedule` object within a market. + + + + * **New fee categories**: Fees now apply to Crypto, Sports, Finance, Politics, Economics, Culture, Weather, Tech, Mentions, and Other / General markets with updated rates per category. Geopolitical and world events markets remain fee-free. + * **Updated documentation**: [Fees](/trading/fees) and [Maker Rebates Program](/market-makers/maker-rebates). + + + + * **March Madness Liquidity Rewards**: Adding \$2M+ in liquidity rewards to both live and pregame markets. + * **How it works**: Liquidity rewards are payments for placing competitive bids. Rewards are paid out based on the size of your orders, how close they are to the midpoint, and how consistently they are quoted relative to other liquidity providers. Orders must be active on the book for a minimum of **3.5 seconds** to be eligible. + + **Daily reward rates for markets (subject to change):** + + **48 hours before GameStartTime:** + + * \$7.5k for full game ML market + * \$500 for 5 other markets (most recently created full game spread, most recently created full game total, 1st half ML, most recently created 1st half spread, most recently created 1st half total) + + **From game live to game completion (note: rewards are expressed in daily rates):** + + * \$60k for full game ML + * \$4k for most recently created full game spread and most recently created full game total + + **From game live to halftime (note: rewards are expressed in daily rates):** + + * \$8k for 1st half ML, most recently created 1st half spread, most recently created 1st half total + + * **Markets**: [Browse March Madness markets](https://polymarket.com/sports/cbb/games) + + * **More details**: [Liquidity Rewards documentation](/market-makers/liquidity-rewards#liquidity-rewards) + + + + * **Crypto market fees expansion**: Starting March 6, 2026, taker fees and maker rebates extend to all crypto markets including 1H, 4H, daily, and weekly. The same fee structure as existing crypto markets applies. Only new markets created after March 6 are affected. + * **Updated documentation**: [Fees](/trading/fees) and [Maker Rebates Program](/market-makers/maker-rebates) updated to reflect all crypto market coverage. + + + + * **5-minute crypto markets**: Launched with taker fees enabled. Fees follow the same curve as 15-minute crypto markets, peaking at 1.56% at 50% probability. + * **Maker Rebates**: Liquidity providers earn daily USDC rebates funded by taker fees, same as 15-minute crypto markets. + + + + * **Sports market fees**: Taker fees to be enabled on NCAAB (college basketball) and Serie A markets on February 18, 2026. + * **Per-market rebate calculation**: Rebates are now calculated per market, makers only compete with other makers in the same market. + * **Updated documentation**: [Maker Rebates Program](/market-makers/maker-rebates) updated with sports fee tables and parameters. + + + + * **Withdrawal Endpoint**: New `/withdraw` endpoint to bridge USDC.e from Polymarket to any supported chain and token. + * **Multi-chain withdrawals**: Withdraw to EVM chains (Ethereum, Arbitrum, Base, etc.), Solana, and Bitcoin. + * **Updated documentation**: Bridge API docs updated to reflect deposit and withdrawal functionality. + + + + * RTDS docs updated to reflect RTDS supports **comments** and **crypto prices** only. + * Removed legacy CLOB references and `clob_auth` from RTDS docs. + + + + * **Maker Rebates Program**: Updated funding schedule with distribution method (volume-weighted vs fee-curve weighted). + * **Fee-curve weighted rebates**: Documented fee-equivalent formula and rebate calculation. + * **FAQ**: Clarified how rebates are calculated during fee-curve weighted periods. + + + + * **Releases**: Daily Releases timing + * **HeartBeats API**: HeartBeats endpoint for monitoring connection status and canceling orders + * **Post Only Orders**: Orders that are rejected if they would immediately match against an existing order + + + + * **Taker Fees**: Enabled on 15-minute crypto markets. Fees vary by price and peak at 1.56% at 50% probability. + * **Maker Rebates**: Daily USDC rebates paid to liquidity providers, funded by taker fees. + + + + * **Crypto Price Feeds**: Access real-time cryptocurrency prices from two sources (Binance & Chainlink) + * **Comment Streaming**: Real-time updates for comment events including new comments, replies, and reactions + * **Dynamic Subscriptions**: Add, remove, and modify subscriptions without reconnecting + * **TypeScript Client**: Official TypeScript client available at [real-time-data-client](https://github.com/Polymarket/real-time-data-client) + For complete documentation, see [Market Data](/market-data/overview). + + + + * There has been a significant change to the structure of the price change message. This update will be applied at 11PM UTC September 15, 2025. We apologize for the short notice + * Please see the [Market Channel](/market-data/websocket/market-channel) for details. + + + + * Reduced maximum values for query parameters on Data-API /trades and /activity: + * `limit`: 500 + * `offset`: 1,000 + + + + * The batch orders limit has been increased from 5 -> 15. Read more about the batch orders functionality [here](/trading/orders/create). + + + + * We’re adding new fields to the `get-book` and `get-books` CLOB endpoints to include key market metadata that previously required separate queries. + * `min_order_size` + * type: string + * description: Minimum price increment. + * `neg_risk` + * type: boolean + * description: Boolean indicating whether the market is neg\_risk. + * `tick_size` + * type: string + * description: Minimum price increment. + + + + * We’re excited to roll out a highly requested feature: **order batching**. With this new endpoint, users can now submit up to five trades in a single request. To help you get started, we’ve included sample code demonstrating how to use it. Please see [Create Orders](/trading/orders/create) for more details. + + + + * We're adding a new `side` field to the `MakerOrder` portion of the trade object. This field will indicate whether the maker order is a `buy` or `sell`, helping to clarify trade events where the maker side was previously ambiguous. For more details, refer to the MakerOrder object on the [Orders](/trading/orders/cancel) page. + + + + * The 100 token subscription limit has been removed for the Markets channel. You can now subscribe to as many token IDs as needed for your use case. + * New Subscribe Field `initial_dump` + * Optional field to indicate whether you want to receive the initial order book state when subscribing to a token or list of tokens. + * `default: true` + + + + We’re excited to introduce a new order type soon to be available to all users: Fill and Kill (FAK). FAK orders behave similarly to the well-known Fill or Kill (FOK) orders, but with a key difference: + + * FAK will fill as many shares as possible immediately at your specified price, and any remaining unfilled portion will be canceled. + * Unlike FOK, which requires the entire order to fill instantly or be canceled, FAK is more flexible and aims to capture partial fills if possible. + + + + All API users will enjoy increased rate limits for the CLOB endpoints. + + * CLOB - /books (website) (300req - 10s / Throttle requests over the maximum configured rate) + * CLOB - /books (50 req - 10s / Throttle requests over the maximum configured rate) + * CLOB - /price (100req - 10s / Throttle requests over the maximum configured rate) + * CLOB markets/0x (50req / 10s - Throttle requests over the maximum configured rate) + * CLOB POST /order - 500 every 10s (50/s) - (BURST) - Throttle requests over the maximum configured rate + * CLOB POST /order - 3000 every 10 minutes (5/s) - Throttle requests over the maximum configured rate + * CLOB DELETE /order - 500 every 10s (50/s) - (BURST) - Throttle requests over the maximum configured rate + * DELETE /order - 3000 every 10 minutes (5/s) - Throttle requests over the maximum configured rate + diff --git a/PolymarketDocumentation-main/docs/concepts/markets-events.md b/PolymarketDocumentation-main/docs/concepts/markets-events.md new file mode 100644 index 00000000..424fc25a --- /dev/null +++ b/PolymarketDocumentation-main/docs/concepts/markets-events.md @@ -0,0 +1,108 @@ +> ## Documentation Index +> Fetch the complete documentation index at: https://docs.polymarket.com/llms.txt +> Use this file to discover all available pages before exploring further. + +# Markets & Events + +> Understanding the fundamental building blocks of Polymarket + +Every prediction on Polymarket is structured around two core concepts: **markets** and **events**. Understanding how they relate is essential for building on the platform. + + + + + + + +## Markets + +A **market** is the fundamental tradable unit on Polymarket. Each market represents a single binary question with Yes/No outcomes. + + + + + + + +Every market has: + +| Identifier | Description | +| ---------------- | ------------------------------------------------------------------------ | +| **Condition ID** | Unique identifier for the market's condition in the CTF contracts | +| **Question ID** | Hash of the market question used for resolution | +| **Token IDs** | ERC1155 token IDs used for trading on the CLOB — one for Yes, one for No | + + + Markets can only be traded via the CLOB if `enableOrderBook` is `true`. Some + markets may exist onchain but not be available for order book trading. + + +### Market Example + +A simple market might be: + +> **"Will Bitcoin reach \$150,000 by December 2026?"** + +This creates two outcome tokens: + +* **Yes token** - Redeemable for `$1` if Bitcoin reaches `$150k` +* **No token** - Redeemable for `$1` if Bitcoin doesn't reach `$150k` + +## Events + +An **event** is a container that groups one or more related markets together. Events provide organizational structure and enable multi-outcome predictions. + +### Single-Market Events + +When an event contains just one market, it creates a simple market pair. The event and market are essentially equivalent. + +``` +Event: Will Bitcoin reach $100,000 by December 2024? +└── Market: Will Bitcoin reach $100,000 by December 2024? (Yes/No) +``` + +### Multi-Market Events + +When an event contains two or more markets, it creates a grouped market pair. This enables mutually exclusive multi-outcome predictions. + +``` +Event: Who will win the 2024 Presidential Election? +├── Market: Donald Trump? (Yes/No) +├── Market: Joe Biden? (Yes/No) +├── Market: Kamala Harris? (Yes/No) +└── Market: Other? (Yes/No) +``` + +## Identifying Markets + +Every market and event has a unique **slug** that appears in the Polymarket URL: + +``` +https://polymarket.com/event/fed-decision-in-october + └── slug: fed-decision-in-october +``` + +You can use slugs to fetch specific markets or events from the API: + +```bash theme={null} +# Fetch event by slug +curl "https://gamma-api.polymarket.com/events?slug=fed-decision-in-october" +``` + +## Sports Markets + +Specifically for sports markets, outstanding limit orders are **automatically cancelled** once the game begins, clearing the order book at the official start time. However, game start times can shift — if a game starts earlier than scheduled, orders may not be cleared in time. Always monitor your orders closely around game start times. + +*** + +## Next Steps + + + + Learn how prices are determined and how the order book works. + + + + Start querying markets and events from the API. + + diff --git a/PolymarketDocumentation-main/docs/concepts/order-lifecycle.md b/PolymarketDocumentation-main/docs/concepts/order-lifecycle.md new file mode 100644 index 00000000..df38760e --- /dev/null +++ b/PolymarketDocumentation-main/docs/concepts/order-lifecycle.md @@ -0,0 +1,159 @@ +> ## Documentation Index +> Fetch the complete documentation index at: https://docs.polymarket.com/llms.txt +> Use this file to discover all available pages before exploring further. + +# Order Lifecycle + +> Understanding how orders flow from creation to settlement + +Every trade on Polymarket follows a specific lifecycle. Orders are created offchain, matched by an operator, and settled onchain through smart contracts. This hybrid approach combines the speed of centralized matching with the security of blockchain settlement. + + + + + + + +## How Orders Work + +All orders on Polymarket are **limit orders**. A limit order specifies the price you're willing to pay (or accept) and the quantity you want to trade. + + + "Market orders" are simply limit orders with a price set to execute + immediately against the best available resting orders. + + +Orders are **EIP712-signed messages**. When you place an order, you sign a structured message with your private key. This signature authorizes the Exchange contract to execute the trade on your behalf—without ever taking custody of your funds. + +## Order Types + +| Type | Behavior | Use Case | +| ------- | ------------------------------------------------------------- | ------------------------ | +| **GTC** | Good Till Cancelled — rests on book until filled or cancelled | Standard limit orders | +| **GTD** | Good Till Date — auto-expires at specified time | Time-limited orders | +| **FOK** | Fill Or Kill — fill entirely or cancel immediately | All-or-nothing execution | +| **FAK** | Fill And Kill — fill what's available, cancel the rest | Partial fills acceptable | + +### Post-Only Orders + +Post-only orders will only rest on the book. If a post-only order would match immediately (cross the spread), it's rejected instead of executed. This guarantees you're always the maker, never the taker. + + + + Your client creates an order object containing: + + * Token ID (which outcome you're trading) + * Side (buy or sell) + * Price and size + * Expiration time + * Timestamp (in milliseconds, used for order uniqueness) + + You sign this order with your private key, creating an EIP712 signature. + + + + The signed order is submitted to the Central Limit Order Book (CLOB) operator. The operator validates: + + * Signature is valid + * You have sufficient balance + * You have set the required allowances + * Price meets minimum tick size requirements + + + + **If the order is marketable** (your buy price ≥ lowest ask, or your sell price ≤ highest bid), it matches against resting orders. Some markets apply a short taker delay before matching: + + * **Taker delay:** used on selected crypto and finance up/down markets. The order is held for 250 ms, then validation runs again and the order is matched or placed on the book. The API waits for this hold and returns the final order result. To check a specific market, call the public CLOB endpoint `GET https://clob.polymarket.com/clob-markets/{condition_id}` or SDK method `getClobMarketInfo(conditionID)` and look for `itode: true`. + * **Sports/game delay:** enabled on configured sports markets around live game conditions. The order waits for the market's configured delay window before matching. + + During either delay, the order is pending and cannot be canceled. If the market, balance, allowance, or risk checks fail when the delay expires, the order is rejected instead of matching. + + **If the order is not marketable**, it rests on the book waiting for a counterparty. It remains open until: + + * Another order matches against it + * You cancel it + * It expires (GTD orders only) + + + + When orders match, the operator submits the trade to the blockchain. The Exchange contract: + + * Verifies both signatures + * Transfers tokens from seller to buyer + * Transfers pUSD from buyer to seller + + Settlement is **atomic**—either the entire trade succeeds or nothing happens. + + + + The trade achieves finality on Polygon. Your token balances update and the trade appears in your history. + + + +## Order Statuses + +When you place an order, it receives one of these statuses: + +| Status | Description | +| ----------- | ----------------------------------------------------------------------------------------------------------------------- | +| `live` | Order is resting on the book | +| `matched` | Order matched immediately | +| `delayed` | Marketable order accepted into an asynchronous delay window on configured seconds-delay markets, such as sports markets | +| `unmatched` | Marketable order placed on the book after the delay expired without a match | + +## Trade Statuses + +After matching, trades progress through these statuses: + +| Status | Terminal | Description | +| ----------- | -------- | ------------------------------------------------------ | +| `MATCHED` | No | Trade matched, sent to executor for onchain submission | +| `MINED` | No | Transaction mined into the blockchain | +| `CONFIRMED` | Yes | Trade achieved finality, successful | +| `RETRYING` | No | Transaction failed, being retried | +| `FAILED` | Yes | Trade failed permanently | + +## Maker vs Taker + +| Role | Description | When | +| --------- | ------------------------------- | ----------------------------------------------------- | +| **Maker** | Adds liquidity to the book | Your order rests and is later matched | +| **Taker** | Removes liquidity from the book | Your order matches immediately against resting orders | + +Price improvement always benefits the taker. If you place a buy order at `$0.55` and it matches against a resting sell at `$0.52`, you pay `$0.52`. + +## Cancellation + +You can cancel orders at any time before they're matched via the CLOB API, except while a marketable order is in a pending delay window. + +Partial fills cannot be cancelled—only the unfilled portion of an order can be cancelled. + +## Requirements + +Before placing orders, ensure: + +| Requirement | Description | +| ------------------- | -------------------------------------------------- | +| **Balance** | Sufficient pUSD (for buys) or tokens (for sells) | +| **Allowance** | Approve the Exchange contract to spend your assets | +| **API Credentials** | Valid API key for authenticated endpoints | + + + Order size is limited by your available balance minus any amounts reserved by existing open orders. + + $$ + \text{maxOrderSize} = \text{balance} - \sum(\text{openOrderSize} - \text{filledAmount}) + $$ + + +## Next Steps + + + + Learn how markets are resolved and winning tokens redeemed. + + + + Start placing orders with our step-by-step guide. + + diff --git a/PolymarketDocumentation-main/docs/concepts/positions-tokens.md b/PolymarketDocumentation-main/docs/concepts/positions-tokens.md new file mode 100644 index 00000000..6086a1b3 --- /dev/null +++ b/PolymarketDocumentation-main/docs/concepts/positions-tokens.md @@ -0,0 +1,116 @@ +> ## Documentation Index +> Fetch the complete documentation index at: https://docs.polymarket.com/llms.txt +> Use this file to discover all available pages before exploring further. + +# Positions & Tokens + +> Understanding outcome tokens and how positions work on Polymarket + +Every prediction on Polymarket is represented by **outcome tokens**. When you trade, you're buying and selling these tokens. Your **position** is simply your balance of tokens for a given market. + + + + + + + +## Outcome Tokens + +Each market has exactly two outcome tokens: + +| Token | Redeems for | If... | +| ------- | ----------- | ------------------------ | +| **Yes** | \$1.00 | The event occurs | +| **No** | \$1.00 | The event does not occur | + +Tokens are **ERC1155** assets on Polygon, using the [Gnosis Conditional Token Framework](https://github.com/gnosis/conditional-tokens-contracts/) (CTF). This means they're fully onchain and function as standard ERC1155 tokens. + + + Outcome tokens are always fully backed. Every Yes/No pair in existence is + backed by exactly `$1` of pUSD collateral locked in the CTF contract. + + +### Split + +Convert pUSD into outcome tokens. Splitting \$1 creates 1 Yes token and 1 No token. + +``` +$100 pUSD → 100 Yes tokens + 100 No tokens +``` + +Use this when you want to: + +* Create inventory for market making +* Obtain both sides of a market + +### Trade + +Buy or sell tokens on the order book. This is how most users acquire positions. + +* **Buy Yes** at `$0.60` → Pay `$0.60`, receive 1 Yes token +* **Sell Yes** at `$0.60` → Give up 1 Yes token, receive `$0.60` + +You can sell your position at any time before resolution. + +### Merge + +Convert a complete set of tokens back into pUSD. Merging requires equal amounts of Yes and No tokens. + +``` +100 Yes tokens + 100 No tokens → $100 pUSD +``` + +Use this when you want to: + +* Exit a position without trading +* Convert accumulated tokens back to collateral + +### Redeem + +After a market resolves, exchange winning tokens for pUSD. + +| Outcome | Yes tokens | No tokens | +| ------------------- | -------------- | -------------- | +| Event occurs | Worth \$1 each | Worth \$0 | +| Event doesn't occur | Worth \$0 | Worth \$1 each | + +``` +100 winning tokens → $100 pUSD +``` + +### Position Value + +The value of your position depends on the current market price: + +``` +Position value = Token balance × Current price +``` + +If you hold 100 Yes tokens and Yes is trading at \$0.75: + +``` +Position value = 100 × $0.75 = $75 +``` + +## Profit and Loss + +Your profit depends on how the market resolves compared to your entry price. + +### Example - Buying Yes at 0.40 + +| Scenario | Outcome | Return | Profit | +| ------------------- | -------- | ------ | ------------------------- | +| Event occurs | Yes wins | \$1.00 | +\$0.60 per token (150%) | +| Event doesn't occur | No wins | \$0.00 | -\$0.40 per token (-100%) | + +### Holding Rewards + +Polymarket pays a **4.00% annualized** Holding Reward based on your total position value in eligible markets. Your total position value is randomly sampled once each hour, and the reward is distributed daily. The rate is variable and subject to change at Polymarket's discretion. + +### Example - Selling Before Resolution + +You can lock in profits or cut losses by selling before the market resolves: + +* Bought Yes at `$0.40` +* Price rises to `$0.70` +* Sell at `$0.70` → Profit of `$0.30` per token (75%) diff --git a/PolymarketDocumentation-main/docs/concepts/prices-orderbook.md b/PolymarketDocumentation-main/docs/concepts/prices-orderbook.md new file mode 100644 index 00000000..15b11812 --- /dev/null +++ b/PolymarketDocumentation-main/docs/concepts/prices-orderbook.md @@ -0,0 +1,116 @@ +> ## Documentation Index +> Fetch the complete documentation index at: https://docs.polymarket.com/llms.txt +> Use this file to discover all available pages before exploring further. + +# Prices & Orderbook + +> How prices work and how the order book enables peer-to-peer trading + +Polymarket uses a **Central Limit Order Book (CLOB)** for trading. Prices aren't set by Polymarket—they emerge from supply and demand as users trade with each other. + + + + + + + +## Prices Are Probabilities + +Every share on Polymarket is priced between `$0.00` and `$1.00`. The price directly represents the market's belief in the probability of that outcome. + +| Price | Implied Probability | +| ------ | ------------------- | +| \$0.25 | 25% chance | +| \$0.50 | 50% chance | +| \$0.75 | 75% chance | + + + The displayed price is the **midpoint** of the bid-ask spread. If the spread + is wider than \$0.10, the last traded price is shown instead. + + +### Example + +If the best bid for "Yes" is `$0.34` and the best ask is `$0.40`: + +``` +Displayed price = ($0.34 + $0.40) / 2 = $0.37 (37% probability) +``` + +You won't necessarily trade at `$0.37`—you'll pay the ask (`$0.40`) when buying or receive the bid (`$0.34`) when selling. + +## The Order Book + +The order book is a list of all open buy and sell orders for a market. It has two sides: + +| Side | Description | +| ---- | ----------------------------------------------------------- | +| Bids | Buy orders—the highest prices traders are willing to pay | +| Asks | Sell orders—the lowest prices traders are willing to accept | + +The **spread** is the gap between the highest bid and lowest ask. Tighter spreads mean more liquid markets. + +## Order Types + +### Market Orders + +Execute immediately at the best available price. Use when you want instant execution and are willing to pay the spread. + +* **Buying**: You pay the lowest ask price +* **Selling**: You receive the highest bid price + +### Limit Orders + +Execute only at your specified price or better. Use when you want price control and are willing to wait. + +* Your order sits in the book until someone trades against it +* Orders can **partially fill** as different traders match portions of your order +* You can cancel unfilled orders at any time + + + All orders on Polymarket are technically limit orders. A "market order" is + simply a limit order priced to execute immediately against resting orders. + + +## How Trades Work + +Polymarket's CLOB is **hybrid-decentralized**: + +1. **Offchain matching** — An operator matches compatible orders +2. **Onchain settlement** — Matched trades settle via smart contracts + + + + + + + +This design gives you the speed of centralized matching with the security of onchain settlement. You always maintain custody of your funds. + +## Price Discovery + +When a new market launches, there's no initial price. The first price emerges when: + +1. Someone places a limit order to buy Yes at a price (e.g., `$0.60`) +2. Someone places a limit order to buy No at the complementary price (e.g., `$0.40`) +3. Since `$0.60` + `$0.40` = `$1.00`, the orders match + +When matched, `$1.00` is converted into 1 Yes token and 1 No token, each going to their respective buyers. + +## Next Steps + + + Polymarket's orderbook has **no trading size limits** — it matches willing + buyers and sellers of any amount. However, large orders may move the price + significantly. Always check orderbook depth before trading in size. + + + + + Learn about outcome tokens and how positions work. + + + + Understand what happens from order placement to settlement. + + diff --git a/PolymarketDocumentation-main/docs/concepts/pusd.md b/PolymarketDocumentation-main/docs/concepts/pusd.md new file mode 100644 index 00000000..d4f2a3fd --- /dev/null +++ b/PolymarketDocumentation-main/docs/concepts/pusd.md @@ -0,0 +1,166 @@ +> ## Documentation Index +> Fetch the complete documentation index at: https://docs.polymarket.com/llms.txt +> Use this file to discover all available pages before exploring further. + +# Polymarket USD + +> pUSD — the collateral token used for all trading on Polymarket + +**pUSD** (Polymarket USD) is the collateral token used for all trading on Polymarket. It's a standard ERC-20 token on Polygon, backed by USDC. The smart contract — which enables the withdrawal functionality — enforces the backing. No algorithmic peg, no fractional reserve. + + + **Day to day, nothing changes.** You load funds, see a balance, trade, and + withdraw. pUSD is the technical settlement layer underneath the same + experience you're used to. + + +*** + +## Why pUSD + +The protocol settles all trading activity in native USDC, providing a more capital efficient, scalable, and institutionally aligned settlement standard as the platform continues to grow. + +pUSD is a standard ERC-20 wrapper that represents a USDC claim. Wrapping and unwrapping are enforced onchain by the `CollateralOnramp` and `CollateralOfframp` contracts. + +*** + +## Key facts + +| | | +| -------------- | ----------------------- | +| Token standard | ERC-20 | +| Network | Polygon mainnet | +| Decimals | 6 | +| Backing | USDC (enforced onchain) | +| Transferable | Yes — standard ERC-20 | + +pUSD is designed to function within Polymarket. There are no current plans to list it on external exchanges. + +See the [Contracts](/resources/contracts) page for all collateral-related contract addresses. + +*** + +## Wrapping — USDC.e → pUSD + +Use the **CollateralOnramp** to wrap USDC.e into pUSD. + +```solidity theme={null} +function wrap(address _asset, address _to, uint256 _amount) external +``` + +**Parameters** + +* `_asset` — address of the asset being wrapped. Must be USDC.e. +* `_to` — recipient of the minted pUSD. Does not have to be `msg.sender`. +* `_amount` — amount to wrap, in USDC.e base units (6 decimals). + +**Requirements** + +* The caller must first approve the **CollateralOnramp** contract (not the pUSD token) to spend USDC.e. +* Reverts with `OnlyUnpaused()` if the admin has paused USDC.e. + +### Example + + + ```typescript TypeScript theme={null} + import { + createWalletClient, + createPublicClient, + http, + parseAbi, + parseUnits, + } from "viem"; + import { polygon } from "viem/chains"; + import { privateKeyToAccount } from "viem/accounts"; + + const account = privateKeyToAccount(process.env.PRIVATE_KEY as `0x${string}`); + const walletClient = createWalletClient({ account, chain: polygon, transport: http() }); + const publicClient = createPublicClient({ chain: polygon, transport: http() }); + + const ONRAMP = "0x93070a847efEf7F70739046A929D47a521F5B8ee" as const; + const USDCE = "0x2791Bca1f2de4661ED88A30C99A7a9449Aa84174" as const; // USDC.e on Polygon + + const amount = parseUnits("100", 6); // 100 USDC.e + + // 1. Approve the Onramp to spend your USDC.e + const approveHash = await walletClient.writeContract({ + address: USDCE, + abi: parseAbi(["function approve(address spender, uint256 amount) returns (bool)"]), + functionName: "approve", + args: [ONRAMP, amount], + }); + await publicClient.waitForTransactionReceipt({ hash: approveHash }); + + // 2. Wrap USDC.e → pUSD + const wrapHash = await walletClient.writeContract({ + address: ONRAMP, + abi: parseAbi(["function wrap(address _asset, address _to, uint256 _amount)"]), + functionName: "wrap", + args: [USDCE, account.address, amount], + }); + await publicClient.waitForTransactionReceipt({ hash: wrapHash }); + ``` + + ```python Python theme={null} + from web3 import Web3 + + ONRAMP = "0x93070a847efEf7F70739046A929D47a521F5B8ee" + USDCE = "0x2791Bca1f2de4661ED88A30C99A7a9449Aa84174" + + amount = 100 * 10**6 # 100 USDC.e + + # 1. Approve the Onramp to spend your USDC.e + usdce = w3.eth.contract(address=USDCE, abi=[{ + "name": "approve", "type": "function", + "inputs": [{"name": "spender", "type": "address"}, + {"name": "amount", "type": "uint256"}], + "outputs": [{"type": "bool"}], + }]) + usdce.functions.approve(ONRAMP, amount).transact({"from": address}) + + # 2. Wrap USDC.e → pUSD + onramp = w3.eth.contract(address=ONRAMP, abi=[{ + "name": "wrap", "type": "function", + "inputs": [{"name": "_asset", "type": "address"}, + {"name": "_to", "type": "address"}, + {"name": "_amount", "type": "uint256"}], + "outputs": [], + }]) + onramp.functions.wrap(USDCE, address, amount).transact({"from": address}) + ``` + + +*** + +## Unwrapping — pUSD → USDC.e + +Use the **CollateralOfframp** to unwrap pUSD back into USDC.e. + +```solidity theme={null} +function unwrap(address _asset, address _to, uint256 _amount) external +``` + +**Parameters** + +* `_asset` — asset you want to receive. Must be USDC.e. +* `_to` — recipient of the underlying asset. +* `_amount` — amount of pUSD to unwrap (6 decimals). + +**Requirements** + +* The caller must first approve the **CollateralOfframp** contract to spend their pUSD. +* Same pause gate as the Onramp. + +*** + +## Next steps + + + + All Polymarket contract addresses and audits + + + + Deposit from other chains — auto-wraps to pUSD + + diff --git a/PolymarketDocumentation-main/docs/concepts/resolution.md b/PolymarketDocumentation-main/docs/concepts/resolution.md new file mode 100644 index 00000000..e7c8d916 --- /dev/null +++ b/PolymarketDocumentation-main/docs/concepts/resolution.md @@ -0,0 +1,151 @@ +> ## Documentation Index +> Fetch the complete documentation index at: https://docs.polymarket.com/llms.txt +> Use this file to discover all available pages before exploring further. + +# Resolution + +> How markets are resolved and winning positions redeemed + +When the outcome of an event becomes known, the market is **resolved**. Resolution determines which outcome won, allowing holders of winning tokens to redeem them for \$1 each. Losing tokens become worthless. + +Polymarket uses the **UMA Optimistic Oracle** for decentralized, permissionless resolution. Anyone can propose an outcome, and anyone can dispute it if they believe it's incorrect. + + + + + + + +## Resolution Rules + +Every market has pre-defined resolution rules that specify: + +* **Resolution source** — Where the outcome will be determined from (e.g., official announcements, specific websites) +* **End date** — When the market is eligible for resolution +* **Edge cases** — How ambiguous situations should be handled + + + Always read the resolution rules before trading. The market title describes + the question, but the **rules** define how it resolves. + + + + + Anyone can propose a resolution by: + + 1. Selecting the winning outcome + 2. Posting a bond (typically \$750 pUSD) + 3. Submitting the proposal to the UMA Oracle + + If the proposal is correct and undisputed, the proposer receives their bond back plus a reward. + + + If you propose incorrectly or too early, you lose your entire bond. Only + propose if you're confident in the outcome and understand the process. + + + + + After a proposal, there's a **2-hour challenge period** where anyone can dispute the outcome. + + * **If no dispute**: The proposal is accepted and the market resolves + * **If disputed**: A new proposal round begins. If the second proposal is also disputed, the resolution escalates to UMA's DVM (Data Verification Mechanism) for a token holder vote. + + There are three possible resolution flows: + + 1. **No dispute** — Propose then Resolve (fastest, \~2 hours) + 2. **One dispute** — Propose, Challenge, second Propose, Resolve (second proposal accepted) + 3. **Two disputes** — Propose, Challenge, second Propose, second Challenge, Resolve via DVM vote + + + + To dispute a proposal: + + 1. Post a counter-bond (same amount as proposer, typically \$750) + 2. The dispute triggers a new proposal round, or if already in the second round, a debate period + + During the **24-48 hour debate period**, evidence can be submitted in UMA's Discord channels (`#evidence-rationale` and `#voting-discussion`). + + + + After the debate period, UMA token holders vote on the correct outcome. The voting process takes approximately 48 hours. + + | Outcome | Result | Bond Distribution | + | ----------------- | -------------------------------------- | -------------------------------------------------------------------------------------------------------- | + | **Proposer wins** | Original proposal accepted | Proposer gets bond back + half of disputer's bond | + | **Disputer wins** | Proposal rejected, new proposal needed | Disputer gets bond back + half of proposer's bond | + | **Too Early** | Event hasn't concluded yet | Disputer gets bond back + half of proposer's bond | + | **Unknown/50-50** | Neither outcome applicable (rare) | Market resolves 50/50 — each token redeems for \$0.50; disputer gets bond back + half of proposer's bond | + + + +## After Resolution + +Once a market resolves: + +* **Trading stops** — You can no longer buy or sell tokens for this market +* **Winning tokens** become redeemable for \$1.00 each +* **Losing tokens** become worthless (\$0.00) + +### Redeeming Tokens + +After resolution, redeem through the CTF collateral adapter to exchange winning tokens for pUSD. The adapter burns your ERC1155 outcome tokens through the CTF contract, receives the released USDC.e collateral, wraps it into pUSD, and returns pUSD to your wallet. + +``` +100 winning tokens → $100 pUSD +``` + +## Clarifications + +In rare cases, unforeseen circumstances require clarification of the rules after trading begins. Polymarket may issue an **"Additional context"** update that proposers and voters should consider during resolution. + +Clarifications: + +* Cannot change the fundamental intent of the question +* Are published onchain via the bulletin board contract +* Should be considered by UMA voters when resolving disputes + + + If you believe a clarification is needed, request it in the [Polymarket + Discord](https://discord.com/invite/polymarket) `#market-review` channel. + + +## Resolution Timeline + +| Phase | Duration | +| --------------------------- | ----------- | +| Challenge period | 2 hours | +| Debate period (if disputed) | 24-48 hours | +| UMA voting (if disputed) | \~48 hours | + +**Undisputed resolution**: \~2 hours after proposal + +**Disputed resolution**: 4-6 days total + +## Contract Addresses + +| Contract | Address | Network | +| ---------------------- | -------------------------------------------- | --------------- | +| **UmaCtfAdapter v3.0** | `0x157Ce2d672854c848c9b79C49a8Cc6cc89176a49` | Polygon Mainnet | +| **UmaCtfAdapter v2.0** | `0x6A9D222616C90FcA5754cd1333cFD9b7fb6a4F74` | Polygon Mainnet | +| **UmaCtfAdapter v1.0** | `0xCB1822859cEF82Cd2Eb4E6276C7916e692995130` | Polygon Mainnet | + +## Resources + +* [UMA Oracle Portal](https://oracle.uma.xyz/) — View and interact with proposals +* [UMA Documentation](https://docs.uma.xyz/) — Learn more about the Optimistic Oracle +* [Polymarket Discord](https://discord.com/invite/polymarket) — Discuss resolutions and request clarifications +* [UmaCtfAdapter Source Code](https://github.com/Polymarket/uma-ctf-adapter) — Smart contract source +* [UmaCtfAdapter Audit](https://github.com/Polymarket/uma-ctf-adapter/blob/main/audit/Polymarket_UMA_Optimistic_Oracle_Adapter_Audit.pdf) — Security audit report + +## Next Steps + + + + Learn how to redeem winning tokens after resolution. + + + + Understand how markets are structured. + + diff --git a/PolymarketDocumentation-main/docs/dev-tooling.md b/PolymarketDocumentation-main/docs/dev-tooling.md new file mode 100644 index 00000000..b7767c8c --- /dev/null +++ b/PolymarketDocumentation-main/docs/dev-tooling.md @@ -0,0 +1,43 @@ +> ## Documentation Index +> Fetch the complete documentation index at: https://docs.polymarket.com/llms.txt +> Use this file to discover all available pages before exploring further. + +# Overview + +> Learn about Polymarket's developer tooling roadmap. + +We are improving Polymarket's developer integration surface across SDKs, APIs, and frontend tooling. The unified TypeScript and Python SDKs are the first beta release in this effort and are currently being hardened before a stable release. Once stable, these SDKs will supersede the existing SDKs, and we will provide a documented migration path. + + + + Current beta release of the unified SDKs for early integrators. + + + + Next, harden the beta SDKs, resolve feedback from integrators, and publish + the documented migration path from the existing SDKs. + + + + A cohesive API surface across Polymarket developer interfaces. + + + + A unified SDK for systems-level integrations and backend services. + + + + Frontend-oriented tooling for React applications on top of the same unified + model. + + + + + + Beta documentation for the unified TypeScript SDK. + + + + Beta documentation for the unified Python SDK. + + diff --git a/PolymarketDocumentation-main/docs/dev-tooling/python.md b/PolymarketDocumentation-main/docs/dev-tooling/python.md new file mode 100644 index 00000000..36ed52a8 --- /dev/null +++ b/PolymarketDocumentation-main/docs/dev-tooling/python.md @@ -0,0 +1,1247 @@ +> ## Documentation Index +> Fetch the complete documentation index at: https://docs.polymarket.com/llms.txt +> Use this file to discover all available pages before exploring further. + +# Python SDK + +> Build with the unified Polymarket Python SDK. + +The unified Python SDK gives you a consistent surface across Polymarket discovery, market data, trading, account data, and realtime streams. + + + The Python SDK is currently in beta. We are keeping it in this beta phase + while we address issues and harden the SDK before transitioning to a more + stable release. + + +The SDK ships parallel async and sync clients with matching method names and arguments: `AsyncPublicClient` / `PublicClient` for public reads, and `AsyncSecureClient` / `SecureClient` for authenticated reads and trading. Prefer the async clients for servers, bots, and any code that already runs inside an event loop. Use the sync clients for scripts, notebooks, and one-off tools where an event loop would just add ceremony. Realtime stream subscriptions are async only and require the async clients. + +Examples below show the body of an `async def main()` function; wrap them with `asyncio.run(main())` to run as a script, as shown in [Quickstart](#quickstart). To switch a snippet to sync, swap `AsyncPublicClient` / `AsyncSecureClient` for `PublicClient` / `SecureClient`, drop `await`, replace `async with` with `with`, replace `async for` with `for`, and remove the `asyncio.run(...)` wrapper. + +## Quickstart + + + + Install the SDK from PyPI. + + + ```bash uv theme={null} + uv add polymarket-client + ``` + + ```bash pip theme={null} + pip install polymarket-client + ``` + + ```bash poetry theme={null} + poetry add polymarket-client + ``` + + + + + Create an instance of the `AsyncPublicClient` inside an `async with` block so its network transports are released when you are done. + + ```python theme={null} + from polymarket import AsyncPublicClient + + async with AsyncPublicClient() as client: + ... + ``` + + + + Fetch a page of markets to discover active trading opportunities. + + + ```python Async theme={null} + import asyncio + + from polymarket import AsyncPublicClient + + + async def main() -> None: + async with AsyncPublicClient() as client: + markets = client.list_markets(closed=False, page_size=5) + first_page = await markets.first_page() + + for market in first_page.items: + # market: Market + ... + + + asyncio.run(main()) + ``` + + ```python Sync theme={null} + from polymarket import PublicClient + + + with PublicClient() as client: + markets = client.list_markets(closed=False, page_size=5) + first_page = markets.first_page() + + for market in first_page.items: + # market: Market + ... + ``` + + + + +## SDK Patterns + +The SDK uses consistent patterns for pagination, Python-native model values, and structured SDK exceptions across public and authenticated workflows. + +### Typed Primitives + +Identifiers and EVM addresses are exposed as `typing.NewType` aliases (`MarketId`, `ConditionId`, `TokenId`, `EventId`, `EvmAddress`, …) so static type checkers can keep them distinct from plain strings. Precision-sensitive price, size, and amount fields generally use `decimal.Decimal`; date and time fields use `datetime.date` or `datetime.datetime`. + +```python theme={null} +from datetime import datetime +from decimal import Decimal + +from polymarket import ConditionId, EvmAddress, MarketId, TokenId + + +class Market: + id: MarketId + condition_id: ConditionId | None + state: MarketState + outcomes: MarketOutcomes + resolution: MarketResolution + # … + + +class MarketState: + start_date: datetime | None + end_date: datetime | None + # … + + +class MarketOutcome: + label: str + token_id: TokenId | None + price: Decimal | None + + +class MarketResolution: + resolved_by: EvmAddress | None + # … +``` + +### Market and Event Data + +Market and event responses are returned as SDK models with snake\_case fields and nested submodels. + + + ```python Market theme={null} + class Market: + id: MarketId + slug: str | None + condition_id: ConditionId | None + question: str | None + description: str | None + category: str | None + image: str | None + icon: str | None + state: MarketState + outcomes: MarketOutcomes + metrics: MarketMetrics + prices: MarketPrices + trading: MarketTrading + resolution: MarketResolution + rewards: MarketRewards + sports: MarketSportsMetadata + tags: tuple[MarketTag, ...] + # … + ``` + + ```python Event theme={null} + class Event: + id: EventId + slug: str | None + title: str | None + subtitle: str | None + description: str | None + category: str | None + subcategory: str | None + image: str | None + icon: str | None + created_at: datetime | None + updated_at: datetime | None + published_at: datetime | None + state: EventState + schedule: EventSchedule + metrics: EventMetrics + trading: EventTrading + estimation: EventEstimation + sports: EventSportsMetadata + partners: tuple[EventPartner, ...] + markets: tuple[Market, ...] + series: tuple[EventSeries, ...] + # … + ``` + + +### Environment Configuration + +Production is the default environment. Pass an `Environment` object when your integration needs to target a different deployment or custom endpoint set. The client owns network transports, so use `async with` (or call `await client.close()`) to release them when you are done. + +```python theme={null} +from polymarket import AsyncPublicClient, PRODUCTION + + +async with AsyncPublicClient(environment=PRODUCTION) as client: + ... +``` + +### Pagination + +With async clients, list methods return an `AsyncPaginator` across paginated endpoints. Use `async for` to iterate through pages. + +```python theme={null} +async with AsyncPublicClient() as client: + markets = client.list_markets(closed=False, page_size=10) + + async for page in markets: + # page.items: tuple[Market, ...] + ... +``` + +You can also fetch the first page directly and resume later from a cursor. + +```python theme={null} +first_page = await markets.first_page() +# first_page.items: tuple[Market, ...] + +async for page in markets.from_cursor(first_page.next_cursor): + # page.items: tuple[Market, ...] + ... +``` + +When you only care about the items and not page boundaries, iterate them directly. + +```python theme={null} +async for market in markets.items(): + # market: Market + ... +``` + +### Error Handling + +All SDK exceptions inherit from `PolymarketError`. Catch specific subclasses to handle known cases, and catch `PolymarketError` as the final SDK fallback. + + + Catching `PolymarketError` last ensures error subclasses added in future SDK + releases do not pass through unhandled. + + +```python theme={null} +from polymarket import ( + AsyncPublicClient, + PolymarketError, + RateLimitError, + UserInputError, +) + +async with AsyncPublicClient() as client: + try: + markets = client.list_markets(closed=False, page_size=10) + first_page = await markets.first_page() + # first_page.items: tuple[Market, ...] + except RateLimitError: + # Retry later. + ... + except UserInputError: + # Fix the request parameters. + ... + except PolymarketError: + # Handle any other SDK error. + ... +``` + +## Market Data + +Use market data methods to fetch market and event details, order books, current prices, historical prices, and batch quotes. + + + ```python Market theme={null} + market = await client.get_market( + url="https://polymarket.com/market/eth-flipped-in-2026", + ) + + market_by_slug = await client.get_market(slug="eth-flipped-in-2026") + + market_by_id = await client.get_market(id="12345") + ``` + + ```python Event theme={null} + event = await client.get_event( + url="https://polymarket.com/event/presidential-election-2028", + ) + + event_by_slug = await client.get_event(slug="presidential-election-2028") + + event_by_id = await client.get_event(id="12345") + ``` + + +Then fetch related tags, order books, prices, and history. + + + ```python Tags theme={null} + market_tags = await client.get_market_tags(market.id) + + event_tags = await client.get_event_tags(event.id) + ``` + + ```python Order Book theme={null} + yes_token_id = market.outcomes.yes.token_id + if yes_token_id is None: + raise RuntimeError("Market does not have a YES token id") + + book = await client.get_order_book(token_id=yes_token_id) + ``` + + ```python Prices theme={null} + yes_token_id = market.outcomes.yes.token_id + if yes_token_id is None: + raise RuntimeError("Market does not have a YES token id") + + buy_price = await client.get_price(token_id=yes_token_id, side="BUY") + + midpoint = await client.get_midpoint(token_id=yes_token_id) + + spread = await client.get_spread(token_id=yes_token_id) + + last_trade = await client.get_last_trade_price(token_id=yes_token_id) + ``` + + ```python History theme={null} + yes_token_id = market.outcomes.yes.token_id + if yes_token_id is None: + raise RuntimeError("Market does not have a YES token id") + + history = await client.get_price_history(token_id=yes_token_id, interval="1d") + ``` + + ```python Batch Reads theme={null} + from polymarket import PriceRequest + + yes_token_id = market.outcomes.yes.token_id + no_token_id = market.outcomes.no.token_id + if yes_token_id is None or no_token_id is None: + raise RuntimeError("Market does not have both outcome token ids") + + prices = await client.get_prices( + requests=[ + PriceRequest(token_id=yes_token_id, side="BUY"), + PriceRequest(token_id=no_token_id, side="BUY"), + ], + ) + + midpoints = await client.get_midpoints(token_ids=[yes_token_id, no_token_id]) + ``` + + +## Discovery + +Use discovery methods to browse events, markets, teams, tags, comments, sports metadata, and search results. The examples below show a few common entry points. + + + + ```python theme={null} + events = client.list_events(page_size=10) + + async for page in events: + # page.items: tuple[Event, ...] + ... + ``` + + + + ```python theme={null} + markets = client.list_markets(closed=False, page_size=10) + + async for page in markets: + # page.items: tuple[Market, ...] + ... + ``` + + + + ```python theme={null} + teams = client.list_teams(league="NBA", page_size=10) + + async for page in teams: + # page.items: tuple[Team, ...] + ... + ``` + + + + ```python theme={null} + tags = client.list_tags(page_size=10) + + async for page in tags: + # page.items: tuple[Tag, ...] + ... + + tag = await client.get_tag(slug="politics") + + related_tags = await client.get_related_tags(slug="politics") + + related_resources = await client.get_related_tag_resources( + slug="politics", + status="active", + ) + ``` + + + + ```python theme={null} + import os + + comments = client.list_comments( + parent_entity_id="12345", + parent_entity_type="Event", + page_size=20, + ) + + async for page in comments: + # page.items: tuple[Comment, ...] + ... + + thread = await client.get_comment_thread("456", get_positions=True) + + user_comments = client.list_comments_by_user_address( + address=os.environ["POLYMARKET_TARGET_WALLET_ADDRESS"], + page_size=10, + order="DESC", + ) + + async for page in user_comments: + # page.items: tuple[Comment, ...] + ... + ``` + + + + ```python theme={null} + sports = await client.get_sports() + + # sports: tuple[SportsMetadata, ...] + ``` + + + + ```python theme={null} + results = client.search(q="ethereum", page_size=10) + + async for page in results: + for search_results in page.items: + # search_results.events: tuple[Event, ...] + # search_results.tags: tuple[SearchTag, ...] + # search_results.profiles: tuple[Profile, ...] + ... + ``` + + + +## Realtime Streams + +Subscribe through one SDK interface even when events come from different stream families. The SDK routes each subscription spec to the right stream and merges the results into one async iterator. Subscriptions are async only and require `AsyncPublicClient` or `AsyncSecureClient`. + +```python theme={null} +from polymarket import AsyncPublicClient +from polymarket.streams import CryptoPricesSpec, MarketSpec + + +yes_token_id = market.outcomes.yes.token_id +if yes_token_id is None: + raise RuntimeError("Market does not have a YES token id") + +async with AsyncPublicClient() as client: + stream = await client.subscribe( + [ + MarketSpec(token_ids=[yes_token_id]), + CryptoPricesSpec( + topic="prices.crypto.binance", + symbols=["btcusdt"], + ), + ], + ) + + async with stream: + async for event in stream: + # event: + # | MarketBookEvent + # | MarketPriceChangeEvent + # | MarketLastTradePriceEvent + # | MarketTickSizeChangeEvent + # | MarketBestBidAskEvent + # | NewMarketEvent + # | MarketResolvedEvent + # | CryptoPricesBinanceEvent + print(type(event).__name__) + break +``` + +`AsyncSecureClient.subscribe` accepts the same public subscription specs and adds `UserSpec` for user-scoped order and trade events on the authenticated wallet. + +```python theme={null} +import os + +from polymarket import AsyncSecureClient +from polymarket.streams import UserSpec + + +async with await AsyncSecureClient.create( + private_key=os.environ["POLYMARKET_PRIVATE_KEY"], + wallet=os.environ.get("POLYMARKET_WALLET_ADDRESS"), +) as secure_client: + user_stream = await secure_client.subscribe(UserSpec()) + + async with user_stream: + async for event in user_stream: + # event: + # | UserOrderEvent + # | UserTradeEvent + print(type(event).__name__) + break +``` + +## Authenticated Client + +Create a secure client when you need wallet-scoped reads or trading. + + + Secure clients own multiple network transports. Wrap them in `async with`, or + call `await secure_client.close()` when you are done, to release the + underlying connections. The snippets below show client creation and subsequent + calls as a flat sequence for readability — in real code, keep the client + inside an `async with` block or close it explicitly. + + +### Private Key Setup + +The Python SDK authenticates with a local private key. By default, +`AsyncSecureClient.create` uses the signer's deterministic Deposit Wallet as the +account wallet. Pass `wallet` when you want to authenticate an existing wallet, +such as an existing Deposit Wallet, Poly Safe, Poly Proxy, or the signer address +itself for EOA trading. + +The examples below pass `wallet` to make account selection explicit. Omit +`wallet` to use the default Deposit Wallet flow. + +```python theme={null} +import os + +from polymarket import AsyncSecureClient + + +async with await AsyncSecureClient.create( + private_key=os.environ["POLYMARKET_PRIVATE_KEY"], + wallet=os.environ.get("POLYMARKET_WALLET_ADDRESS"), +) as secure_client: + ... +``` + +Keep private keys and API credentials in your secret manager or local environment. Do not commit them to source control. + +### API Key Authorization + +Configure API key authorization when the SDK needs to deploy a Deposit Wallet or +submit approval transactions. + + + ```python Relayer API Key theme={null} + import os + + from polymarket import AsyncSecureClient, RelayerApiKey + + + secure_client = await AsyncSecureClient.create( + private_key=os.environ["POLYMARKET_PRIVATE_KEY"], + wallet=os.environ.get("POLYMARKET_WALLET_ADDRESS"), + api_key=RelayerApiKey( + key=os.environ["POLYMARKET_RELAYER_API_KEY"], + address=os.environ["POLYMARKET_RELAYER_API_KEY_ADDRESS"], + ), + ) + ``` + + ```python Builder API Key theme={null} + import os + + from polymarket import AsyncSecureClient, BuilderApiKey + + + secure_client = await AsyncSecureClient.create( + private_key=os.environ["POLYMARKET_PRIVATE_KEY"], + wallet=os.environ.get("POLYMARKET_WALLET_ADDRESS"), + api_key=BuilderApiKey( + key=os.environ["POLYMARKET_BUILDER_API_KEY"], + secret=os.environ["POLYMARKET_BUILDER_SECRET"], + passphrase=os.environ["POLYMARKET_BUILDER_PASSPHRASE"], + ), + ) + ``` + + + + Builder API keys are supported for backwards compatibility with builders that + still use them for wallet operations. They are not used for order attribution. + Use `builder_code` on orders for attribution. + + +### Trading Setup + +Before placing orders, make sure the authenticated wallet is deployed and has +the required trading approvals. `AsyncSecureClient.create` resolves the signer's +deterministic Deposit Wallet by default and deploys it if needed. + + + From this point forward, snippets in Trading Setup, Trading, Position + Lifecycle, and Wallet Operations submit real on-chain transactions or live + orders against the configured environment when executed. Review each call + before running it against a wallet that holds funds. + + +Set up the approvals required for trading. + +```python theme={null} +await secure_client.setup_trading_approvals() +``` + +`setup_trading_approvals()` waits for the setup transaction internally and is +idempotent. If the wallet already has the required approvals, it returns without +submitting a transaction. + +### Trading + +Use a secure client to create, sign, and submit orders. Limit orders specify the price and size you want to trade. Market orders execute against resting liquidity immediately. + +Order placement returns a discriminated response. Check `response.ok` before reading order details. + +#### Place Orders + + + + ```python theme={null} + yes_token_id = market.outcomes.yes.token_id + if yes_token_id is None: + raise RuntimeError("Market does not have a YES token id") + + response = await secure_client.place_limit_order( + token_id=yes_token_id, + side="BUY", + price="0.52", + size="10", + ) + + if response.ok: + # response.order_id: str + ... + else: + # response.code: OrderResponseErrorCode + # response.message: str + ... + ``` + + + + ```python theme={null} + import time + + yes_token_id = market.outcomes.yes.token_id + if yes_token_id is None: + raise RuntimeError("Market does not have a YES token id") + + response = await secure_client.place_limit_order( + token_id=yes_token_id, + side="SELL", + price="0.52", + size="10", + expiration=int(time.time()) + 60 * 60, + ) + + if response.ok: + # response.order_id: str + ... + else: + # response.code: OrderResponseErrorCode + # response.message: str + ... + ``` + + + + ```python theme={null} + yes_token_id = market.outcomes.yes.token_id + if yes_token_id is None: + raise RuntimeError("Market does not have a YES token id") + + response = await secure_client.place_market_order( + token_id=yes_token_id, + side="BUY", + amount="10", + max_spend="11", + order_type="FAK", + ) + + if response.ok: + # response.order_id: str + ... + else: + # response.code: OrderResponseErrorCode + # response.message: str + ... + ``` + + + + ```python theme={null} + yes_token_id = market.outcomes.yes.token_id + if yes_token_id is None: + raise RuntimeError("Market does not have a YES token id") + + response = await secure_client.place_market_order( + token_id=yes_token_id, + side="SELL", + shares="10", + order_type="FOK", + ) + + if response.ok: + # response.order_id: str + ... + else: + # response.code: OrderResponseErrorCode + # response.message: str + ... + ``` + + + + ```python theme={null} + import os + + yes_token_id = market.outcomes.yes.token_id + if yes_token_id is None: + raise RuntimeError("Market does not have a YES token id") + + response = await secure_client.place_limit_order( + token_id=yes_token_id, + side="BUY", + price="0.52", + size="10", + builder_code=os.environ["POLYMARKET_BUILDER_CODE"], + ) + + if response.ok: + # response.order_id: str + ... + else: + # response.code: OrderResponseErrorCode + # response.message: str + ... + ``` + + + +#### Create, Then Post + +Create signed orders separately when you want to review, store, or batch them before submitting. + + + + ```python theme={null} + yes_token_id = market.outcomes.yes.token_id + if yes_token_id is None: + raise RuntimeError("Market does not have a YES token id") + + order = await secure_client.create_limit_order( + token_id=yes_token_id, + side="BUY", + price="0.52", + size="10", + ) + + response = await secure_client.post_order(order) + + if response.ok: + # response.order_id: str + ... + else: + # response.code: OrderResponseErrorCode + # response.message: str + ... + ``` + + + + ```python theme={null} + yes_token_id = market.outcomes.yes.token_id + if yes_token_id is None: + raise RuntimeError("Market does not have a YES token id") + + first_order = await secure_client.create_limit_order( + token_id=yes_token_id, + side="BUY", + price="0.52", + size="10", + ) + + second_order = await secure_client.create_limit_order( + token_id=yes_token_id, + side="SELL", + price="0.58", + size="5", + ) + + responses = await secure_client.post_orders([first_order, second_order]) + + for response in responses: + if response.ok: + # response.order_id: str + ... + else: + # response.code: OrderResponseErrorCode + # response.message: str + ... + ``` + + + +### Position Lifecycle + +Use position lifecycle methods to split collateral into outcome tokens, merge +complete sets back into collateral, or redeem resolved positions. These examples +assume the secure client is configured with API key authorization as shown in +[API Key Authorization](#api-key-authorization), and that you set up trading +approvals as shown above. + + + + ```python theme={null} + condition_id = market.condition_id + if condition_id is None: + raise RuntimeError("Market does not have a condition id") + + handle = await secure_client.split_position( + condition_id=condition_id, + amount=1, + ) + + outcome = await handle.wait() + + # outcome.transaction_hash: TransactionHash + ``` + + + + ```python theme={null} + condition_id = market.condition_id + if condition_id is None: + raise RuntimeError("Market does not have a condition id") + + handle = await secure_client.merge_positions( + condition_id=condition_id, + amount="max", + ) + + outcome = await handle.wait() + + # outcome.transaction_hash: TransactionHash + ``` + + + + ```python theme={null} + handle = await secure_client.redeem_positions( + market_id=market.id, + ) + + outcome = await handle.wait() + + # outcome.transaction_hash: TransactionHash + ``` + + + +### Wallet Operations + +Use wallet operation methods for direct token movements from the authenticated +wallet. Amounts are in base units. These examples assume the secure client is +configured with API key authorization as shown in [API Key +Authorization](#api-key-authorization). + +```python theme={null} +import os + +handle = await secure_client.transfer_erc20( + token_address=secure_client.environment.collateral_token, + recipient_address=os.environ["POLYMARKET_RECIPIENT_ADDRESS"], + amount=1_000_000, +) + +outcome = await handle.wait() + +# outcome.transaction_hash: TransactionHash +``` + +### Order Management + +Manage open orders for the authenticated wallet after placement. These examples assume `order_id` comes from an accepted order response. + + + + ```python theme={null} + order = await secure_client.get_order(order_id=order_id) + + # order: OpenOrder + ``` + + + + ```python theme={null} + condition_id = market.condition_id + if condition_id is None: + raise RuntimeError("Market does not have a condition id") + + open_orders = secure_client.list_open_orders(market=condition_id) + + async for page in open_orders: + # page.items: tuple[OpenOrder, ...] + ... + ``` + + + + ```python theme={null} + response = await secure_client.cancel_order(order_id=order_id) + + # response.canceled: tuple[str, ...] + ``` + + + + ```python theme={null} + yes_token_id = market.outcomes.yes.token_id + if yes_token_id is None: + raise RuntimeError("Market does not have a YES token id") + + response = await secure_client.cancel_market_orders(token_id=yes_token_id) + + # response.canceled: tuple[str, ...] + ``` + + + +### Rewards and Scoring + +Use rewards methods to inspect active reward programs and scoring methods to check whether orders are eligible for scoring. `list_current_rewards` and `list_market_rewards` are public reads and are also available on `AsyncPublicClient` / `PublicClient`; `get_order_scoring` and `get_orders_scoring` require a secure client because they read account-scoped order data. + + + + ```python theme={null} + rewards = secure_client.list_current_rewards() + + async for page in rewards: + # page.items: tuple[CurrentReward, ...] + ... + ``` + + + + ```python theme={null} + condition_id = market.condition_id + if condition_id is None: + raise RuntimeError("Market does not have a condition id") + + rewards = secure_client.list_market_rewards(condition_id=condition_id) + + async for page in rewards: + # page.items: tuple[MarketReward, ...] + ... + ``` + + + + ```python theme={null} + scoring = await secure_client.get_order_scoring(order_id=order_id) + + # scoring: bool + ``` + + + + ```python theme={null} + scoring = await secure_client.get_orders_scoring( + order_ids=[first_order_id, second_order_id], + ) + + # scoring: dict[str, bool] + ``` + + + +### Account Data + +Secure clients read account-scoped data for the authenticated wallet by default. Methods that take a `user=` parameter (positions, portfolio value, activity) accept a different wallet address to read its data instead. + + + + ```python theme={null} + positions = secure_client.list_positions( + market=[market.id], + page_size=10, + ) + + async for page in positions: + # page.items: tuple[Position, ...] + ... + ``` + + + + ```python theme={null} + value = await secure_client.get_portfolio_values(market=[market.id]) + + # value: tuple[PortfolioValue, ...] + ``` + + + + ```python theme={null} + activity = secure_client.list_activity( + market=[market.id], + page_size=10, + ) + + async for page in activity: + for item in page.items: + match item.type: + case "TRADE": + # item.token_id: TokenId + # item.shares: Decimal + ... + case "REWARD": + # item.amount: Decimal + ... + case _: + # SPLIT / MERGE / REDEEM / CONVERSION / MAKER_REBATE + # / TAKER_REBATE / REFERRAL_REWARD / YIELD + ... + ``` + + + + ```python theme={null} + yes_token_id = market.outcomes.yes.token_id + if yes_token_id is None: + raise RuntimeError("Market does not have a YES token id") + + trades = secure_client.list_account_trades(token_id=yes_token_id) + + async for page in trades: + # page.items: tuple[ClobTrade, ...] + ... + ``` + + + + ```python theme={null} + notifications = await secure_client.get_notifications() + + # notifications: tuple[Notification, ...] + ``` + + + +### Authentication Sessions + +Secure clients expose the API credentials created for the authenticated session. Store them securely if you want to reuse the session later without producing a new authentication signature while the credentials remain valid. + + + + ```python theme={null} + import os + + from polymarket import AsyncSecureClient + + + secure_client = await AsyncSecureClient.create( + private_key=os.environ["POLYMARKET_PRIVATE_KEY"], + wallet=os.environ.get("POLYMARKET_WALLET_ADDRESS"), + ) + + saved_credentials = secure_client.credentials.model_dump(mode="json") + ``` + + + + ```python theme={null} + import os + + from polymarket import ApiKeyCreds, AsyncSecureClient + + + credentials = ApiKeyCreds.model_validate(saved_credentials) + + secure_client = await AsyncSecureClient.create( + private_key=os.environ["POLYMARKET_PRIVATE_KEY"], + wallet=os.environ.get("POLYMARKET_WALLET_ADDRESS"), + credentials=credentials, + ) + ``` + + + +## Changelog + +### `0.1.0b17` + +* Added SDK pagination for Combo lifecycle activity and server-cursor pagination for Combo positions. +* Added typed overloads for market, event, and tag lookups, mutually-exclusive lookup arguments, and `redeem_positions`. +* Added trade time filters. +* Hardened Combo pagination filters and branded Combo activity IDs. +* Breaking beta change: Combo activity and position fields now use `wallet`, `amount`, and `payout`; Combo activity rows no longer expose `module_kind`. + +```diff theme={null} +-activity.user_address +-activity.amount_usdc +-redeem_activity.payout_usdc +-position.user_address ++activity.wallet ++activity.amount ++redeem_activity.payout ++position.wallet +``` + +### `0.1.0b16` + +* Fixed Deposit Wallet trading setup approvals to use the current Protocol V2 auto-redeem operator. + +### `0.1.0b15` + +* Added support for Perps. + +### `0.1.0b14` + +* Added builder API key management for creating, fetching, and revoking builder API keys. +* Added support for merging multiple positions in one request. +* Added runnable Python SDK examples for common integration workflows. +* Resolve closed markets when redeeming positions. +* Gasless transaction handles now wait for relayer transactions to reach confirmed state before resolving. + +### `0.1.0b13` + +* Require GTD limit order expirations to be at least 3 minutes in the future. + +### `0.1.0b12` + +* Support CLOB order tick sizes `0.005` and `0.0025`. + +### `0.1.0b11` + +* Preserve already-deployed legacy UUPS Deposit Wallets when secure clients resolve the default wallet, while new Deposit Wallet deployments use the beacon factory path. +* Retry rejected JSON-RPC batches by splitting them into smaller batches. +* Added typed Gamma search sort fields for search requests. + +### `0.1.0b10` + +* Preserve `group_item_title` on market responses so grouped market titles remain available after normalization. + +### `0.1.0b9` + +* RFQ quoter sessions now emit typed `RfqTradeEvent` events for confirmed Combos fills. +* RFQ rejection errors now expose `error_id` values and parse `INVALID_SIGNATURE` and `INTERNAL_ERROR` codes. + +### `0.1.0b8` + +* Added `parent_event_id` to `Event` so child events can link back to their parent event. +* Added `max_price` and `min_price` protection fields to market order requests. +* Handle legacy multi-outcome market listings more safely by omitting markets that cannot be represented by the binary market model. +* Normalize empty-string trade and position market icons to `None`. +* Parse Combo trade activity rows correctly. +* Support new Combos RFQ error codes for balance, allowance, and pre-execution reservation failures. +* Broad user websocket subscriptions now omit market filters so all-market streams receive trade events. + +### `0.1.0b7` + +* Point Combos RFQ endpoints at the production domains: `combos-rfq-api.polymarket.com` (REST) and `combos-rfq-gateway-quoter.polymarket.com` (quoter WebSocket). + +### `0.1.0b6` + +* Added `list_combo_markets` for fetching the Combo market catalog with SDK pagination. See [Combos](/market-makers/combos). +* Parse RFQ quote rejections that use the `SUBMISSION_WINDOW_CLOSED` gateway error code. + +### `0.1.0b5` + +* Added Combos support for multi-leg RFQ positions. See [Combos](/market-makers/combos). +* Added notebook-friendly model display for Jupyter workflows. +* `ConditionId` is now deprecated in favor of `CtfConditionId`; existing + `ConditionId` exports remain available as deprecated aliases. + +### `0.1.0b4` + +* Added dataframe conversion support for SDK models and response collections. + +**Secure client setup now defaults to the Deposit Wallet flow** + +`AsyncSecureClient.create` can now derive and use the signer's deterministic +Deposit Wallet when you omit `wallet`. If you already know which Polymarket +wallet you want to use, keep passing `wallet`. + +```diff theme={null} +secure_client = await AsyncSecureClient.create( + private_key=os.environ["POLYMARKET_PRIVATE_KEY"], +- wallet=os.environ["POLYMARKET_WALLET_ADDRESS"], +) +``` + +If you want to keep account selection explicit, no change is required: + +```python theme={null} +secure_client = await AsyncSecureClient.create( + private_key=os.environ["POLYMARKET_PRIVATE_KEY"], + wallet=os.environ["POLYMARKET_WALLET_ADDRESS"], +) +``` + +**`setup_trading_approvals()` now waits internally** + +You no longer need to wait on the returned handle. Call the method once before +trading; it is safe to call again if approvals are already set. + +```diff theme={null} +-handle = await secure_client.setup_trading_approvals() +-await handle.wait() ++await secure_client.setup_trading_approvals() +``` + +**Gasless setup helpers are deprecated** + +You no longer need to call `is_gasless_ready()` or `setup_gasless_wallet()` in +the normal setup path. Create the secure client, then set up trading approvals. + +```diff theme={null} +-ready = await secure_client.is_gasless_ready() +- +-if not ready: +- secure_client = await secure_client.setup_gasless_wallet() +- + await secure_client.setup_trading_approvals() +``` + +### `0.1.0b1` + +First beta release of the unified Python SDK. Install the beta package with your +package manager: + +```bash theme={null} +uv add polymarket-client +``` diff --git a/PolymarketDocumentation-main/docs/dev-tooling/typescript.md b/PolymarketDocumentation-main/docs/dev-tooling/typescript.md new file mode 100644 index 00000000..e8934f8b --- /dev/null +++ b/PolymarketDocumentation-main/docs/dev-tooling/typescript.md @@ -0,0 +1,1237 @@ +> ## Documentation Index +> Fetch the complete documentation index at: https://docs.polymarket.com/llms.txt +> Use this file to discover all available pages before exploring further. + +# TypeScript SDK + +> Build with the unified Polymarket TypeScript SDK. + +The unified TypeScript SDK gives you a consistent surface across Polymarket discovery, market data, trading, account data, and realtime streams. + + + The TypeScript SDK is currently in beta. We are keeping it in this beta phase + while we address issues and harden the SDK before transitioning to a more + stable release. + + +## Quickstart + + + + Install the SDK from your package manager. + + + ```bash pnpm theme={null} + pnpm add @polymarket/client@beta + ``` + + ```bash npm theme={null} + npm install @polymarket/client@beta + ``` + + ```bash yarn theme={null} + yarn add @polymarket/client@beta + ``` + + + + + Create an instance of the `PublicClient`. + + ```ts theme={null} + import { createPublicClient } from "@polymarket/client"; + + const client = createPublicClient(); + ``` + + + + Fetch a page of markets to discover active trading opportunities. + + ```ts theme={null} + const markets = client.listMarkets({ + closed: false, + pageSize: 5, + }); + + const firstPage = await markets.firstPage(); + + for (const market of firstPage.items) { + // market: Market + } + ``` + + + +## SDK Patterns + +The SDK normalizes data across API seams and uses consistent patterns for pagination and typed error handling across public and authenticated workflows. + +### Typed Primitives + +Common primitives such as IDs, decimal values, date/time strings, and EVM addresses are represented with explicit SDK types so integrations can avoid treating every value as a plain string. + +```ts theme={null} +type Market = { + id: MarketId; + conditionId: ConditionId | null; + state: { + startDate?: IsoDateTimeString | null; + endDate?: IsoDateTimeString | null; + }; + outcomes: { + yes: { + tokenId: TokenId | null; + price: DecimalString | null; + }; + }; + resolution: { + resolvedBy: EvmAddress | null; + }; + // … +}; +``` + +### Market and Event Data + +Market and event responses use normalized field names and TypeScript shapes instead of service-specific response formats. + + + ```ts Market theme={null} + type Market = { + id: MarketId; + slug?: string | null; + conditionId: ConditionId | null; + question?: string | null; + description?: string | null; + category?: string | null; + image?: string | null; + icon?: string | null; + state: MarketState; + outcomes: MarketOutcomes; + metrics: MarketMetrics; + prices: MarketPrices; + trading: MarketTrading; + resolution: MarketResolution; + rewards: MarketRewards; + sports: MarketSportsMetadata; + tags: MarketTag[]; + // … + }; + ``` + + ```ts Event theme={null} + type Event = { + id: EventId; + slug?: string | null; + title?: string | null; + subtitle?: string | null; + description?: string | null; + category?: string | null; + subcategory?: string | null; + image?: string | null; + icon?: string | null; + createdAt?: IsoDateTimeString | null; + updatedAt?: IsoDateTimeString | null; + publishedAt?: IsoDateTimeString | null; + state: EventState; + schedule: EventSchedule; + metrics: EventMetrics; + trading: EventTrading; + estimation: EventEstimation; + sports: EventSportsMetadata; + partners: EventPartner[]; + markets: Market[]; + series: EventSeries[]; + // … + }; + ``` + + +### Pagination + +List methods return a consistent paginator interface across paginated endpoints. Use `for await` to iterate through pages. + +```ts theme={null} +const markets = client.listMarkets({ + closed: false, + pageSize: 10, +}); + +for await (const page of markets) { + // page.items: Market[] +} +``` + +You can also fetch the first page directly and resume later from a cursor. + +```ts theme={null} +const firstPage = await markets.firstPage(); +// firstPage.items: Market[] + +for await (const page of markets.from(firstPage.nextCursor)) { + // page.items: Market[] +} +``` + +### Error Handling + +Each public action exposes a matching error guard. Use it to handle expected SDK errors and rethrow anything unexpected. + + + Error guards make exhaustive checks easier and help surface newly added SDK + error cases during upgrades. + + +```ts theme={null} +import { ListMarketsError } from "@polymarket/client"; + +try { + const markets = client.listMarkets({ + closed: false, + pageSize: 10, + }); + + const firstPage = await markets.firstPage(); + // firstPage.items: Market[] +} catch (error) { + if (!ListMarketsError.isError(error)) { + throw error; + } + + switch (error.name) { + case "RateLimitError": + // Retry later. + break; + case "UserInputError": + // Fix the request parameters. + break; + default: + // … + } +} +``` + +## Market Data + +Use market data methods to fetch market and event details, order books, current prices, historical prices, and batch quotes. + + + ```ts Market theme={null} + const market = await client.fetchMarket({ + url: "https://polymarket.com/market/eth-flipped-in-2026", + }); + + const market = await client.fetchMarket({ + slug: "eth-flipped-in-2026", + }); + + const market = await client.fetchMarket({ + id: "12345", + }); + ``` + + ```ts Event theme={null} + const event = await client.fetchEvent({ + url: "https://polymarket.com/event/presidential-election-2028", + }); + + const event = await client.fetchEvent({ + slug: "presidential-election-2028", + }); + + const event = await client.fetchEvent({ + id: "12345", + }); + ``` + + +Then fetch related tags, order books, prices, and history. + + + ```ts Tags theme={null} + const marketTags = await client.fetchMarketTags({ + id: market.id, + }); + + const eventTags = await client.fetchEventTags({ + id: event.id, + }); + ``` + + ```ts Order Book theme={null} + const book = await client.fetchOrderBook({ + tokenId: market.outcomes.yes.tokenId!, + }); + ``` + + ```ts Prices theme={null} + import { OrderSide } from "@polymarket/client"; + + const buyPrice = await client.fetchPrice({ + tokenId: market.outcomes.yes.tokenId!, + side: OrderSide.BUY, + }); + + const midpoint = await client.fetchMidpoint({ + tokenId: market.outcomes.yes.tokenId!, + }); + + const spread = await client.fetchSpread({ + tokenId: market.outcomes.yes.tokenId!, + }); + + const lastTrade = await client.fetchLastTradePrice({ + tokenId: market.outcomes.yes.tokenId!, + }); + ``` + + ```ts History theme={null} + const history = await client.fetchPriceHistory({ + tokenId: market.outcomes.yes.tokenId!, + interval: "1d", + }); + ``` + + ```ts Batch Reads theme={null} + import { OrderSide } from "@polymarket/client"; + + const prices = await client.fetchPrices([ + { + tokenId: market.outcomes.yes.tokenId!, + side: OrderSide.BUY, + }, + { + tokenId: market.outcomes.no.tokenId!, + side: OrderSide.BUY, + }, + ]); + + const midpoints = await client.fetchMidpoints([ + { + tokenId: market.outcomes.yes.tokenId!, + }, + { + tokenId: market.outcomes.no.tokenId!, + }, + ]); + ``` + + +## Discovery + +Use discovery methods to browse events, markets, teams, tags, comments, sports metadata, and search results. The examples below show a few common entry points. + + + + ```ts theme={null} + const events = client.listEvents({ + pageSize: 10, + }); + + for await (const page of events) { + // page.items: Event[] + } + ``` + + + + ```ts theme={null} + const markets = client.listMarkets({ + closed: false, + pageSize: 10, + }); + + for await (const page of markets) { + // page.items: Market[] + } + ``` + + + + ```ts theme={null} + const teams = client.listTeams({ + league: ["NBA"], + pageSize: 10, + }); + + for await (const page of teams) { + // page.items: Team[] + } + ``` + + + + ```ts theme={null} + const tags = client.listTags({ + pageSize: 10, + }); + + for await (const page of tags) { + // page.items: Tag[] + } + + const tag = await client.fetchTag({ + slug: "politics", + }); + + const relatedTags = await client.fetchRelatedTags({ + slug: "politics", + }); + + const relatedResources = await client.fetchRelatedTagResources({ + slug: "politics", + status: "active", + }); + ``` + + + + ```ts theme={null} + const comments = client.listComments({ + parentEntityId: "12345", + parentEntityType: "Event", + pageSize: 20, + }); + + for await (const page of comments) { + // page.items: Comment[] + } + + const thread = await client.fetchCommentsById({ + id: "456", + getPositions: true, + }); + + const userComments = client.listCommentsByUserAddress({ + address: "0x1234…", + pageSize: 10, + order: "DESC", + }); + + for await (const page of userComments) { + // page.items: Comment[] + } + ``` + + + + ```ts theme={null} + const sports = await client.listSports(); + + // sports: SportsMetadata[] + ``` + + + + ```ts theme={null} + const results = client.search({ + q: "ethereum", + pageSize: 10, + }); + + for await (const page of results) { + // page.items.events: Event[] + // page.items.tags: SearchTag[] + // page.items.profiles: Profile[] + } + ``` + + + +## Realtime Streams + +Subscribe through one SDK interface even when events are served by different websocket surfaces. The SDK routes each subscription spec to the right stream and merges the results into one stream. + +```ts theme={null} +const stream = await client.subscribe([ + { + topic: "market", + tokenIds: [market.outcomes.yes.tokenId!], + }, + { + topic: "prices.crypto.binance", + symbols: ["btcusdt"], + }, +]); + +for await (const event of stream) { + // event: + // | MarketBookEvent + // | MarketPriceChangeEvent + // | MarketLastTradePriceEvent + // | MarketTickSizeChangeEvent + // | CryptoPricesBinanceEvent + + if (shouldStopStreaming()) { + await stream.close(); + } +} +``` + +## Authenticated Client + +Create a secure client when you need wallet-scoped reads or trading. + +By default, `createSecureClient` uses the signer's deterministic Deposit Wallet +as the account wallet. The SDK deploys that wallet if needed during client +creation. Pass `wallet` only when you want to authenticate an existing wallet, +such as an existing Deposit Wallet, Poly Safe, Poly Proxy, or the signer address +itself for EOA trading. + +The examples below pass `wallet` to make account selection explicit. Omit +`wallet` to use the default Deposit Wallet flow. + +### Wallet Integrations + +The SDK is intended to support a variety of wallet libraries. At launch, we support [Viem](https://viem.sh), [Privy](https://www.privy.io/docs), and [Ethers v5](https://docs.ethers.org/v5/). We will expand support for more libraries based on demand. + + + + + + Install the SDK and Viem wallet tools. + + ```bash theme={null} + pnpm add @polymarket/client@beta viem + ``` + + + + Use the private-key helper, or adapt an existing `viem` wallet client. + + + ```ts Private Key theme={null} + import { createSecureClient } from "@polymarket/client"; + import { privateKey } from "@polymarket/client/viem"; + + const secureClient = await createSecureClient({ + wallet: "YOUR_POLYMARKET_WALLET_ADDRESS", + signer: privateKey(process.env.PRIVATE_KEY), + }); + ``` + + ```ts Wallet Client theme={null} + import { createSecureClient } from "@polymarket/client"; + import { signerFrom } from "@polymarket/client/viem"; + import { createWalletClient, http } from "viem"; + import { privateKeyToAccount } from "viem/accounts"; + import { polygon } from "viem/chains"; + + const walletClient = createWalletClient({ + account: privateKeyToAccount(process.env.PRIVATE_KEY as `0x${string}`), + chain: polygon, + transport: http(), + }); + + const secureClient = await createSecureClient({ + wallet: "YOUR_POLYMARKET_WALLET_ADDRESS", + signer: signerFrom(walletClient), + }); + ``` + + + + + + + + + Install the SDK and Privy Node client. + + ```bash theme={null} + pnpm add @polymarket/client@beta @privy-io/node + ``` + + + + Use the Privy Node client with the SDK's Privy signer adapter. + + ```ts theme={null} + import { createSecureClient } from "@polymarket/client"; + import { signerFrom } from "@polymarket/client/privy"; + import { PrivyClient } from "@privy-io/node"; + + const privy = new PrivyClient({ + appId: process.env.PRIVY_APP_ID!, + appSecret: process.env.PRIVY_APP_SECRET!, + }); + + const secureClient = await createSecureClient({ + wallet: "YOUR_POLYMARKET_WALLET_ADDRESS", + signer: signerFrom({ + privy, + walletId: process.env.PRIVY_WALLET_ID!, + }), + }); + ``` + + + + + + + + Install the SDK and the Ethers v5 package alias used by the adapter. + + ```bash theme={null} + pnpm add @polymarket/client@beta ethers-v5@npm:ethers@^5.8.0 + ``` + + + + Use the Ethers v5 signer adapter when your integration already manages an `ethers.Signer`. + + ```ts theme={null} + import { createSecureClient } from "@polymarket/client"; + import { signerFrom } from "@polymarket/client/ethers-v5"; + import { ethers } from "ethers-v5"; + + const provider = new ethers.providers.JsonRpcProvider( + process.env.POLYGON_RPC_URL, + ); + const wallet = new ethers.Wallet(process.env.PRIVATE_KEY!, provider); + + const secureClient = await createSecureClient({ + wallet: "YOUR_POLYMARKET_WALLET_ADDRESS", + signer: signerFrom(wallet), + }); + ``` + + + + + +### Trading Setup + +Before placing orders, make sure the authenticated wallet is deployed and has +the required trading approvals. `createSecureClient` resolves the signer's +deterministic Deposit Wallet by default and deploys it if needed. + + + + Configure API key authorization when the SDK needs to deploy a Deposit Wallet or + submit approval transactions. + + + ```ts Relayer API Key theme={null} + import { createSecureClient, relayerApiKey } from "@polymarket/client"; + + const secureClient = await createSecureClient({ + wallet: "YOUR_POLYMARKET_WALLET_ADDRESS", + signer, + apiKey: relayerApiKey({ + key: process.env.RELAYER_API_KEY!, + address: process.env.RELAYER_API_KEY_ADDRESS!, + }), + }); + ``` + + ```ts Builder API Key theme={null} + import { createSecureClient } from "@polymarket/client"; + import { builderApiKey } from "@polymarket/client/node"; + + const secureClient = await createSecureClient({ + wallet: "YOUR_POLYMARKET_WALLET_ADDRESS", + signer, + apiKey: builderApiKey({ + key: process.env.BUILDER_API_KEY!, + secret: process.env.BUILDER_SECRET!, + passphrase: process.env.BUILDER_PASSPHRASE!, + }), + }); + ``` + + + + Builder API keys are supported for backwards compatibility with builders that + still use them for wallet operations. They are not used for order attribution. + Use `builderCode` on orders for attribution. + + + + + Then set up trading approvals. + + ```ts theme={null} + await secureClient.setupTradingApprovals(); + ``` + + `setupTradingApprovals()` waits for the setup transaction internally and is + idempotent. If the wallet already has the required approvals, it returns without + submitting a transaction. + + + +### Trading + +Use a secure client to create, sign, and submit orders. Limit orders specify the price and size you want to trade. Market orders execute against resting liquidity immediately. + +Order placement returns a discriminated response. Check `response.ok` before reading order details. + +#### Place Orders + + + + ```ts theme={null} + import { OrderSide } from "@polymarket/client"; + + const response = await secureClient.placeLimitOrder({ + tokenId: market.outcomes.yes.tokenId!, + side: OrderSide.BUY, + price: 0.52, + size: 10, + }); + + if (response.ok) { + // response.orderId: string + } else { + // response.code: OrderResponseErrorCode + // response.message: string + } + ``` + + + + ```ts theme={null} + import { OrderSide } from "@polymarket/client"; + + const response = await secureClient.placeLimitOrder({ + tokenId: market.outcomes.yes.tokenId!, + side: OrderSide.SELL, + price: 0.52, + size: 10, + expiration: Math.floor(Date.now() / 1000) + 60 * 60, + }); + + if (response.ok) { + // response.orderId: string + } else { + // response.code: OrderResponseErrorCode + // response.message: string + } + ``` + + + + ```ts theme={null} + import { OrderSide, OrderType } from "@polymarket/client"; + + const response = await secureClient.placeMarketOrder({ + tokenId: market.outcomes.yes.tokenId!, + side: OrderSide.BUY, + amount: 10, + maxSpend: 11, + orderType: OrderType.FAK, + }); + + if (response.ok) { + // response.orderId: string + } else { + // response.code: OrderResponseErrorCode + // response.message: string + } + ``` + + + + ```ts theme={null} + import { OrderSide, OrderType } from "@polymarket/client"; + + const response = await secureClient.placeMarketOrder({ + tokenId: market.outcomes.yes.tokenId!, + side: OrderSide.SELL, + shares: 10, + orderType: OrderType.FOK, + }); + + if (response.ok) { + // response.orderId: string + } else { + // response.code: OrderResponseErrorCode + // response.message: string + } + ``` + + + + ```ts theme={null} + import { OrderSide } from "@polymarket/client"; + + const response = await secureClient.placeLimitOrder({ + tokenId: market.outcomes.yes.tokenId!, + side: OrderSide.BUY, + price: 0.52, + size: 10, + builderCode: "0xabc123…", + }); + + if (response.ok) { + // response.orderId: string + } else { + // response.code: OrderResponseErrorCode + // response.message: string + } + ``` + + + +#### Create, Then Post + +Create signed orders separately when you want to review, store, or batch them before submitting. + + + + ```ts theme={null} + import { OrderSide } from "@polymarket/client"; + + const order = await secureClient.createLimitOrder({ + tokenId: market.outcomes.yes.tokenId!, + side: OrderSide.BUY, + price: 0.52, + size: 10, + }); + + const response = await secureClient.postOrder(order); + + if (response.ok) { + // response.orderId: string + } else { + // response.code: OrderResponseErrorCode + // response.message: string + } + ``` + + + + ```ts theme={null} + import { OrderSide } from "@polymarket/client"; + + const firstOrder = await secureClient.createLimitOrder({ + tokenId: market.outcomes.yes.tokenId!, + side: OrderSide.BUY, + price: 0.52, + size: 10, + }); + + const secondOrder = await secureClient.createLimitOrder({ + tokenId: market.outcomes.yes.tokenId!, + side: OrderSide.SELL, + price: 0.58, + size: 5, + }); + + const responses = await secureClient.postOrders([firstOrder, secondOrder]); + + for (const response of responses) { + if (response.ok) { + // response.orderId: string + } else { + // response.code: OrderResponseErrorCode + // response.message: string + } + } + ``` + + + +### Position Lifecycle + +Use position lifecycle methods to split collateral into outcome tokens, merge +complete sets back into collateral, or redeem resolved positions. These examples +assume you created a secure client and set up trading approvals as shown above. + + + + ```ts theme={null} + const handle = await secureClient.splitPosition({ + conditionId: market.conditionId!, + amount: 1n, + }); + + const outcome = await handle.wait(); + + // outcome.transactionHash: TxHash + ``` + + + + ```ts theme={null} + const handle = await secureClient.mergePositions({ + conditionId: market.conditionId!, + amount: "max", + }); + + const outcome = await handle.wait(); + + // outcome.transactionHash: TxHash + ``` + + + + ```ts theme={null} + const handle = await secureClient.redeemPositions({ + marketId: market.id, + }); + + const outcome = await handle.wait(); + + // outcome.transactionHash: TxHash + ``` + + + +### Wallet Operations + +Use wallet operation methods for direct token movements from the authenticated +wallet. These examples assume you created a secure client as shown above. + +```ts theme={null} +const handle = await secureClient.transferErc20({ + amount: 1n, + recipientAddress: "RECIPIENT_ADDRESS", + tokenAddress: secureClient.environment.collateralToken, +}); + +const outcome = await handle.wait(); + +// outcome.transactionHash: TxHash +``` + +### Order Management + +Manage open orders for the authenticated wallet after placement. These examples assume `orderId` comes from an accepted order response. + + + + ```ts theme={null} + const order = await secureClient.fetchOrder({ + orderId, + }); + + // order: OpenOrder + ``` + + + + ```ts theme={null} + const openOrders = secureClient.listOpenOrders({ + market: market.id, // Or market.conditionId + }); + + for await (const page of openOrders) { + // page.items: OpenOrder[] + } + ``` + + + + ```ts theme={null} + const response = await secureClient.cancelOrder({ + orderId, + }); + + // response.canceled: string[] + ``` + + + + ```ts theme={null} + const response = await secureClient.cancelMarketOrders({ + tokenId: market.outcomes.yes.tokenId!, + }); + + // response.canceled: string[] + ``` + + + +### Rewards and Scoring + +Use rewards methods to inspect active reward programs and scoring methods to check whether orders are eligible for scoring. + + + + ```ts theme={null} + const rewards = client.listCurrentRewards(); + + for await (const page of rewards) { + // page.items: CurrentReward[] + } + ``` + + + + ```ts theme={null} + const rewards = client.listMarketRewards({ + conditionId: market.conditionId!, + }); + + for await (const page of rewards) { + // page.items: MarketReward[] + } + ``` + + + + ```ts theme={null} + const scoring = await secureClient.fetchOrderScoring({ + orderId, + }); + + // scoring: boolean + ``` + + + + ```ts theme={null} + const scoring = await secureClient.fetchOrdersScoring({ + orderIds: [firstOrderId, secondOrderId], + }); + + // scoring: OrdersScoringResponse + ``` + + + +### Account Data + +Secure clients can read account-scoped data for the authenticated wallet. + + + + ```ts theme={null} + const positions = secureClient.listPositions({ + market: [market.id], // Or market.conditionId + pageSize: 10, + }); + + for await (const page of positions) { + // page.items: Position[] + } + ``` + + + + ```ts theme={null} + const value = await secureClient.fetchPortfolioValue({ + market: [market.id], // Or market.conditionId + }); + + // value: Value[] + ``` + + + + ```ts theme={null} + import { ActivityType } from "@polymarket/client"; + + const activity = secureClient.listActivity({ + market: [market.id], // Or market.conditionId + pageSize: 10, + }); + + for await (const page of activity) { + for (const item of page.items) { + switch (item.type) { + case ActivityType.TRADE: + // item.tokenId: TokenId + // item.shares: DecimalString + break; + case ActivityType.REWARD: + // item.amount: DecimalString + break; + default: + // … + } + } + } + ``` + + + + ```ts theme={null} + const yesTokenId = market.outcomes.yes.tokenId!; + + const trades = secureClient.listAccountTrades({ + tokenId: yesTokenId, + }); + + for await (const page of trades) { + // page.items: ClobTrade[] + } + ``` + + + + ```ts theme={null} + const notifications = await secureClient.fetchNotifications(); + + // notifications: Notification[] + ``` + + + +### Authentication Sessions + +Secure clients expose the API credentials created for the authenticated session. Store them securely if you want to reuse the session later without requiring a new authentication signature while the credentials remain valid. + + + + ```ts theme={null} + const secureClient = await createSecureClient({ + wallet: "YOUR_POLYMARKET_WALLET_ADDRESS", + signer, + }); + + await storage.set("polymarketCredentials", secureClient.credentials); + ``` + + + + ```ts theme={null} + const credentials = await storage.get("polymarketCredentials"); + + const secureClient = await createSecureClient({ + wallet: "YOUR_POLYMARKET_WALLET_ADDRESS", + signer, + credentials, + }); + ``` + + + +## Changelog + +### `0.1.0-beta.14` + +* Added SDK pagination for Combo lifecycle activity and server-cursor pagination for Combo positions. +* Added Combo position sync request fields and exposed `outcome` and `redeemable` on Combo positions. +* Branded Combo activity row IDs. +* Breaking beta change: Combo activity and position fields now use `wallet`, `amount`, and `payout`; Combo activity rows no longer expose `moduleKind`. + +```diff theme={null} +-activity.userAddress +-activity.amountUsdc +-redeemActivity.payoutUsdc +-position.userAddress ++activity.wallet ++activity.amount ++redeemActivity.payout ++position.wallet +``` + +### `0.1.0-beta.13` + +* Added `listMarketClarifications` for reading market clarification text with SDK-owned pagination and market, event, state, question, and transaction filters. +* Fixed legacy Proxy wallet gasless execution and added live Safe and Proxy wallet coverage. +* Resolve closed markets when preparing market position redemptions. +* Gasless transaction handles now wait for relayer transactions to reach confirmed state before resolving. + +### `0.1.0-beta.12` + +* Require GTD limit order expirations to be at least 3 minutes in the future. + +### `0.1.0-beta.11` + +* Support CLOB order tick sizes `0.005` and `0.0025`. +* Pagination request cursors now infer the branded pagination cursor type. + +### `0.1.0-beta.10` + +* Preserve already-deployed legacy UUPS Deposit Wallets when `createSecureClient` resolves the default wallet, while new Deposit Wallet deployments use the beacon factory path. + +### `0.1.0-beta.9` + +* Added `PriceHistoryInterval` and `SearchSort` exports, preserved `groupItemTitle` on normalized markets, and published `expectPrivateKey` from `@polymarket/types`. + +### `0.1.0-beta.8` + +* RFQ quoter sessions now emit typed `trade` events for confirmed Combos fills. +* RFQ rejection errors now expose `errorId` values and parse `INVALID_SIGNATURE` and `INTERNAL_ERROR` codes. + +### `0.1.0-beta.7` + +* Added `parentEventId` to `Event` so child events can link back to their parent event. +* Added `maxPrice` and `minPrice` protection fields to market order requests. +* Handle legacy multi-outcome markets more safely: `listMarkets` skips markets that cannot be represented by the binary market model, and `fetchMarket` returns a typed SDK error for unsupported markets. +* Normalize empty-string order and activity fields to SDK values: decimal amounts become `"0"`, missing maker order fee rates become `null`, and missing trade or position market icons become `null`. +* Parse Combo trade activity rows with an `isCombo` discriminated union. +* Support new Combos RFQ websocket error codes for balance, allowance, and pre-execution reservation failures. +* Broad user websocket subscriptions now omit market filters so all-market streams receive trade events. +* Retry rejected JSON-RPC `eth_call` batches by splitting them into smaller batches. + +### `0.1.0-beta.6` + +* Point Combos RFQ endpoints at the production domains: `combos-rfq-api.polymarket.com` (REST) and `combos-rfq-gateway-quoter.polymarket.com` (quoter WebSocket). + +### `0.1.0-beta.5` + +* Added `listComboMarkets` for fetching the Combo market catalog with typed bindings and SDK-owned pagination. See [Combos](/market-makers/combos). +* Parse RFQ quote rejections that use the `SUBMISSION_WINDOW_CLOSED` gateway error code. + +### `0.1.0-beta.4` + +* Added Combos support for multi-leg RFQ positions. See [Combos](/market-makers/combos). +* Reject whitespace-only search queries and trim leading or trailing search input. +* `ConditionId` is now deprecated in favor of `CtfConditionId`; existing + `ConditionId` exports remain available as deprecated aliases. + +### `0.1.0-beta.3` + +**Secure client setup now defaults to the Deposit Wallet flow** + +`createSecureClient` can now derive and use the signer's deterministic Deposit +Wallet when you omit `wallet`. If you already know which Polymarket wallet you +want to use, keep passing `wallet`. + +```diff theme={null} +const secureClient = await createSecureClient({ +- wallet: "YOUR_POLYMARKET_WALLET_ADDRESS", + signer, +}); +``` + +If you want to keep account selection explicit, no change is required: + +```ts theme={null} +const secureClient = await createSecureClient({ + wallet: "YOUR_POLYMARKET_WALLET_ADDRESS", + signer, +}); +``` + +**`setupTradingApprovals()` now waits internally** + +You no longer need to wait on the returned handle. Call the method once before +trading; it is safe to call again if approvals are already set. + +```diff theme={null} +-const handle = await secureClient.setupTradingApprovals(); +-await handle.wait(); ++await secureClient.setupTradingApprovals(); +``` + +**Gasless setup helpers are deprecated** + +You no longer need to call `isGaslessReady()` or `setupGaslessWallet()` in the +normal setup path. Create the secure client, then set up trading approvals. + +```diff theme={null} +-const ready = await secureClient.isGaslessReady(); +- +-if (!ready) { +- secureClient = await secureClient.setupGaslessWallet(); +-} +- + await secureClient.setupTradingApprovals(); +``` + +### `0.1.0-beta.2` + +First beta release of the unified TypeScript SDK. Install the beta package with +your package manager: + +```bash theme={null} +pnpm add @polymarket/client@beta +``` diff --git a/PolymarketDocumentation-main/docs/developers/CLOB/authentication.md b/PolymarketDocumentation-main/docs/developers/CLOB/authentication.md new file mode 100644 index 00000000..d099fd75 --- /dev/null +++ b/PolymarketDocumentation-main/docs/developers/CLOB/authentication.md @@ -0,0 +1,437 @@ +> ## Documentation Index +> Fetch the complete documentation index at: https://docs.polymarket.com/llms.txt +> Use this file to discover all available pages before exploring further. + +# Authentication + +> How to authenticate requests to the CLOB API + +The CLOB API uses two levels of authentication: **L1 (Private Key)** and **L2 (API Key)**. Either can be accomplished using the CLOB client or REST API. + +## Public vs Authenticated + + + + The **Gamma API**, **Data API**, and CLOB read endpoints (orderbook, prices, spreads) require no authentication. + + + + CLOB trading endpoints (placing orders, cancellations, heartbeat) require all 5 `POLY_*` L2 HTTP headers. + + + +*** + +## Two-Level Authentication Model + +The CLOB uses two levels of authentication: L1 (Private Key) and L2 (API Key). Either can be accomplished using the CLOB client or REST API + +### L1 Authentication + +L1 authentication uses the wallet's private key to sign an EIP-712 message used in the request header. It proves ownership and control over the private key. The private key stays in control of the user and all trading activity remains non-custodial. + +**Used for:** + +* Creating API credentials +* Deriving existing API credentials +* Signing and creating user's orders locally + +### L2 Authentication + +L2 uses API credentials (apiKey, secret, passphrase) generated from L1 authentication. These are used solely to authenticate requests made to the CLOB API. Requests are signed using HMAC-SHA256. + +**Used for:** + +* Cancel or get user's open orders +* Check user's balances and allowances +* Post user's signed orders + + + Even with L2 authentication headers, methods that create user orders still + require the user to sign the order payload. + + +*** + +## Getting API Credentials + +Before making authenticated requests, you need to obtain API credentials using L1 authentication. + +### Using the SDK + + + + ```typescript theme={null} + import { ClobClient } from "@polymarket/clob-client-v2"; + import { createWalletClient, http } from "viem"; + import { privateKeyToAccount } from "viem/accounts"; + + const account = privateKeyToAccount(process.env.PRIVATE_KEY as `0x${string}`); + const signer = createWalletClient({ account, transport: http() }); + + const client = new ClobClient({ + host: "https://clob.polymarket.com", + chain: 137, // Polygon mainnet + signer, + }); + + // Creates new credentials or derives existing ones + const credentials = await client.createOrDeriveApiKey(); + + console.log(credentials); + // { + // key: "550e8400-e29b-41d4-a716-446655440000", + // secret: "base64EncodedSecretString", + // passphrase: "randomPassphraseString" + // } + ``` + + + + ```python theme={null} + from py_clob_client_v2 import ClobClient + import os + + client = ClobClient( + host="https://clob.polymarket.com", + chain_id=137, # Polygon mainnet + key=os.getenv("PRIVATE_KEY") + ) + + # Creates new credentials or derives existing ones + credentials = client.create_or_derive_api_key() + + print(credentials) + # { + # "apiKey": "550e8400-e29b-41d4-a716-446655440000", + # "secret": "base64EncodedSecretString", + # "passphrase": "randomPassphraseString" + # } + ``` + + + + ```rust theme={null} + use std::str::FromStr; + use polymarket_client_sdk_v2::POLYGON; + use polymarket_client_sdk_v2::auth::{LocalSigner, Signer}; + use polymarket_client_sdk_v2::clob::{Client, Config}; + + let private_key = std::env::var("POLYMARKET_PRIVATE_KEY")?; + let signer = LocalSigner::from_str(&private_key)? + .with_chain_id(Some(POLYGON)); + + // Creates new credentials or derives existing ones, + // then initializes the authenticated client — all in one step + let client = Client::new("https://clob.polymarket.com", Config::default())? + .authentication_builder(&signer) + .authenticate() + .await?; + + let credentials = client.credentials(); + println!("API Key: {}", credentials.key()); + ``` + + + + + **Never commit private keys to version control.** Always use environment + variables or secure key management systems. + + +### Using the REST API + +While we highly recommend using our provided clients to handle signing and authentication, the following is for developers who choose NOT to use our [Python](https://github.com/Polymarket/py-clob-client-v2) or [TypeScript](https://github.com/Polymarket/clob-client-v2) clients. + +**Create API Credentials** + +```bash theme={null} +POST https://clob.polymarket.com/auth/api-key +``` + +**Derive API Credentials** + +```bash theme={null} +GET https://clob.polymarket.com/auth/derive-api-key +``` + +Required L1 headers: + +| Header | Description | +| ---------------- | ---------------------- | +| `POLY_ADDRESS` | Polygon signer address | +| `POLY_SIGNATURE` | CLOB EIP-712 signature | +| `POLY_TIMESTAMP` | Current UNIX timestamp | +| `POLY_NONCE` | Nonce (default: 0) | + +The `POLY_SIGNATURE` is generated by signing the following EIP-712 struct: + + + + ```typescript TypeScript theme={null} + const domain = { + name: "ClobAuthDomain", + version: "1", + chainId: chainId, // Polygon Chain ID 137 + }; + + const types = { + ClobAuth: [ + { name: "address", type: "address" }, + { name: "timestamp", type: "string" }, + { name: "nonce", type: "uint256" }, + { name: "message", type: "string" }, + ], + }; + + const value = { + address: signingAddress, // The Signing address + timestamp: ts, // The CLOB API server timestamp + nonce: nonce, // The nonce used + message: "This message attests that I control the given wallet", + }; + + const sig = await signer._signTypedData(domain, types, value); + ``` + + ```python Python theme={null} + domain = { + "name": "ClobAuthDomain", + "version": "1", + "chainId": chainId, # Polygon Chain ID 137 + } + + types = { + "ClobAuth": [ + {"name": "address", "type": "address"}, + {"name": "timestamp", "type": "string"}, + {"name": "nonce", "type": "uint256"}, + {"name": "message", "type": "string"}, + ] + } + + value = { + "address": signingAddress, # The signing address + "timestamp": ts, # The CLOB API server timestamp + "nonce": nonce, # The nonce used + "message": "This message attests that I control the given wallet", + } + + sig = signer.sign_typed_data(domain, types, value) + ``` + + + +Reference implementations: + +* [TypeScript](https://github.com/Polymarket/clob-client-v2/blob/main/src/signing/eip712.ts) +* [Python](https://github.com/Polymarket/py-clob-client-v2/blob/main/py_clob_client_v2/signing/eip712.py) + +Response: + +```json theme={null} +{ + "apiKey": "550e8400-e29b-41d4-a716-446655440000", + "secret": "base64EncodedSecretString", + "passphrase": "randomPassphraseString" +} +``` + +**You'll need all three values for L2 authentication.** + +*** + +## L2 Authentication Headers + +All trading endpoints require these 5 headers: + +| Header | Description | +| ----------------- | ----------------------------- | +| `POLY_ADDRESS` | Polygon signer address | +| `POLY_SIGNATURE` | HMAC signature for request | +| `POLY_TIMESTAMP` | Current UNIX timestamp | +| `POLY_API_KEY` | User's API `apiKey` value | +| `POLY_PASSPHRASE` | User's API `passphrase` value | + +The `POLY_SIGNATURE` for L2 is an HMAC-SHA256 signature created using the user's API credentials `secret` value. Reference implementations can be found in the [TypeScript](https://github.com/Polymarket/clob-client-v2/blob/main/src/signing/hmac.ts) and [Python](https://github.com/Polymarket/py-clob-client-v2/blob/main/py_clob_client_v2/signing/hmac.py) clients. + +### CLOB Client + + + + ```typescript theme={null} + import { ClobClient, Side } from "@polymarket/clob-client-v2"; + import { createWalletClient, http } from "viem"; + import { privateKeyToAccount } from "viem/accounts"; + + const account = privateKeyToAccount(process.env.PRIVATE_KEY as `0x${string}`); + const signer = createWalletClient({ account, transport: http() }); + const depositWalletAddress = process.env.DEPOSIT_WALLET_ADDRESS!; + + const client = new ClobClient({ + host: "https://clob.polymarket.com", + chain: 137, + signer, + creds: apiCreds, // Generated from L1 auth, API credentials enable L2 methods + signatureType: 3, // POLY_1271, explained below + funderAddress: depositWalletAddress, // deposit wallet funder + }); + + // Now you can trade! + const order = await client.createAndPostOrder( + { tokenID: "123456", price: 0.65, size: 100, side: Side.BUY }, + { tickSize: "0.01", negRisk: false } + ); + ``` + + + + ```python theme={null} + from py_clob_client_v2 import ClobClient, OrderArgs, PartialCreateOrderOptions + from py_clob_client_v2.order_builder.constants import BUY + import os + + client = ClobClient( + host="https://clob.polymarket.com", + chain_id=137, + key=os.getenv("PRIVATE_KEY"), + creds=api_creds, # Generated from L1 auth, API credentials enable L2 methods + signature_type=3, # POLY_1271, explained below + funder=os.getenv("DEPOSIT_WALLET_ADDRESS") + ) + + # Now you can trade! + order = client.create_and_post_order( + OrderArgs(token_id="123456", price=0.65, size=100, side=BUY), + options=PartialCreateOrderOptions(tick_size="0.01", neg_risk=False), + ) + ``` + + + + ```rust theme={null} + use polymarket_client_sdk_v2::clob::types::{Side, SignatureType}; + use polymarket_client_sdk_v2::types::dec; + + let deposit_wallet = std::env::var("DEPOSIT_WALLET_ADDRESS")?.parse()?; + + let client = Client::new("https://clob.polymarket.com", Config::default())? + .authentication_builder(&signer) + .funder(deposit_wallet) + .signature_type(SignatureType::Poly1271) + .authenticate() + .await?; + + // Now you can trade! + let order = client.limit_order() + .token_id("123456".parse()?) + .price(dec!(0.65)) + .size(dec!(100)) + .side(Side::Buy) + .build().await?; + let signed = client.sign(&signer, order).await?; + let response = client.post_order(signed).await?; + ``` + + + + + Even with L2 authentication headers, methods that create user orders still + require the user to sign the order payload. + + +*** + +## Signature Types and Funder + +When initializing the L2 client, you must specify your wallet **signatureType** and the **funder** address which holds the funds: + +| Signature Type | Value | Description | +| -------------- | ----- | -------------------------------------------------------------------------------------------------------------------------- | +| EOA | `0` | Standard Ethereum wallet (MetaMask). Funder is the EOA address and will need POL to pay gas on transactions. | +| POLY\_PROXY | `1` | Existing Polymarket proxy wallet flow, commonly used by users who logged in via Magic Link email/Google. | +| GNOSIS\_SAFE | `2` | Existing Gnosis Safe wallet flow. Existing Safe users can continue using this type. | +| POLY\_1271 | `3` | Deposit wallet flow for new API users. The funder is the deposit wallet address and orders are validated through ERC-1271. | + + + New API users should use deposit wallets with `POLY_1271`. Existing Safe and + Proxy users are unaffected and can keep using their current funder address and + signature type. See the [Deposit Wallet Guide](/trading/deposit-wallets) for + setup details. + + +*** + +## Security Best Practices + + + + Store private keys in environment variables or secure key management systems. Never commit them to version control. + + ```bash theme={null} + # .env (never commit this file) + PRIVATE_KEY=0x... + ``` + + + + Never expose your API secret in client-side code. All authenticated requests should originate from your backend. + + + +*** + +## Troubleshooting + + + + Your wallet's private key is incorrect or improperly formatted. + + **Solutions:** + + * Verify your private key is a valid hex string (starts with "0x") + * Ensure you're using the correct key for the intended address + * Check that the key has proper permissions + + + + The nonce you provided has already been used to create an API key. + + **Solutions:** + + * Use `deriveApiKey()` with the same nonce to retrieve existing credentials + * Or use a different nonce with `createApiKey()` + + + + Your funder address is incorrect or doesn't match your wallet. + + **Solution:** Check your Polymarket profile address at [polymarket.com/settings](https://polymarket.com/settings). + + If it does not exist or user has never logged into Polymarket.com, deploy it first before creating L2 authentication. + + + + Unfortunately, there's no way to recover lost API credentials without the nonce. You'll need to create new credentials: + + ```typescript theme={null} + // Create fresh credentials with a new nonce + const newCreds = await client.createApiKey(); + // Save the nonce this time! + ``` + + + +*** + +## Next Steps + + + + Learn how to create and submit orders. + + + + Check trading availability by region. + + diff --git a/PolymarketDocumentation-main/docs/developers/CLOB/clients/methods-builder.md b/PolymarketDocumentation-main/docs/developers/CLOB/clients/methods-builder.md new file mode 100644 index 00000000..384010bf --- /dev/null +++ b/PolymarketDocumentation-main/docs/developers/CLOB/clients/methods-builder.md @@ -0,0 +1,305 @@ +> ## Documentation Index +> Fetch the complete documentation index at: https://docs.polymarket.com/llms.txt +> Use this file to discover all available pages before exploring further. + +# Builder Methods + +> Methods for querying orders and trades attributed to your builder code. + +## Overview + +Builder attribution in V2 is handled natively through the order struct — you attach your **builder code** (a `bytes32` identifier from your [Builder Profile](https://polymarket.com/settings?tab=builder)) to every order you submit. No separate client configuration is required. + + + ```typescript TypeScript theme={null} + import { ClobClient } from "@polymarket/clob-client-v2"; + + const client = new ClobClient({ + host: "https://clob.polymarket.com", + chain: 137, + signer, + creds: apiCreds, + signatureType, + funderAddress, + }); + + // Attach your builder code on every order + const response = await client.createAndPostOrder( + { + tokenID: "0x...", + price: 0.55, + size: 100, + side: Side.BUY, + builderCode: process.env.POLY_BUILDER_CODE!, + }, + { tickSize: "0.01", negRisk: false }, + ); + ``` + + ```python Python theme={null} + from py_clob_client_v2 import ClobClient + from py_clob_client_v2 import OrderArgs, PartialCreateOrderOptions + from py_clob_client_v2.order_builder.constants import BUY + import os + + client = ClobClient( + host="https://clob.polymarket.com", + chain_id=137, + key=os.getenv("PRIVATE_KEY"), + creds=creds, + signature_type=signature_type, + funder=funder, + ) + + # Attach your builder code on every order + response = client.create_and_post_order( + OrderArgs( + token_id="0x...", + price=0.55, + size=100, + side=BUY, + builder_code=os.environ["POLY_BUILDER_CODE"], + ), + options=PartialCreateOrderOptions(tick_size="0.01", neg_risk=False), + ) + ``` + + + + See [Order Attribution](/trading/orders/attribution) for the full attribution flow. + + +*** + +## Methods + +*** + +### getOrder + +Get details for a specific order by ID. + +```typescript Signature theme={null} +async getOrder(orderID: string): Promise +``` + + + ```typescript TypeScript theme={null} + const order = await client.getOrder("0xb816482a..."); + console.log(order); + ``` + + ```python Python theme={null} + order = client.get_order("0xb816482a...") + print(order) + ``` + + +*** + +### getOpenOrders + +Get all open orders attributed to your builder code. + +```typescript Signature theme={null} +async getOpenOrders( + params?: OpenOrderParams, + only_first_page?: boolean, +): Promise +``` + +**Params** + + + Optional. Filter by order ID. + + + + Optional. Filter by market condition ID. + + + + Optional. Filter by token ID. + + +```typescript TypeScript theme={null} +// All open orders for this builder +const orders = await client.getOpenOrders(); + +// Filtered by market +const marketOrders = await client.getOpenOrders({ + market: "0xbd31dc8a...", +}); +``` + +*** + +### getBuilderTrades + +Retrieves all trades attributed to your builder code. Use this to track which trades were routed through your platform. + +```typescript Signature theme={null} +async getBuilderTrades( + params?: TradeParams, +): Promise +``` + +**Params (`TradeParams`)** + + + Optional. Filter trades by trade ID. + + + + Optional. Filter trades by maker address. + + + + Optional. Filter trades by market condition ID. + + + + Optional. Filter trades by asset (token) ID. + + + + Optional. Return trades created before this cursor value. + + + + Optional. Return trades created after this cursor value. + + +**Response (`BuilderTradesPaginatedResponse`)** + + + Array of trades attributed to the builder account. + + + + Cursor string for fetching the next page of results. + + + + Maximum number of trades returned per page. + + + + Total number of trades returned in this response. + + +**`BuilderTrade` fields** + + + Unique identifier for the trade. + + + + Type of the trade. + + + + Hash of the taker order associated with this trade. + + + + Builder code attributed to this trade. + + + + Condition ID of the market this trade belongs to. + + + + Token ID of the asset traded. + + + + Side of the trade (e.g. BUY or SELL). + + + + Size of the trade in shares. + + + + Size of the trade denominated in USDC. + + + + Price at which the trade was executed. + + + + Current status of the trade. + + + + Outcome label associated with the traded asset. + + + + Index of the outcome within the market. + + + + Address of the order owner (taker). + + + + Address of the maker in the trade. + + + + On-chain transaction hash for the trade. + + + + Timestamp when the trade was matched. + + + + Bucket index used for trade grouping. + + + + Fee charged for the trade in shares. + + + + Fee charged for the trade denominated in USDC. + + + + Optional. Error message if the trade encountered an issue, otherwise null. + + + + Timestamp when the trade record was created, or null if unavailable. + + + + Timestamp when the trade record was last updated, or null if unavailable. + + +*** + +## See Also + + + + Learn about the Builders Program and its benefits. + + + + Attach your builder code to orders for volume credit. + + + + Place and manage orders with API credentials. + + + + Execute onchain operations without paying gas. + + diff --git a/PolymarketDocumentation-main/docs/developers/CLOB/clients/methods-l1.md b/PolymarketDocumentation-main/docs/developers/CLOB/clients/methods-l1.md new file mode 100644 index 00000000..2b866b34 --- /dev/null +++ b/PolymarketDocumentation-main/docs/developers/CLOB/clients/methods-l1.md @@ -0,0 +1,403 @@ +> ## Documentation Index +> Fetch the complete documentation index at: https://docs.polymarket.com/llms.txt +> Use this file to discover all available pages before exploring further. + +# L1 Methods + +> These methods require a wallet signer (private key) but do not require user API credentials. Use these for initial setup. + +## Client Initialization + +L1 methods require the client to initialize with a signer. + + + + ```typescript theme={null} + import { ClobClient } from "@polymarket/clob-client-v2"; + import { createWalletClient, http } from "viem"; + import { privateKeyToAccount } from "viem/accounts"; + + const account = privateKeyToAccount(process.env.PRIVATE_KEY as `0x${string}`); + const signer = createWalletClient({ account, transport: http() }); + + const client = new ClobClient({ + host: "https://clob.polymarket.com", + chain: 137, + signer, // Signer required for L1 methods + }); + + // Ready to create user API credentials + const apiKey = await client.createApiKey(); + ``` + + + + ```python theme={null} + from py_clob_client_v2 import ClobClient + import os + + private_key = os.getenv("PRIVATE_KEY") + + client = ClobClient( + host="https://clob.polymarket.com", + chain_id=137, + key=private_key # Signer required for L1 methods + ) + + # Ready to create user API credentials + api_key = client.create_api_key() + ``` + + + + + Never commit private keys to version control. Always use environment variables + or a secure key management system. + + +*** + +## API Key Management + +*** + +### createApiKey + +Creates a new API key (L2 credentials) for the wallet signer. + +```typescript Signature theme={null} +async createApiKey(nonce?: number): Promise +``` + + + Optional custom nonce for deterministic key generation. Optional. + + + + The generated API key string. + + + + The secret associated with the API key. + + + + The passphrase associated with the API key. + + +*** + +### deriveApiKey + +Derives an existing API key using a specific nonce. If you've already created credentials with a particular nonce, this returns the same credentials. + +```typescript Signature theme={null} +async deriveApiKey(nonce?: number): Promise +``` + + + The nonce used when originally creating the key. Optional. + + + + The derived API key string. + + + + The secret associated with the API key. + + + + The passphrase associated with the API key. + + +*** + +### createOrDeriveApiKey + +Convenience method that attempts to derive an API key with the default nonce, or creates a new one if it doesn't exist. **Recommended for initial setup.** + +```typescript Signature theme={null} +async createOrDeriveApiKey(nonce?: number): Promise +``` + + + The API key string, either derived or newly created. + + + + The secret associated with the API key. + + + + The passphrase associated with the API key. + + +*** + +## Order Signing + + + In CLOB V2, `expiration` is still accepted in order payloads for GTD/order + expiry handling, but it is not part of the EIP-712 signed order struct. The + signed struct uses `timestamp`, `metadata`, and `builder` instead of the V1 + `expiration`, `nonce`, `feeRateBps`, and `taker` fields. + + +### createOrder + +Create and sign a limit order locally without posting it to the CLOB. Use this when you want to sign orders in advance or implement custom submission logic. Submit via [`postOrder()`](/trading/clients/l2#postorder) or [`postOrders()`](/trading/clients/l2#postorders). + +```typescript Signature theme={null} +async createOrder( + userOrder: UserOrder, + options?: Partial +): Promise +``` + + + The token ID of the market outcome to trade. + + + + The limit price for the order. + + + + The size (number of shares) for the order. + + + + The side of the order (buy or sell). + + + + Optional expiration timestamp included in the order payload for GTD/order + expiry handling. This is not part of the CLOB V2 EIP-712 signed order struct. + + + + The tick size used for order validation (CreateOrderOptions). + + + + Optional flag for negative risk markets (CreateOrderOptions). Optional. + + + + A random salt value for the signed order. + + + + The maker's address. + + + + The signer's address. + + + + The token ID in the signed order. + + + + The maker amount as a string. + + + + The taker amount as a string. + + + + The side of the order as a number (0 = BUY, 1 = SELL). + + + + The expiration timestamp included in the order payload. This is not part of + the CLOB V2 EIP-712 signed order struct. + + + + Order creation timestamp in milliseconds, used for order uniqueness in CLOB + V2. + + + + Reserved `bytes32` metadata field. + + + + Builder code (`bytes32`) for attribution, or zero if no builder code is + attached. + + + + The type identifier for the signature scheme used. + + + + The cryptographic signature of the order. + + +*** + +### createMarketOrder + +Create and sign a market order locally without posting it to the CLOB. Submit via [`postOrder()`](/trading/clients/l2#postorder) or [`postOrders()`](/trading/clients/l2#postorders). + +```typescript Signature theme={null} +async createMarketOrder( + userMarketOrder: UserMarketOrder, + options?: Partial +): Promise +``` + + + The token ID of the market outcome to trade. + + + + The order amount. For BUY orders this is a dollar amount; for SELL orders this + is the number of shares. + + + + The side of the order (buy or sell). + + + + Optional price limit for the market order. Optional. + + + + Optional order type, either FOK (Fill-Or-Kill) or FAK (Fill-And-Kill). + Optional. + + + + A random salt value for the signed order. + + + + The maker's address. + + + + The signer's address. + + + + The token ID in the signed order. + + + + The maker amount as a string. + + + + The taker amount as a string. + + + + The side of the order as a number (0 = BUY, 1 = SELL). + + + + The expiration timestamp included in the order payload. This is not part of + the CLOB V2 EIP-712 signed order struct. + + + + Order creation timestamp in milliseconds, used for order uniqueness in CLOB + V2. + + + + Reserved `bytes32` metadata field. + + + + Builder code (`bytes32`) for attribution, or zero if no builder code is + attached. + + + + The type identifier for the signature scheme used. + + + + The cryptographic signature of the order. + + +*** + +## Troubleshooting + + + + Your wallet's private key is incorrect or improperly formatted. + + **Solution:** + + * Verify your private key is a valid hex string (starts with `0x`) + * Ensure you're using the correct key for the intended address + * Check that the key has proper permissions + + + + The nonce you provided has already been used to create an API key. + + **Solution:** + + * Use `deriveApiKey()` with the same nonce to retrieve existing credentials + * Or use a different nonce with `createApiKey()` + + + + Your funder address is incorrect or doesn't match your wallet. + + **Solution:** New API users should use the deposit wallet address as the + funder with signature type `3`. Existing Safe and Proxy users should use + their current smart-wallet address. + + + + Use `deriveApiKey()` with the original nonce: + + ```typescript theme={null} + const recovered = await client.deriveApiKey(originalNonce); + ``` + + + + There's no way to recover lost credentials without the nonce. Create new ones: + + ```typescript theme={null} + // Create fresh credentials with a new nonce + const newCreds = await client.createApiKey(); + // Save the nonce this time! + ``` + + + +*** + +## See Also + + + + Deep dive into L1 and L2 authentication. + + + + Initialize the client and place your first order. + + + + Access market data, orderbooks, and prices without auth. + + + + Place and manage orders with API credentials. + + diff --git a/PolymarketDocumentation-main/docs/developers/CLOB/clients/methods-l2.md b/PolymarketDocumentation-main/docs/developers/CLOB/clients/methods-l2.md new file mode 100644 index 00000000..99920c87 --- /dev/null +++ b/PolymarketDocumentation-main/docs/developers/CLOB/clients/methods-l2.md @@ -0,0 +1,752 @@ +> ## Documentation Index +> Fetch the complete documentation index at: https://docs.polymarket.com/llms.txt +> Use this file to discover all available pages before exploring further. + +# L2 Methods + +> These methods require user API credentials (L2 headers). Use these for placing trades and managing your positions. + +## Client Initialization + +L2 methods require the client to initialize with a signer, signature type, API credentials, and funder address. + + + + ```typescript theme={null} + import { ClobClient } from "@polymarket/clob-client-v2"; + import { createWalletClient, http } from "viem"; + import { privateKeyToAccount } from "viem/accounts"; + + const account = privateKeyToAccount(process.env.PRIVATE_KEY as `0x${string}`); + const signer = createWalletClient({ account, transport: http() }); + + const apiCreds = { + key: process.env.API_KEY, + secret: process.env.SECRET, + passphrase: process.env.PASSPHRASE, + }; + const depositWalletAddress = process.env.DEPOSIT_WALLET_ADDRESS!; + + const client = new ClobClient({ + host: "https://clob.polymarket.com", + chain: 137, + signer, + creds: apiCreds, + signatureType: 3, // POLY_1271 + funderAddress: depositWalletAddress, + }); + + // Ready to send authenticated requests + const order = await client.postOrder(signedOrder); + ``` + + + + ```python theme={null} + from py_clob_client_v2 import ClobClient + from py_clob_client_v2 import ApiCreds + import os + + api_creds = ApiCreds( + api_key=os.getenv("API_KEY"), + api_secret=os.getenv("SECRET"), + api_passphrase=os.getenv("PASSPHRASE") + ) + + client = ClobClient( + host="https://clob.polymarket.com", + chain_id=137, + key=os.getenv("PRIVATE_KEY"), + creds=api_creds, + signature_type=3, # POLY_1271 + funder=os.getenv("DEPOSIT_WALLET_ADDRESS") + ) + + # Ready to send authenticated requests + order = client.post_order(signed_order) + ``` + + + +*** + +## Order Creation and Management + +*** + +### createAndPostOrder + +Convenience method that creates, signs, and posts a limit order in a single call. Use when you want to buy or sell at a specific price. + +```typescript Signature theme={null} +async createAndPostOrder( + userOrder: UserOrder, + options?: Partial, + orderType?: OrderType.GTC | OrderType.GTD, // Defaults to GTC +): Promise +``` + +**Params** + + + The token ID of the outcome to trade. + + + + The limit price for the order. + + + + The size of the order. + + + + The side of the order (buy or sell). + + + + Optional expiration timestamp for the order. + + + + Tick size for the order. One of `"0.1"`, `"0.01"`, `"0.001"`, `"0.0001"`. + + + + Optional. Whether the market uses negative risk. + + +**Response** + + + Whether the order was successfully placed. + + + + Error message if the order was not successful. + + + + The ID of the placed order. + + + + Array of transaction hashes associated with the order. + + + + The current status of the order. + + + + The amount being taken in the order. + + + + The amount being made in the order. + + +*** + +### createAndPostMarketOrder + +Convenience method that creates, signs, and posts a market order in a single call. Use when you want to buy or sell at the current market price. + +```typescript Signature theme={null} +async createAndPostMarketOrder( + userMarketOrder: UserMarketOrder, + options?: Partial, + orderType?: OrderType.FOK | OrderType.FAK, // Defaults to FOK +): Promise +``` + +**Params** + + + The token ID of the outcome to trade. + + + + The amount for the market order. + + + + The side of the order (buy or sell). + + + + Optional price hint for the market order. + + + + Optional order type override. Defaults to FOK. + + +**Response** + + + Whether the order was successfully placed. + + + + Error message if the order was not successful. + + + + The ID of the placed order. + + + + Array of transaction hashes associated with the order. + + + + The current status of the order. + + + + The amount being taken in the order. + + + + The amount being made in the order. + + +*** + +### postOrder + +Posts a pre-signed order to the CLOB. Use with [`createOrder()`](/trading/clients/l1#createorder) or [`createMarketOrder()`](/trading/clients/l1#createmarketorder) from L1 methods. + +```typescript Signature theme={null} +async postOrder( + order: SignedOrder, + orderType?: OrderType, // Defaults to GTC + postOnly?: boolean, // Defaults to false +): Promise +``` + +*** + +### postOrders + +Posts up to 15 pre-signed orders in a single batch. + +```typescript Signature theme={null} +async postOrders( + args: PostOrdersArgs[], +): Promise +``` + +**Params** + + + The pre-signed order to post. + + + + The order type (e.g. GTC, FOK, FAK). + + + + Optional. Whether to post the order as post-only. Defaults to false. + + +*** + +### cancelOrder + +Cancels a single open order. + +```typescript Signature theme={null} +async cancelOrder(orderID: string): Promise +``` + +**Response** + + + Array of order IDs that were successfully canceled. + + + + Map of order IDs to reasons why they could not be canceled. + + +*** + +### cancelOrders + +Cancels multiple orders in a single batch. + +```typescript Signature theme={null} +async cancelOrders(orderIDs: string[]): Promise +``` + +*** + +### cancelAll + +Cancels all open orders. + +```typescript Signature theme={null} +async cancelAll(): Promise +``` + +*** + +### cancelMarketOrders + +Cancels all open orders for a specific market. + +```typescript Signature theme={null} +async cancelMarketOrders( + payload: OrderMarketCancelParams +): Promise +``` + +**Params** + + + Optional. The market condition ID to cancel orders for. + + + + Optional. The token ID to cancel orders for. + + +*** + +## Order and Trade Queries + +*** + +### getOrder + +Get details for a specific order by ID. + +```typescript Signature theme={null} +async getOrder(orderID: string): Promise +``` + +**Response** + + + The unique order ID. + + + + The current status of the order. + + + + The API key of the order owner. + + + + The on-chain address of the order maker. + + + + The market condition ID the order belongs to. + + + + The token ID the order is for. + + + + The side of the order (BUY or SELL). + + + + The original size of the order when it was placed. + + + + The amount of the order that has been matched so far. + + + + The limit price of the order. + + + + Array of trade IDs associated with this order. + + + + The outcome label for the order's token. + + + + Unix timestamp of when the order was created. + + + + The expiration time of the order. + + + + The order type (e.g. GTC, FOK, FAK, GTD). + + +*** + +### getOpenOrders + +Get all your open orders. + +```typescript Signature theme={null} +async getOpenOrders( + params?: OpenOrderParams, + only_first_page?: boolean, +): Promise +``` + +**Params** + + + Optional. Filter by order ID. + + + + Optional. Filter by market condition ID. + + + + Optional. Filter by token ID. + + +*** + +### getTrades + +Get your trade history (filled orders). + +```typescript Signature theme={null} +async getTrades( + params?: TradeParams, + only_first_page?: boolean, +): Promise +``` + +**Params** + + + Optional. Filter by trade ID. + + + + Optional. Filter by maker address. + + + + Optional. Filter by market condition ID. + + + + Optional. Filter by token ID. + + + + Optional. Return trades before this timestamp. + + + + Optional. Return trades after this timestamp. + + +**Response** + + + The unique trade ID. + + + + The order ID of the taker side. + + + + The market condition ID for the trade. + + + + The token ID for the trade. + + + + The side of the trade (BUY or SELL). + + + + The size of the trade. + + + + The fee rate in basis points. + + + + The price at which the trade was matched. + + + + The current status of the trade. + + + + The time at which the trade was matched. + + + + The time of the last update to this trade. + + + + The outcome label for the traded token. + + + + The bucket index for the trade. + + + + The API key of the trade owner. + + + + The on-chain address of the maker. + + + + Array of maker order objects that participated in this trade. Each + `MakerOrder` contains the following fields: + + + + The maker order ID. + + + + The API key of the maker order owner. + + + + The on-chain address of the maker order maker. + + + + The amount matched for this maker order. + + + + The price of the maker order. + + + + The fee rate in basis points for the maker order. + + + + The token ID for the maker order. + + + + The outcome label for the maker order's token. + + + + The side of the maker order (BUY or SELL). + + + + The on-chain transaction hash for the trade. + + + + Whether the authenticated user is the taker or a maker in this trade. + + +*** + +### getTradesPaginated + +Get trade history with pagination for large result sets. + +```typescript Signature theme={null} +async getTradesPaginated( + params?: TradeParams, +): Promise +``` + +**Response** + + + Array of trade objects for the current page. + + + + The maximum number of trades returned per page. + + + + The total number of trades matching the query. + + +*** + +## Balance and Allowances + +*** + +### getBalanceAllowance + +Get your balance and allowance for specific tokens. + +```typescript Signature theme={null} +async getBalanceAllowance( + params?: BalanceAllowanceParams +): Promise +``` + +**Params** + + + The type of asset to query. One of `"COLLATERAL"` or `"CONDITIONAL"`. + + + + Optional. The token ID to query (required when `asset_type` is `CONDITIONAL`). + + +**Response** + + + The current balance for the specified asset. + + + + The current allowance for the specified asset. + + +*** + +### updateBalanceAllowance + +Updates the cached balance and allowance for specific tokens. + +```typescript Signature theme={null} +async updateBalanceAllowance( + params?: BalanceAllowanceParams +): Promise +``` + +*** + +## API Key Management + +*** + +### getApiKeys + +Get all API keys associated with your account. + +```typescript Signature theme={null} +async getApiKeys(): Promise +``` + +**Response** + + + Array of API key credential objects associated with the account. + + +*** + +### deleteApiKey + +Deletes (revokes) the currently authenticated API key. + +```typescript Signature theme={null} +async deleteApiKey(): Promise +``` + +*** + +## Notifications + +*** + +### getNotifications + +Retrieves all event notifications for the authenticated user. Records are automatically removed after 48 hours. + +```typescript Signature theme={null} +async getNotifications(): Promise +``` + +**Response** + + + Unique notification ID. + + + + The user's API key, or an empty string for global notifications. + + + + Type-specific payload data for the notification. + + + + Optional Unix timestamp of when the notification was created. + + + + Notification type (see below). + + +| Name | Value | Description | +| ------------------ | ----- | ---------------------------------------- | +| Order Cancellation | `1` | User's order was canceled | +| Order Fill | `2` | User's order was filled (maker or taker) | +| Market Resolved | `4` | Market was resolved | + +*** + +### dropNotifications + +Mark notifications as read/dismissed. + +```typescript Signature theme={null} +async dropNotifications(params?: DropNotificationParams): Promise +``` + +**Params** + + + Array of notification IDs to dismiss. + + +*** + +## See Also + + + + Deep dive into L1 and L2 authentication. + + + + Sign orders and derive API credentials with your private key. + + + + Read market data and orderbooks without auth. + + + + Real-time market data streaming. + + diff --git a/PolymarketDocumentation-main/docs/developers/CLOB/clients/methods-overview.md b/PolymarketDocumentation-main/docs/developers/CLOB/clients/methods-overview.md new file mode 100644 index 00000000..af061da5 --- /dev/null +++ b/PolymarketDocumentation-main/docs/developers/CLOB/clients/methods-overview.md @@ -0,0 +1,99 @@ +> ## Documentation Index +> Fetch the complete documentation index at: https://docs.polymarket.com/llms.txt +> Use this file to discover all available pages before exploring further. + +# Clients & SDKs + +> Official open-source libraries for interacting with Polymarket + +Polymarket provides official open-source clients in TypeScript, Python, and Rust. All three support the full CLOB API including market data, order management, and authentication. + +## Installation + + + ```bash TypeScript theme={null} + npm install @polymarket/clob-client-v2 viem + ``` + + ```bash Python theme={null} + pip install py-clob-client-v2 + ``` + + ```bash Rust theme={null} + cargo add polymarket_client_sdk_v2 --features clob + ``` + + +## Quick Example + + + ```typescript TypeScript theme={null} + import { ClobClient } from "@polymarket/clob-client-v2"; + + const client = new ClobClient({ + host: "https://clob.polymarket.com", + chain: 137, + signer, + creds: apiCreds, + }); + + const markets = await client.getMarkets(); + ``` + + ```python Python theme={null} + from py_clob_client_v2 import ClobClient + + client = ClobClient( + "https://clob.polymarket.com", + key=private_key, + chain_id=137, + creds=api_creds, + ) + + markets = client.get_markets() + ``` + + ```rust Rust theme={null} + use polymarket_client_sdk_v2::clob::{Client, Config}; + + let client = Client::new("https://clob.polymarket.com", Config::default())? + .authentication_builder(&signer) + .authenticate() + .await?; + + let markets = client.markets(None).await?; + ``` + + +## Source Code + +| Language | Package | Repository | +| ---------- | ---------------------------- | ------------------------------------------------------------------------------------------ | +| TypeScript | `@polymarket/clob-client-v2` | [github.com/Polymarket/clob-client-v2](https://github.com/Polymarket/clob-client-v2) | +| Python | `py-clob-client-v2` | [github.com/Polymarket/py-clob-client-v2](https://github.com/Polymarket/py-clob-client-v2) | +| Rust | `polymarket_client_sdk_v2` | [github.com/Polymarket/rs-clob-client-v2](https://github.com/Polymarket/rs-clob-client-v2) | + +Each repository includes working examples in the `/examples` directory. + +## Relayer SDK + +For [gasless transactions](/trading/gasless), the relayer client handles deposit +wallet creation and signed wallet batches for new API users. Existing Safe and +Proxy wallet flows remain supported. + +| Language | Package | Repository | +| ---------- | ------------------------------------ | ---------------------------------------------------------------------------------------------------------- | +| TypeScript | `@polymarket/builder-relayer-client` | [github.com/Polymarket/builder-relayer-client](https://github.com/Polymarket/builder-relayer-client) | +| Python | `py-builder-relayer-client` | [github.com/Polymarket/py-builder-relayer-client](https://github.com/Polymarket/py-builder-relayer-client) | + +## Next Steps + + + + Set up your client and place your first order. + + + + Understand L1/L2 auth and API credentials. + + diff --git a/PolymarketDocumentation-main/docs/developers/CLOB/clients/methods-public.md b/PolymarketDocumentation-main/docs/developers/CLOB/clients/methods-public.md new file mode 100644 index 00000000..22b33b3f --- /dev/null +++ b/PolymarketDocumentation-main/docs/developers/CLOB/clients/methods-public.md @@ -0,0 +1,748 @@ +> ## Documentation Index +> Fetch the complete documentation index at: https://docs.polymarket.com/llms.txt +> Use this file to discover all available pages before exploring further. + +# Public Methods + +> These methods can be called without a signer or user credentials. Use these for reading market data, prices, and order books. + +## Client Initialization + +Public methods require the client to initialize with the host URL and Polygon chain ID. + + + + ```typescript theme={null} + import { ClobClient } from "@polymarket/clob-client-v2"; + + const client = new ClobClient({ + host: "https://clob.polymarket.com", + chain: 137, + }); + + // Ready to call public methods + const markets = await client.getMarkets(); + ``` + + + + ```python theme={null} + from py_clob_client_v2 import ClobClient + + client = ClobClient( + host="https://clob.polymarket.com", + chain_id=137 + ) + + # Ready to call public methods + markets = client.get_markets() + ``` + + + +*** + +## Health Check + +*** + +### getOk + +Health check endpoint to verify the CLOB service is operational. + +```typescript Signature theme={null} +async getOk(): Promise +``` + +*** + +## Markets + +*** + +### getMarket + +Get details for a single market by condition ID. + +```typescript Signature theme={null} +async getMarket(conditionId: string): Promise +``` + + + Timestamp from which the market started accepting orders, or null if not set. + + + + Whether the market is currently accepting orders. + + + + Whether the market is active. + + + + Whether the market has been archived. + + + + Whether the market is closed. + + + + The unique condition ID for the market. + + + + Human-readable description of the market. + + + + Whether the order book is enabled for this market. + + + + ISO 8601 end date of the market. + + + + Address of the Fixed Product Market Maker contract. + + + + Start time of the underlying game or event. + + + + URL of the market icon image. + + + + URL of the market image. + + + + Whether the market has equal 50/50 outcomes. + + + + Base fee charged to makers in basis points. + + + + URL-friendly slug identifier for the market. + + + + Minimum order size allowed in this market. + + + + Minimum price increment allowed in this market. + + + + Whether the market uses negative risk (binary complementary tokens). + + + + Negative risk market identifier, if applicable. + + + + Negative risk request identifier, if applicable. + + + + Whether notifications are enabled for this market. + + + + The market question text. + + + + Unique identifier for the market question. + + + + Object containing reward config: `max_spread` (number), `min_size` (number), `rates` (any) + + + + Delay in seconds before orders are processed. + + + + List of tags associated with the market. + + + + Base fee charged to takers in basis points. + + + + Array of market tokens, each containing `outcome` (string), `price` (number), `token_id` (string), and `winner` (boolean). + + +*** + +### getMarkets + +Get details for multiple markets paginated. + +```typescript Signature theme={null} +async getMarkets(): Promise +``` + + + Maximum number of results per page. + + + + Total number of markets returned. + + + + Array of Market objects. See `getMarket()` for the full Market structure. + + +*** + +### getSimplifiedMarkets + +Get simplified market data paginated for faster loading. + +```typescript Signature theme={null} +async getSimplifiedMarkets(): Promise +``` + + + Maximum number of results per page. + + + + Total number of markets returned. + + + + Array of simplified market objects, each containing `accepting_orders` (boolean), `active` (boolean), `archived` (boolean), `closed` (boolean), `condition_id` (string), `rewards` (object with `rates`, `min_size`, `max_spread`), and `tokens` (SimplifiedToken\[]) with `outcome` (string), `price` (number), `token_id` (string). + + +*** + +### getSamplingMarkets + +Get markets eligible for sampling/liquidity rewards. + +```typescript Signature theme={null} +async getSamplingMarkets(): Promise +``` + +*** + +### getSamplingSimplifiedMarkets + +Get simplified market data for markets eligible for sampling/liquidity rewards. + +```typescript Signature theme={null} +async getSamplingSimplifiedMarkets(): Promise +``` + +*** + +## Order Books and Prices + +*** + +### calculateMarketPrice + +Calculate the estimated price for a market order of a given size. + +```typescript Signature theme={null} +async calculateMarketPrice( + tokenID: string, + side: Side, + amount: number, + orderType: OrderType = OrderType.FOK +): Promise +``` + + + The token ID to calculate the market price for. + + + + The side of the order. One of: `BUY`, `SELL` + + + + The size of the order to calculate price for. + + + + The order type. One of: `GTC` (Good Till Cancelled), `FOK` (Fill or Kill), `GTD` (Good Till Date), `FAK` (Fill and Kill). Defaults to `FOK`. + + + + The calculated estimated market price for the given order size. + + +*** + +### getOrderBook + +Get the order book for a specific token ID. + +```typescript Signature theme={null} +async getOrderBook(tokenID: string): Promise +``` + + + The market condition ID. + + + + The token/asset ID for this order book. + + + + Timestamp of the order book snapshot. + + + + Array of bid entries, each with `price` (string) and `size` (string). + + + + Array of ask entries, each with `price` (string) and `size` (string). + + + + Minimum order size for this market. + + + + Minimum price increment for this market. + + + + Whether the market uses negative risk. + + + + Hash of the order book state. + + +*** + +### getOrderBooks + +Get order books for multiple token IDs. + +```typescript Signature theme={null} +async getOrderBooks(params: BookParams[]): Promise +``` + + + The token ID to fetch the order book for. + + + + The side of the book to query. One of: `BUY`, `SELL` + + + + Array of OrderBookSummary objects. See `getOrderBook()` for the full structure. + + +*** + +### getPrice + +Get the current best price for buying or selling a token ID. + +```typescript Signature theme={null} +async getPrice( + tokenID: string, + side: "BUY" | "SELL" +): Promise +``` + + + The current best price for the requested side. + + +*** + +### getPrices + +Get the current best prices for multiple token IDs. + +```typescript Signature theme={null} +async getPrices(params: BookParams[]): Promise +``` + + + A map of token IDs to their prices. Each entry contains an optional `BUY` (string) and/or `SELL` (string) price. + + +*** + +### getMidpoint + +Get the midpoint price (average of best bid and best ask) for a token ID. + +```typescript Signature theme={null} +async getMidpoint(tokenID: string): Promise +``` + + + The midpoint price, calculated as the average of best bid and best ask. + + +*** + +### getMidpoints + +Get the midpoint prices for multiple token IDs. + +```typescript Signature theme={null} +async getMidpoints(params: BookParams[]): Promise +``` + + + A map of token IDs to their midpoint price strings. Each key is a token ID and its value is the midpoint price as a string. + + +*** + +### getSpread + +Get the spread (difference between best ask and best bid) for a token ID. + +```typescript Signature theme={null} +async getSpread(tokenID: string): Promise +``` + + + The spread value, calculated as the difference between best ask and best bid. + + +*** + +### getSpreads + +Get the spreads for multiple token IDs. + +```typescript Signature theme={null} +async getSpreads(params: BookParams[]): Promise +``` + + + A map of token IDs to their spread strings. Each key is a token ID and its value is the spread as a string. + + +*** + +### getPricesHistory + +Get historical price data for a token. + +```typescript Signature theme={null} +async getPricesHistory(params: PriceHistoryFilterParams): Promise +``` + + + The token ID to fetch price history for. + + + + Optional start timestamp (Unix seconds) for the price history range. + + + + Optional end timestamp (Unix seconds) for the price history range. + + + + Optional fidelity/resolution of the price history data. + + + + Time interval for the price history. One of: `max`, `1w`, `1d`, `6h`, `1h` + + + + Unix timestamp of the price data point. + + + + Price value at the corresponding timestamp. + + +*** + +## Trades + +*** + +### getLastTradePrice + +Get the price of the most recent trade for a token. + +```typescript Signature theme={null} +async getLastTradePrice(tokenID: string): Promise +``` + + + The price of the most recent trade. + + + + The side of the most recent trade. + + +*** + +### getLastTradesPrices + +Get the most recent trade prices for multiple tokens. + +```typescript Signature theme={null} +async getLastTradesPrices(params: BookParams[]): Promise +``` + + + The price of the most recent trade for the token. + + + + The side of the most recent trade. + + + + The token ID this trade price corresponds to. + + +*** + +### getMarketTradesEvents + +Get recent trade events for a market. + +```typescript Signature theme={null} +async getMarketTradesEvents(conditionID: string): Promise +``` + + + The type of trade event. + + + + Object containing market info: `condition_id` (string), `asset_id` (string), `question` (string), `icon` (string), `slug` (string). + + + + Object containing user info: `address` (string), `username` (string), `profile_picture` (string), `optimized_profile_picture` (string), `pseudonym` (string). + + + + The side of the trade. One of: `BUY`, `SELL` + + + + The size of the trade. + + + + The fee rate in basis points for the trade. + + + + The price at which the trade was executed. + + + + The outcome label for the traded token. + + + + The index of the outcome in the market. + + + + The on-chain transaction hash for the trade. + + + + The timestamp of when the trade event occurred. + + +*** + +## Market Parameters + +*** + +### getClobMarketInfo + +Fetch all CLOB-level parameters for a market in a single call — tokens, tick size, base fees, rewards config, RFQ status, and fee details. + +```typescript Signature theme={null} +async getClobMarketInfo(conditionID: string): Promise +``` + + + The condition ID of the market. + + +**Response (`ClobMarketDetails`)** + + + Game start time (used for sports markets), ISO 8601 timestamp or `null`. + + + + Rewards configuration for the market. + + + + Tokens for this market. Each entry has: + + * `t` (string) — token ID + * `o` (string) — outcome label (e.g. `Yes`, `No`) + + + + Minimum order size. + + + + Minimum tick size (price increment). + + + + Maker base fee in basis points. + + + + Taker base fee in basis points. + + + + Whether RFQ (Request for Quote) is enabled for this market. + + + + Whether taker order delay is enabled. + + + + Whether Blockaid check is enabled. + + + + Fee curve parameters: + + * `r` (number) — fee rate + * `e` (number) — fee curve exponent + * `to` (boolean) — whether fees apply to takers only + + + + Minimum order age in seconds. + + +*** + +### getFeeRateBps + +Get the fee rate in basis points for a token. + +```typescript Signature theme={null} +async getFeeRateBps(tokenID: string): Promise +``` + + + The fee rate in basis points for the specified token. + + +*** + +### getFeeExponent + +Get the fee curve exponent for a token. The exponent shapes the fee curve used by the protocol when calculating fees at match time. + +```typescript Signature theme={null} +async getFeeExponent(tokenID: string): Promise +``` + + + The fee curve exponent for the specified token's market. + + +*** + +### getTickSize + +Get the tick size (minimum price increment) for a market. + +```typescript Signature theme={null} +async getTickSize(tokenID: string): Promise +``` + + + The tick size for the market. One of: `0.1`, `0.01`, `0.001`, `0.0001` + + +*** + +### getNegRisk + +Check if a market uses negative risk (binary complementary tokens). + +```typescript Signature theme={null} +async getNegRisk(tokenID: string): Promise +``` + + + Whether the market uses negative risk. + + +*** + +## Time and Server Info + +### getServerTime + +Get the current server timestamp. + +```typescript Signature theme={null} +async getServerTime(): Promise +``` + + + Unix timestamp in seconds representing the current server time. + + +*** + +## See Also + + + + Private key authentication to create or derive API credentials. + + + + Place orders, cancel orders, and query your trades. + + + + Complete REST endpoint documentation. + + + + Real-time market data streaming. + + diff --git a/PolymarketDocumentation-main/docs/developers/CLOB/geoblock.md b/PolymarketDocumentation-main/docs/developers/CLOB/geoblock.md new file mode 100644 index 00000000..f94e30f0 --- /dev/null +++ b/PolymarketDocumentation-main/docs/developers/CLOB/geoblock.md @@ -0,0 +1,233 @@ +> ## Documentation Index +> Fetch the complete documentation index at: https://docs.polymarket.com/llms.txt +> Use this file to discover all available pages before exploring further. + +# Geographic Restrictions + +> Check geographic restrictions before placing orders on the Polymarket API + +Polymarket restricts order placement from certain geographic locations due to regulatory requirements and compliance with international sanctions. Before placing orders, builders should verify the location. + + + Orders submitted from blocked regions will be rejected. Implement geoblock + checks in your application to provide users with appropriate feedback before + they attempt to trade. + + +*** + +## Geoblock Endpoint + +Check the geographic eligibility of the requesting IP address: + +```bash theme={null} +GET https://polymarket.com/api/geoblock +``` + +This endpoint is on `polymarket.com`, not the API servers. + +### Response + +```json theme={null} +{ + "blocked": true, + "ip": "203.0.113.42", + "country": "US", + "region": "NY" +} +``` + +| Field | Type | Description | +| --------- | ------- | ----------------------------------------------- | +| `blocked` | boolean | Whether the user is blocked from placing orders | +| `ip` | string | Detected IP address | +| `country` | string | ISO 3166-1 alpha-2 country code | +| `region` | string | Region/state code | + +*** + +## Restricted Jurisdictions + +Restrictions fall into three groups. **Block completely** means no new orders and no closing of existing positions. **Close-only** means users can close existing positions but cannot open new ones. Each group notes whether it applies on the frontend, the API, or both. Codes are ISO 3166-1 alpha-2 for countries and ISO 3166-2 for sub-national regions. + +### OFAC-Sanctioned Jurisdictions (Block Completely) + +Blocked on both the frontend and the API. No new orders, and existing positions cannot be closed. + +| Jurisdiction | Code | +| ----------------- | ----- | +| Iran | IR | +| Syria | SY | +| Cuba | CU | +| North Korea | KP | +| Ukraine — Crimea | UA-43 | +| Ukraine — Donetsk | UA-14 | +| Ukraine — Luhansk | UA-09 | + +### Regulatory-Restricted Jurisdictions (Close-Only on Frontend and API) + +Users can close existing positions but cannot open new ones, on both the frontend and the API. + +| Jurisdiction | Code | +| ------------------------------------ | ----- | +| Australia | AU | +| Belarus | BY | +| Belgium | BE | +| Burundi | BI | +| Brazil | BR | +| Canada — British Columbia | CA-BC | +| Canada — Ontario | CA-ON | +| Canada — Alberta | CA-AB | +| Canada — Quebec | CA-QC | +| Central African Republic | CF | +| Congo (Kinshasa) | CD | +| Ethiopia | ET | +| France | FR | +| Germany | DE | +| Iraq | IQ | +| Italy | IT | +| Lebanon | LB | +| Libya | LY | +| Myanmar | MM | +| Nicaragua | NI | +| North Korea | KP | +| Poland | PL | +| Russia | RU | +| Singapore | SG | +| Somalia | SO | +| Slovakia | SK | +| South Sudan | SS | +| Sudan | SD | +| Taiwan | TW | +| Thailand | TH | +| United Kingdom | GB | +| United States | US | +| United States Minor Outlying Islands | UM | +| Venezuela | VE | +| Yemen | YE | +| Zimbabwe | ZW | + +### Regulatory-Restricted Jurisdictions (Close-Only on Frontend) + +Close-only on the Polymarket frontend; the API itself is not restricted. + +| Jurisdiction | Code | +| ------------------- | ---- | +| Japan | JP | +| Netherlands | NL | +| Malta (Sports Only) | MT | + +*** + +## Blocking Logic + +The geoblocking system includes: + +1. **OFAC-Sanctioned Countries**: Countries sanctioned by the U.S. Office of Foreign Assets Control (OFAC) +2. **Additional Regulatory Restrictions**: Countries added for specific regulatory compliance reasons + +*** + +## Server Infrastructure + +* **Primary Servers**: eu-west-2 +* **Closest Non-Georestricted Region**: eu-west-1 + + + **Direct co-location available.** Users who complete the [KYC/KYB + form](https://docs.google.com/forms/d/e/1FAIpQLSfY-3Dl3yxq8HKFjFad8YzKZmm0k3Gdg29HD6gL-K-AmI6KXw/viewform) can get access to co-locate + directly in `eu-west-2` for the lowest possible latency to Polymarket's + primary servers. + + +*** + +## Usage Examples + + + + ```typescript theme={null} + interface GeoblockResponse { + blocked: boolean; + ip: string; + country: string; + region: string; + } + + async function checkGeoblock(): Promise { + const response = await fetch("https://polymarket.com/api/geoblock"); + return response.json(); + } + + // Usage + const geo = await checkGeoblock(); + + if (geo.blocked) { + console.log(`Trading not available in ${geo.country}`); + } else { + console.log("Trading available"); + } + ``` + + + + ```python theme={null} + import requests + + def check_geoblock() -> dict: + response = requests.get("https://polymarket.com/api/geoblock") + return response.json() + + # Usage + geo = check_geoblock() + + if geo["blocked"]: + print(f"Trading not available in {geo['country']}") + else: + print("Trading available") + ``` + + + + ```rust theme={null} + use polymarket_client_sdk_v2::clob::{Client, Config}; + + let client = Client::new("https://clob.polymarket.com", Config::default())?; + let geo = client.check_geoblock().await?; + + if geo.blocked { + println!("Trading not available in {}", geo.country); + } else { + println!("Trading available"); + } + ``` + + + +*** + +## Why These Restrictions + +Geographic restrictions are implemented to ensure compliance with: + +* International sanctions and embargoes +* Local financial regulations +* Gambling and prediction market laws +* Anti-money laundering (AML) requirements +* Know Your Customer (KYC) regulations + +If you believe you are incorrectly restricted or have questions about geographic availability, please contact [Polymarket Support](https://polymarket.com/support). + +*** + +## Next Steps + + + + Learn how to authenticate trading requests. + + + + Start placing orders (from eligible regions). + + diff --git a/PolymarketDocumentation-main/docs/developers/CLOB/introduction.md b/PolymarketDocumentation-main/docs/developers/CLOB/introduction.md new file mode 100644 index 00000000..52a2176c --- /dev/null +++ b/PolymarketDocumentation-main/docs/developers/CLOB/introduction.md @@ -0,0 +1,265 @@ +> ## Documentation Index +> Fetch the complete documentation index at: https://docs.polymarket.com/llms.txt +> Use this file to discover all available pages before exploring further. + +# Overview + +> Trading on the Polymarket CLOB + +Polymarket's CLOB (Central Limit Order Book) is a hybrid-decentralized trading system — offchain order matching with onchain settlement via the [Exchange contract](https://github.com/Polymarket/ctf-exchange/tree/main/src) ([audited by Chainsecurity](https://github.com/Polymarket/ctf-exchange/blob/main/audit/ChainSecurity_Polymarket_Exchange_audit.pdf)). All trading is non-custodial. Orders are [EIP-712](https://eips.ethereum.org/EIPS/eip-712) signed messages, and matched trades settle atomically on Polygon. The operator cannot set prices or execute unauthorized trades. + +We recommend using the open-source SDK clients, which handle order signing, authentication, and submission: + + + +

+ npm install @polymarket/clob-client-v2 viem +

+
+ + +

pip install py-clob-client-v2

+
+ + +

+ cargo add polymarket\_client\_sdk\_v2 --features clob +

+
+
+ + + You can also use the REST API directly, but you'll need to manage [EIP-712 + order + signing](https://github.com/Polymarket/clob-client-v2/blob/main/src/signing/eip712.ts) + and [HMAC authentication + headers](https://github.com/Polymarket/clob-client-v2/blob/main/src/signing/hmac.ts) + yourself. See [REST API Headers](#rest-api-headers) below. + + +*** + +## Authentication + +The CLOB uses two levels of authentication: + +| Level | Method | Purpose | +| ------ | ------------------------------- | ----------------------------------------- | +| **L1** | EIP-712 signature (private key) | Create or derive API credentials | +| **L2** | HMAC-SHA256 (API credentials) | Place orders, cancel orders, query trades | + +You use your private key once to derive **L2 credentials** (API key, secret, passphrase), which authenticate all subsequent trading requests. + + + ```typescript TypeScript theme={null} + import { ClobClient } from "@polymarket/clob-client-v2"; + import { createWalletClient, http } from "viem"; + import { privateKeyToAccount } from "viem/accounts"; + + const account = privateKeyToAccount(process.env.PRIVATE_KEY as `0x${string}`); + const signer = createWalletClient({ account, transport: http() }); + + // Derive L2 API credentials + const tempClient = new ClobClient({ + host: "https://clob.polymarket.com", + chain: 137, + signer, + }); + const apiCreds = await tempClient.createOrDeriveApiKey(); + ``` + + ```python Python theme={null} + from py_clob_client_v2 import ClobClient + import os + + private_key = os.getenv("PRIVATE_KEY") + + # Derive L2 API credentials + temp_client = ClobClient("https://clob.polymarket.com", key=private_key, chain_id=137) + api_creds = temp_client.create_or_derive_api_key() + ``` + + ```rust Rust theme={null} + use std::str::FromStr; + use polymarket_client_sdk_v2::POLYGON; + use polymarket_client_sdk_v2::auth::{LocalSigner, Signer}; + use polymarket_client_sdk_v2::clob::{Client, Config}; + + let private_key = std::env::var("POLYMARKET_PRIVATE_KEY")?; + let signer = LocalSigner::from_str(&private_key)? + .with_chain_id(Some(POLYGON)); + + // Derive L2 API credentials and initialize client in one step + let client = Client::new("https://clob.polymarket.com", Config::default())? + .authentication_builder(&signer) + .authenticate() + .await?; + ``` + + +*** + +## Signature Types + +When initializing the trading client, you must specify your wallet's **signature type** and **funder address**: + +| Wallet Type | ID | When to Use | Funder Address | +| ---------------- | --- | -------------------------------------------------------------------------------------------------------------- | --------------------------- | +| **EOA** | `0` | Standalone wallet — you pay your own gas (POL for gas) | Your EOA wallet address | +| **POLY\_PROXY** | `1` | Existing Polymarket proxy wallet flow | Your proxy wallet address | +| **GNOSIS\_SAFE** | `2` | Existing Gnosis Safe wallet flow | Your Safe wallet address | +| **POLY\_1271** | `3` | Deposit wallet flow for new API users. Orders are signed by the owner/session signer and validated by ERC-1271 | Your deposit wallet address | + + + New API users should use deposit wallets with signature type `3`. Existing + Proxy and Safe users are unaffected and can keep using signature types `1` and + `2`. Type `0` is for standalone EOA wallets only. + + +### Initialize the Trading Client + + + ```typescript TypeScript theme={null} + const depositWalletAddress = process.env.DEPOSIT_WALLET_ADDRESS!; + + const client = new ClobClient({ + host: "https://clob.polymarket.com", + chain: 137, + signer, + creds: apiCreds, + signatureType: 3, // POLY_1271 + funderAddress: depositWalletAddress, + }); + ``` + + ```python Python theme={null} + deposit_wallet_address = os.getenv("DEPOSIT_WALLET_ADDRESS") + + client = ClobClient( + "https://clob.polymarket.com", + key=private_key, + chain_id=137, + creds=api_creds, + signature_type=3, # POLY_1271 + funder=deposit_wallet_address + ) + ``` + + ```rust Rust theme={null} + use polymarket_client_sdk_v2::clob::types::SignatureType; + + let deposit_wallet = std::env::var("DEPOSIT_WALLET_ADDRESS")?.parse()?; + + let client = Client::new("https://clob.polymarket.com", Config::default())? + .authentication_builder(&signer) + .funder(deposit_wallet) + .signature_type(SignatureType::Poly1271) + .authenticate() + .await?; + ``` + + +*** + +## REST API Headers + +If you're using the REST API directly (without the SDK), you need to attach authentication headers to each request. + +**L1 Headers** — for creating or deriving API credentials: + +| Header | Description | +| ---------------- | ------------------- | +| `POLY_ADDRESS` | Your wallet address | +| `POLY_SIGNATURE` | EIP-712 signature | +| `POLY_TIMESTAMP` | Unix timestamp | +| `POLY_NONCE` | Request nonce | + +**L2 Headers** — for all trading operations (orders, cancellations, queries): + +| Header | Description | +| ----------------- | ------------------------------------ | +| `POLY_ADDRESS` | Your wallet address | +| `POLY_SIGNATURE` | HMAC-SHA256 signature of the request | +| `POLY_TIMESTAMP` | Unix timestamp | +| `POLY_API_KEY` | Your API key | +| `POLY_PASSPHRASE` | Your API passphrase | + + + Even with L2 authentication, methods that create orders still require the + user's private key for EIP-712 order payload signing. L2 credentials + authenticate the request, but the order itself must be signed by the key. + + +*** + +## Client Methods + + + + Market data, orderbooks, prices, and spreads — no auth required. + + + + Sign orders and derive API credentials with your private key. + + + + Place orders, cancel orders, query trades, and manage notifications. + + + + Track orders and trades attributed to your builder code. + + + +*** + +## Server Infrastructure + +The CLOB matching engine runs in the following regions: + +* **Primary Servers**: eu-west-2 +* **Closest Non-Georestricted Region**: eu-west-1 + + + **Direct co-location available.** Users who complete the [KYC/KYB + form](https://docs.google.com/forms/d/e/1FAIpQLSfY-3Dl3yxq8HKFjFad8YzKZmm0k3Gdg29HD6gL-K-AmI6KXw/viewform) can get access to co-locate + directly in `eu-west-2` for the lowest possible latency to Polymarket's + primary servers. See [Geographic + Restrictions](/api-reference/geoblock#server-infrastructure) for full + geographic availability details. + + +*** + +## What Is in This Section + + + + Place your first order end-to-end + + + + Reading the orderbook, prices, spreads, and midpoints + + + + Order types, tick sizes, creating, cancelling, and querying orders + + + + Fee structure, fee-enabled markets, and maker rebates + + + + Execute onchain operations without paying gas + + + + Split, merge, and redeem outcome tokens + + + + Deposit and withdraw funds across chains + + diff --git a/PolymarketDocumentation-main/docs/developers/CLOB/orders/cancel-orders.md b/PolymarketDocumentation-main/docs/developers/CLOB/orders/cancel-orders.md new file mode 100644 index 00000000..ee48ed17 --- /dev/null +++ b/PolymarketDocumentation-main/docs/developers/CLOB/orders/cancel-orders.md @@ -0,0 +1,391 @@ +> ## Documentation Index +> Fetch the complete documentation index at: https://docs.polymarket.com/llms.txt +> Use this file to discover all available pages before exploring further. + +# Cancel Order + +> Cancel single, multiple, or all open orders + +All cancel endpoints require [L2 authentication](/trading/overview#authentication). The response always includes `canceled` (list of cancelled order IDs) and `not_canceled` (map of order IDs to failure reasons). + +*** + +## Cancel a Single Order + + + ```typescript TypeScript theme={null} + const resp = await client.cancelOrder("0xb816482a..."); + console.log(resp); + // { canceled: ["0xb816482a..."], not_canceled: {} } + ``` + + ```python Python theme={null} + resp = client.cancel(order_id="0xb816482a...") + print(resp) + # {"canceled": ["0xb816482a..."], "not_canceled": {}} + ``` + + ```rust Rust theme={null} + let resp = client.cancel_order("0xb816482a...").await?; + println!("{:?}", resp); + // CancelOrdersResponse { canceled: ["0xb816482a..."], not_canceled: {} } + ``` + + ```bash REST theme={null} + curl -X DELETE "https://clob.polymarket.com/order" \ + -H "Content-Type: application/json" \ + -H "POLY_ADDRESS: ..." \ + -H "POLY_SIGNATURE: ..." \ + -H "POLY_TIMESTAMP: ..." \ + -H "POLY_API_KEY: ..." \ + -H "POLY_PASSPHRASE: ..." \ + -d '{"orderID": "0xb816482a..."}' + ``` + + +*** + +## Cancel Multiple Orders + + + ```typescript TypeScript theme={null} + const resp = await client.cancelOrders(["0xb816482a...", "0xc927593b..."]); + ``` + + ```python Python theme={null} + resp = client.cancel_orders([ + "0xb816482a...", + "0xc927593b...", + ]) + ``` + + ```rust Rust theme={null} + let resp = client.cancel_orders(&["0xb816482a...", "0xc927593b..."]).await?; + ``` + + ```bash REST theme={null} + curl -X DELETE "https://clob.polymarket.com/orders" \ + -H "Content-Type: application/json" \ + -H "POLY_ADDRESS: ..." \ + -H "POLY_SIGNATURE: ..." \ + -H "POLY_TIMESTAMP: ..." \ + -H "POLY_API_KEY: ..." \ + -H "POLY_PASSPHRASE: ..." \ + -d '["0xb816482a...", "0xc927593b..."]' + ``` + + +*** + +## Cancel All Orders + +Cancel every open order across all markets: + + + ```typescript TypeScript theme={null} + const resp = await client.cancelAll(); + ``` + + ```python Python theme={null} + resp = client.cancel_all() + ``` + + ```rust Rust theme={null} + let resp = client.cancel_all_orders().await?; + ``` + + ```bash REST theme={null} + curl -X DELETE "https://clob.polymarket.com/cancel-all" \ + -H "POLY_ADDRESS: ..." \ + -H "POLY_SIGNATURE: ..." \ + -H "POLY_TIMESTAMP: ..." \ + -H "POLY_API_KEY: ..." \ + -H "POLY_PASSPHRASE: ..." + ``` + + +*** + +## Cancel by Market + +Cancel all orders for a specific market, optionally filtered to a single token. Both `market` and `asset_id` are optional — omit both to cancel all orders. + + + ```typescript TypeScript theme={null} + const resp = await client.cancelMarketOrders({ + market: "0xbd31dc8a...", // optional: condition ID + asset_id: "52114319501245...", // optional: specific token + }); + ``` + + ```python Python theme={null} + resp = client.cancel_market_orders( + market="0xbd31dc8a...", + asset_id="52114319501245...", # optional + ) + ``` + + ```rust Rust theme={null} + use polymarket_client_sdk_v2::clob::types::request::CancelMarketOrderRequest; + + let request = CancelMarketOrderRequest::builder() + .market("0xbd31dc8a...".parse()?) + .asset_id("52114319501245...".parse()?) + .build(); + let resp = client.cancel_market_orders(&request).await?; + ``` + + ```bash REST theme={null} + curl -X DELETE "https://clob.polymarket.com/cancel-market-orders" \ + -H "Content-Type: application/json" \ + -H "POLY_ADDRESS: ..." \ + -H "POLY_SIGNATURE: ..." \ + -H "POLY_TIMESTAMP: ..." \ + -H "POLY_API_KEY: ..." \ + -H "POLY_PASSPHRASE: ..." \ + -d '{"market": "0xbd31dc8a...", "asset_id": "52114319501245..."}' + ``` + + +*** + +## Querying Orders + +### Get a Single Order + + + ```typescript TypeScript theme={null} + const order = await client.getOrder("0xb816482a..."); + console.log(order.status, order.size_matched); + ``` + + ```python Python theme={null} + order = client.get_order("0xb816482a...") + print(order["status"], order["size_matched"]) + ``` + + ```rust Rust theme={null} + let order = client.order("0xb816482a...").await?; + println!("{:?} {}", order.status, order.size_matched); + ``` + + +### Get Open Orders + +Retrieve all open orders, optionally filtered by market or token: + + + ```typescript TypeScript theme={null} + // All open orders + const orders = await client.getOpenOrders(); + + // Filtered by market + const marketOrders = await client.getOpenOrders({ + market: "0xbd31dc8a...", + }); + + // Filtered by token + const tokenOrders = await client.getOpenOrders({ + asset_id: "52114319501245...", + }); + ``` + + ```python Python theme={null} + from py_clob_client_v2 import OpenOrderParams + + # All open orders + orders = client.get_orders() + + # Filtered by market + market_orders = client.get_orders( + OpenOrderParams(market="0xbd31dc8a...") + ) + ``` + + ```rust Rust theme={null} + use polymarket_client_sdk_v2::clob::types::request::OrdersRequest; + + // All open orders + let orders = client.orders(&OrdersRequest::default(), None).await?; + + // Filtered by market + let request = OrdersRequest::builder() + .market("0xbd31dc8a...".parse()?) + .build(); + let market_orders = client.orders(&request, None).await?; + ``` + + +### OpenOrder Object + +| Field | Type | Description | +| ------------------ | --------- | ------------------------------------------ | +| `id` | string | Order ID | +| `status` | string | Current order status | +| `market` | string | Condition ID | +| `asset_id` | string | Token ID | +| `side` | string | `BUY` or `SELL` | +| `original_size` | string | Size at placement | +| `size_matched` | string | Amount filled | +| `price` | string | Limit price | +| `outcome` | string | Human-readable outcome (e.g., "Yes", "No") | +| `order_type` | string | Order type (GTC, GTD, FOK, FAK) | +| `maker_address` | string | Funder address | +| `owner` | string | API key of the order owner | +| `associate_trades` | string\[] | Trade IDs this order has been included in | +| `expiration` | string | Unix expiration timestamp (`0` if none) | +| `created_at` | string | Unix creation timestamp | + +*** + +## Trade History + +When an order is matched, it creates a trade. Trades progress through these statuses: + +| Status | Terminal | Description | +| ----------- | -------- | --------------------------------------- | +| `MATCHED` | No | Matched and sent for onchain submission | +| `MINED` | No | Mined on the chain, no finality yet | +| `CONFIRMED` | Yes | Achieved finality — trade successful | +| `RETRYING` | No | Transaction failed — being retried | +| `FAILED` | Yes | Failed permanently | + + + ```typescript TypeScript theme={null} + // All trades + const trades = await client.getTrades(); + + // Filtered by market + const marketTrades = await client.getTrades({ + market: "0xbd31dc8a...", + }); + ``` + + ```python Python theme={null} + from py_clob_client_v2 import TradeParams + + trades = client.get_trades() + + market_trades = client.get_trades( + TradeParams(market="0xbd31dc8a...") + ) + ``` + + ```rust Rust theme={null} + use polymarket_client_sdk_v2::clob::types::request::TradesRequest; + + // All trades + let trades = client.trades(&TradesRequest::default(), None).await?; + + // Filtered by market + let request = TradesRequest::builder() + .market("0xbd31dc8a...".parse()?) + .build(); + let market_trades = client.trades(&request, None).await?; + ``` + + +Additional filter parameters: `id`, `maker_address`, `asset_id`, `before`, `after`. + +The Rust SDK uses cursor-based pagination via the `next_cursor` parameter: + + + ```typescript TypeScript theme={null} + const page = await client.getTradesPaginated({ market: "0xbd31dc8a..." }); + console.log(page.trades, page.count); // trades array + total count + ``` + + ```python Python theme={null} + page = client.get_trades_paginated(TradeParams(market="0xbd31dc8a...")) + ``` + + ```rust Rust theme={null} + // First page + let page = client.trades(&request, None).await?; + println!("{} trades, cursor: {}", page.data.len(), page.next_cursor); + + // Next page + let page2 = client.trades(&request, Some(page.next_cursor)).await?; + ``` + + +### Trade Object + +| Field | Type | Description | +| ------------------ | ------------- | ------------------------------------ | +| `id` | string | Trade ID | +| `taker_order_id` | string | Taker order hash | +| `market` | string | Condition ID | +| `asset_id` | string | Token ID | +| `side` | string | `BUY` or `SELL` | +| `size` | string | Trade size | +| `price` | string | Execution price | +| `fee_rate_bps` | string | Fee rate in basis points | +| `status` | string | Trade status (see table above) | +| `match_time` | string | Unix timestamp when matched | +| `last_update` | string | Unix timestamp of last status change | +| `outcome` | string | Human-readable outcome (e.g., "Yes") | +| `maker_address` | string | Maker's funder address | +| `owner` | string | API key of the trade owner | +| `transaction_hash` | string | Onchain transaction hash | +| `bucket_index` | number | Index for trade reconciliation | +| `trader_side` | string | `TAKER` or `MAKER` | +| `maker_orders` | MakerOrder\[] | Maker orders that filled this trade | + + + A single trade can be split across multiple onchain transactions due to gas + limits. Use `bucket_index` and `match_time` to reconcile related transactions + back to a single logical trade. + + +*** + +## Order Scoring + +Check if your resting orders are eligible for [maker rebates](/market-makers/maker-rebates) scoring: + + + ```typescript TypeScript theme={null} + // Single order + const scoring = await client.isOrderScoring({ orderId: "0x..." }); + + // Multiple orders + const batch = await client.areOrdersScoring({ + orderIds: ["0x...", "0x..."], + }); + ``` + + ```python Python theme={null} + from py_clob_client_v2 import OrderScoringParams, OrdersScoringParams + + scoring = client.is_order_scoring( + OrderScoringParams(orderId="0x...") + ) + + batch = client.are_orders_scoring( + OrdersScoringParams(orderIds=["0x...", "0x..."]) + ) + ``` + + ```rust Rust theme={null} + // Single order + let scoring = client.is_order_scoring("0x...").await?; + + // Multiple orders + let batch = client.are_orders_scoring(&["0x...", "0x..."]).await?; + ``` + + +*** + +## Next Steps + + + + Attribute orders to your builder account for volume credit + + + + Understand fee structures and maker rebates + + diff --git a/PolymarketDocumentation-main/docs/developers/CLOB/orders/check-scoring.md b/PolymarketDocumentation-main/docs/developers/CLOB/orders/check-scoring.md new file mode 100644 index 00000000..20013388 --- /dev/null +++ b/PolymarketDocumentation-main/docs/developers/CLOB/orders/check-scoring.md @@ -0,0 +1,550 @@ +> ## Documentation Index +> Fetch the complete documentation index at: https://docs.polymarket.com/llms.txt +> Use this file to discover all available pages before exploring further. + +# Overview + +> Order types, tick sizes, and querying orders + +All orders on Polymarket are expressed as **limit orders**. Market orders are supported by submitting a limit order with a marketable price — your order executes immediately at the best available price on the book. + +The underlying order primitive is structured, hashed, and signed using the [EIP-712](https://eips.ethereum.org/EIPS/eip-712) standard, then executed onchain via the Exchange contract. Preparing orders manually is involved, so we recommend using the open-source [TypeScript](https://github.com/Polymarket/clob-client-v2) or [Python](https://github.com/Polymarket/py-clob-client-v2) SDK clients, which handle signing and submission for you. + + + If you prefer to use the REST API directly, you'll need to manage order + signing yourself. See [Authentication](/api-reference/authentication) for details on + constructing the required headers. + + +*** + +## Order Types + +| Type | Behavior | Use Case | +| ---------------------------- | -------------------------------------------------------------------------------------------------- | -------------------------------------- | +| **GTC** (Good-Til-Cancelled) | Rests on the book until filled or cancelled | Default for passive limit orders | +| **GTD** (Good-Til-Date) | Active until a specified expiration time (UTC seconds timestamp), unless filled or cancelled first | Auto-expire orders before known events | +| **FOK** (Fill-Or-Kill) | Must be filled immediately and entirely, or the whole order is cancelled | All-or-nothing execution | +| **FAK** (Fill-And-Kill) | Fills as many shares as available immediately, then cancels any unfilled remainder | Partial immediate execution | + +* **FOK** and **FAK** are market order types — they execute against resting liquidity immediately. + * **BUY**: specify the dollar amount you want to spend + * **SELL**: specify the number of shares you want to sell +* **GTC** and **GTD** are limit order types — they rest on the book at your specified price. + + + **GTD expiration**: Orders expire one minute before their stated expiration + as a security threshold, and the expiration must be at least three minutes + in the future. For a 5-minute effective lifetime, the correct expiration + value is `now + 1 minute + 5 minutes`. + + +### Post-Only Orders + +Post-only orders are limit orders that will only rest on the book and not match immediately on entry. + +* If a post-only order would cross the spread (i.e., it is marketable), it will be **rejected** rather than executed. +* Post-only **cannot** be combined with market order types (FOK or FAK). If `postOnly = true` is sent with a market order type, the order will be rejected. +* Post-only can only be used with **GTC** and **GTD** order types. + +*** + +## Tick Sizes + +Markets have different minimum price increments (tick sizes). Your order price must conform to the market's tick size, or the order will be rejected. + +| Tick Size | Price Precision | Example Prices | +| --------- | --------------- | ---------------------- | +| `0.1` | 1 decimal | 0.1, 0.2, 0.5 | +| `0.01` | 2 decimals | 0.01, 0.50, 0.99 | +| `0.001` | 3 decimals | 0.001, 0.500, 0.999 | +| `0.0001` | 4 decimals | 0.0001, 0.5000, 0.9999 | +| `0.0025` | 0.25¢ steps | 0.0025, 0.5000, 0.9975 | + + + The `0.0025` (0.25¢) tick size applies only to World Cup *to advance*, *moneyline*, *spreads*, and *totals* markets. Always fetch the market's tick size before quoting rather than assuming a value. + + +Retrieve the tick size for a market using the SDK: + + + ```typescript TypeScript theme={null} + const tickSize = await client.getTickSize(tokenID); + // Returns: "0.1" | "0.01" | "0.001" | "0.0001" + ``` + + ```python Python theme={null} + tick_size = client.get_tick_size(token_id) + # Returns: "0.1" | "0.01" | "0.001" | "0.0001" + ``` + + ```rust Rust theme={null} + let resp = client.tick_size(token_id).await?; + // resp.minimum_tick_size: TickSize::Tenth | Hundredth | Thousandth | TenThousandth + ``` + + + + You can also check the `minimum_tick_size` field on a market object returned + by the [Markets API](/market-data/fetching-markets). + + +*** + +## Negative Risk + +Multi-outcome events (e.g., "Who will win the election?" with 3+ candidates) use a different exchange contract called the **Neg Risk CTF Exchange**. When placing orders on these markets, you must pass `negRisk: true` in the order options. + + + ```typescript TypeScript theme={null} + const response = await client.createAndPostOrder( + { + tokenID: "TOKEN_ID", + price: 0.5, + size: 10, + side: Side.BUY, + }, + { + tickSize: "0.01", + negRisk: true, // Required for multi-outcome markets + }, + ); + ``` + + ```python Python theme={null} + from py_clob_client_v2 import OrderArgs, PartialCreateOrderOptions + from py_clob_client_v2.order_builder.constants import BUY + + response = client.create_and_post_order( + OrderArgs( + token_id="TOKEN_ID", + price=0.50, + size=10, + side=BUY, + ), + options=PartialCreateOrderOptions( + tick_size="0.01", + neg_risk=True, # Required for multi-outcome markets + ) + ) + ``` + + ```rust Rust theme={null} + // The Rust SDK auto-detects neg risk from the token ID — no flag needed. + // The order builder fetches neg_risk and uses the correct exchange contract. + let order = client + .limit_order() + .token_id("TOKEN_ID".parse()?) + .price(dec!(0.50)) + .size(dec!(10)) + .side(Side::Buy) + .build() + .await?; + let signed = client.sign(&signer, order).await?; + let response = client.post_order(signed).await?; + ``` + + +You can check whether a market uses negative risk via the SDK or the market object's `neg_risk` field: + + + ```typescript TypeScript theme={null} + const isNegRisk = await client.getNegRisk(tokenID); + ``` + + ```python Python theme={null} + is_neg_risk = client.get_neg_risk(token_id) + ``` + + ```rust Rust theme={null} + let is_neg_risk = client.neg_risk(token_id).await?; + ``` + + +*** + +## Allowances + +Before placing an order, your funder address must have approved the Exchange contract to spend the relevant tokens: + +* **Buying**: the funder must have set a **pUSD** allowance greater than or equal to the spending amount. +* **Selling**: the funder must have set a **conditional token** allowance greater than or equal to the selling amount. + +This allows the Exchange contract to execute settlement according to your signed order instructions. + +*** + +## Validity Checks + +Orders are continually monitored to make sure they remain valid. This includes tracking: + +* Underlying balances +* Allowances + + + Any maker caught intentionally abusing these checks will be blacklisted. + + +There are also limits on order placement per market. You can only place orders that sum to less than or equal to your available balance for each market. For example, if you have 500 pUSD in your funding wallet, you can place one order to buy 1000 YES at \$0.50 — but any additional buy orders in that market will be rejected since your entire balance is reserved for the first order. + +The max size you can place for an order is: + +$$ +\text{maxOrderSize} = \text{underlyingAssetBalance} - \sum(\text{orderSize} - \text{orderFillAmount}) +$$ + +*** + +## Querying Orders + +All query endpoints require [L2 authentication](/api-reference/authentication). [Builder-authenticated](/trading/clients/builder) clients can also query orders attributed to their builder account using the same methods. + +### Get a Single Order + +Retrieve details for a specific order by its ID: + + + ```typescript TypeScript theme={null} + const order = await client.getOrder("0xb816482a..."); + console.log(order); + ``` + + ```python Python theme={null} + order = client.get_order("0xb816482a...") + print(order) + ``` + + ```rust Rust theme={null} + let order = client.order("0xb816482a...").await?; + println!("{order:?}"); + ``` + + +### Get Open Orders + +Retrieve your open orders, optionally filtered by market or asset: + + + ```typescript TypeScript theme={null} + // All open orders + const orders = await client.getOpenOrders(); + + // Filtered by market + const marketOrders = await client.getOpenOrders({ + market: "0xbd31dc8a...", + }); + + // Filtered by asset + const assetOrders = await client.getOpenOrders({ + asset_id: "52114319501245...", + }); + ``` + + ```python Python theme={null} + from py_clob_client_v2 import OpenOrderParams + + # All open orders + orders = client.get_orders() + + # Filtered by market + market_orders = client.get_orders( + OpenOrderParams( + market="0xbd31dc8a...", + ) + ) + ``` + + ```rust Rust theme={null} + use polymarket_client_sdk_v2::clob::types::request::OrdersRequest; + + // All open orders + let orders = client.orders(&OrdersRequest::default(), None).await?; + + // Filtered by market + let request = OrdersRequest::builder() + .market("0xbd31dc8a...".parse()?) + .build(); + let market_orders = client.orders(&request, None).await?; + + // Filtered by asset + let request = OrdersRequest::builder() + .asset_id("52114319501245...".parse()?) + .build(); + let asset_orders = client.orders(&request, None).await?; + ``` + + +### OpenOrder Object + +Each order returned contains these fields: + +| Field | Type | Description | +| ------------------ | --------- | ------------------------------------------------------------ | +| `id` | string | Order ID | +| `status` | string | Current order status | +| `market` | string | Market ID (condition ID) | +| `asset_id` | string | Token ID | +| `side` | string | `BUY` or `SELL` | +| `original_size` | string | Original order size at placement | +| `size_matched` | string | Amount that has been filled | +| `price` | string | Limit price | +| `outcome` | string | Human-readable outcome (e.g., "Yes", "No") | +| `order_type` | string | Order type (GTC, GTD, FOK, FAK) | +| `maker_address` | string | Funder address | +| `owner` | string | API key of the order owner | +| `expiration` | string | Unix timestamp when the order expires (`0` if no expiration) | +| `associate_trades` | string\[] | Trade IDs this order has been partially included in | +| `created_at` | string | Unix timestamp when the order was created | + +*** + +## Trade History + +When an order is matched, it creates a trade. Trades go through the following statuses: + +| Status | Terminal? | Description | +| ----------- | --------- | -------------------------------------------------------------------- | +| `MATCHED` | No | Matched and sent to the executor service for onchain submission | +| `MINED` | No | Observed as mined on the chain, no finality threshold yet | +| `CONFIRMED` | Yes | Achieved strong probabilistic finality — trade successful | +| `RETRYING` | No | Transaction failed (revert or reorg) — being retried by the operator | +| `FAILED` | Yes | Trade failed permanently and is not being retried | + +### Trade Object + +Each trade contains these fields: + +| Field | Type | Description | +| ------------------ | ------ | ------------------------------------------------------------ | +| `id` | string | Trade ID | +| `taker_order_id` | string | Taker order ID (hash) | +| `market` | string | Market ID (condition ID) | +| `asset_id` | string | Token ID | +| `side` | string | `BUY` or `SELL` | +| `size` | string | Trade size | +| `fee_rate_bps` | string | Fee rate in basis points | +| `price` | string | Trade price | +| `status` | string | Trade status (see table above) | +| `match_time` | string | Unix timestamp when the trade was matched | +| `last_update` | string | Unix timestamp of last status update | +| `outcome` | string | Human-readable outcome (e.g., "Yes", "No") | +| `owner` | string | API key ID of the trade owner | +| `maker_address` | string | Funder address | +| `trader_side` | string | Whether you were `TAKER` or `MAKER` in this trade | +| `transaction_hash` | string | Onchain transaction hash (available after mining) | +| `maker_orders` | array | Array of maker orders matched against this trade (see below) | + +### MakerOrder Fields + +Each entry in the `maker_orders` array contains: + +| Field | Type | Description | +| ---------------- | ------ | ---------------------------- | +| `order_id` | string | Maker order ID (hash) | +| `owner` | string | Maker's API key ID | +| `maker_address` | string | Maker's funder address | +| `matched_amount` | string | Amount matched in this trade | +| `price` | string | Maker order price | +| `fee_rate_bps` | string | Maker fee rate in bps | +| `asset_id` | string | Token ID | +| `outcome` | string | Outcome name | +| `side` | string | `BUY` or `SELL` | + +Retrieve your trades with the SDK: + + + ```typescript TypeScript theme={null} + // All trades + const trades = await client.getTrades(); + + // Filtered by market + const marketTrades = await client.getTrades({ + market: "0xbd31dc8a...", + }); + + // With pagination + const paginatedTrades = await client.getTradesPaginated({ + market: "0xbd31dc8a...", + }); + ``` + + ```python Python theme={null} + from py_clob_client_v2 import TradeParams + + # All trades + trades = client.get_trades() + + # Filtered by market + market_trades = client.get_trades( + TradeParams( + market="0xbd31dc8a...", + ) + ) + ``` + + ```rust Rust theme={null} + use polymarket_client_sdk_v2::clob::types::request::TradesRequest; + + // All trades + let trades = client.trades(&TradesRequest::default(), None).await?; + + // Filtered by market + let request = TradesRequest::builder() + .market("0xbd31dc8a...".parse()?) + .build(); + let market_trades = client.trades(&request, None).await?; + ``` + + +*** + +## Heartbeat + +The heartbeat endpoint maintains session liveness for order safety. If a valid heartbeat is not received within **10 seconds** (with up to a 5-second buffer), **all of your open orders will be cancelled**. + + + ```typescript TypeScript theme={null} + // Send heartbeats in a loop + let heartbeatId = ""; + setInterval(async () => { + const resp = await client.postHeartbeat(heartbeatId); + heartbeatId = resp.heartbeat_id; + }, 5000); + ``` + + ```python Python theme={null} + import time + + heartbeat_id = "" + while True: + resp = client.post_heartbeat(heartbeat_id) + heartbeat_id = resp["heartbeat_id"] + time.sleep(5) + ``` + + ```rust Rust theme={null} + // With the `heartbeats` feature, auto-send in background: + Client::start_heartbeats(&mut client)?; + + // Or manually: + let resp = client.post_heartbeat(None).await?; // None for first call + let resp = client.post_heartbeat(Some(resp.heartbeat_id)).await?; + ``` + + +* On each request, include the most recent `heartbeat_id` you received. For your first request, use an empty string. +* If you send an invalid or expired `heartbeat_id`, the server responds with a `400 Bad Request` and provides the correct `heartbeat_id` in the response. Update your client and retry. + +*** + +## Order Scoring + +Check if your resting orders are eligible for [maker rebates](/market-makers/maker-rebates) scoring: + + + ```typescript TypeScript theme={null} + // Single order + const scoring = await client.isOrderScoring({ orderId: "0x..." }); + console.log(scoring); // { scoring: true } + + // Multiple orders + const batchScoring = await client.areOrdersScoring({ + orderIds: ["0x...", "0x..."], + }); + ``` + + ```python Python theme={null} + from py_clob_client_v2 import OrderScoringParams, OrdersScoringParams + + # Single order + scoring = client.is_order_scoring( + OrderScoringParams(orderId="0x...") + ) + + # Multiple orders + batch_scoring = client.are_orders_scoring( + OrdersScoringParams(orderIds=["0x...", "0x..."]) + ) + ``` + + ```rust Rust theme={null} + // Single order + let scoring = client.is_order_scoring("0x...").await?; + println!("Scoring: {}", scoring.scoring); + + // Multiple orders + let batch = client.are_orders_scoring(&["0x...", "0x..."]).await?; + ``` + + +*** + +## Onchain Order Info + +When a trade is settled onchain, the Exchange contract emits an `OrderFilled` event with the following fields: + +| Field | Description | +| ------------------- | --------------------------------------------------------------------------------------------- | +| `orderHash` | Unique hash for the filled order | +| `maker` | The user who generated the order and source of funds | +| `taker` | The user filling the order, or the Exchange contract if multiple limit orders are filled | +| `makerAssetId` | ID of the asset given out. If `0`, the order is a **BUY** (giving pUSD for outcome tokens) | +| `takerAssetId` | ID of the asset received. If `0`, the order is a **SELL** (receiving pUSD for outcome tokens) | +| `makerAmountFilled` | Amount of the asset given out | +| `takerAmountFilled` | Amount of the asset received | +| `fee` | Fees paid by the order maker | + +*** + +## Error Messages + +When placing an order, the response may include an `errorMsg` if the order could not be placed. If `success` is `false`, there was a server-side error: + +| Error | Description | +| ---------------------------------- | ------------------------------------------------------ | +| `INVALID_ORDER_MIN_TICK_SIZE` | Price doesn't conform to the market's tick size | +| `INVALID_ORDER_MIN_SIZE` | Order size is below the minimum threshold | +| `INVALID_ORDER_DUPLICATED` | Identical order has already been placed | +| `INVALID_ORDER_NOT_ENOUGH_BALANCE` | Funder doesn't have sufficient balance or allowance | +| `INVALID_ORDER_EXPIRATION` | Expiration timestamp is in the past | +| `INVALID_ORDER_ERROR` | System error while inserting order | +| `INVALID_POST_ONLY_ORDER_TYPE` | Post-only flag used with a market order type (FOK/FAK) | +| `INVALID_POST_ONLY_ORDER` | Post-only order would cross the book | +| `EXECUTION_ERROR` | System error while executing trade | +| `ORDER_DELAYED` | Order placement delayed due to market conditions | +| `DELAYING_ORDER_ERROR` | System error while delaying order | +| `FOK_ORDER_NOT_FILLED_ERROR` | FOK order couldn't be fully filled | +| `MARKET_NOT_READY` | Market is not yet accepting orders | + +### Insert Statuses + +When an order is successfully placed, the response includes a `status` field: + +| Status | Description | +| ----------- | -------------------------------------------------------------------- | +| `matched` | Order placed and matched with a resting order | +| `live` | Order placed and resting on the book | +| `delayed` | Order is marketable but subject to a matching delay | +| `unmatched` | Order is marketable but failed to delay — placement still successful | + +*** + +## Security + +Polymarket's Exchange contract has been audited by Chainsecurity ([View Audit](https://github.com/Polymarket/ctf-exchange/blob/main/audit/ChainSecurity_Polymarket_Exchange_audit.pdf)). + +The operator's privileges are limited to order matching and ensuring correct ordering. Operators cannot set prices or execute unauthorized trades. + +*** + +## Next Steps + + + + Build, sign, and submit orders + + + + Cancel single, multiple, or all orders + + diff --git a/PolymarketDocumentation-main/docs/developers/CLOB/orders/create-order-batch.md b/PolymarketDocumentation-main/docs/developers/CLOB/orders/create-order-batch.md new file mode 100644 index 00000000..7b25901c --- /dev/null +++ b/PolymarketDocumentation-main/docs/developers/CLOB/orders/create-order-batch.md @@ -0,0 +1,706 @@ +> ## Documentation Index +> Fetch the complete documentation index at: https://docs.polymarket.com/llms.txt +> Use this file to discover all available pages before exploring further. + +# Create Order + +> Build, sign, and submit orders + +All orders on Polymarket are expressed as **limit orders**. Market orders are supported by submitting a limit order with a marketable price — your order executes immediately at the best available price on the book. + + + The SDK handles EIP-712 signing and submission for you. If you prefer the REST + API directly, see [Authentication](/api-reference/authentication) for + constructing the required headers and the [API + Reference](/api-reference/introduction) for full endpoint documentation + including the raw order object fields and request/response schemas. + + +*** + +## Order Types + +| Type | Behavior | Use Case | +| ------- | -------------------------------------------------------------------- | ------------------------------- | +| **GTC** | Good-Til-Cancelled — rests on the book until filled or cancelled | Default for limit orders | +| **GTD** | Good-Til-Date — active until a specified expiration time | Auto-expire before known events | +| **FOK** | Fill-Or-Kill — must fill immediately and entirely, or cancel | All-or-nothing market orders | +| **FAK** | Fill-And-Kill — fills what's available immediately, cancels the rest | Partial-fill market orders | + +* **GTC** and **GTD** are limit order types — they rest on the book at your specified price. +* **FOK** and **FAK** are market order types — they execute against resting liquidity immediately. + * **BUY**: specify the dollar amount you want to spend + * **SELL**: specify the number of shares you want to sell + +*** + +## Limit Orders + +The simplest way to place a limit order — create, sign, and submit in one call: + + + ```typescript TypeScript theme={null} + import { ClobClient, Side, OrderType } from "@polymarket/clob-client-v2"; + + const response = await client.createAndPostOrder( + { + tokenID: "TOKEN_ID", + price: 0.5, + size: 10, + side: Side.BUY, + }, + { + tickSize: "0.01", + negRisk: false, + }, + OrderType.GTC, + ); + + console.log("Order ID:", response.orderID); + console.log("Status:", response.status); + ``` + + ```python Python theme={null} + from py_clob_client_v2 import OrderArgs, OrderType, PartialCreateOrderOptions + from py_clob_client_v2.order_builder.constants import BUY + + response = client.create_and_post_order( + OrderArgs( + token_id="TOKEN_ID", + price=0.50, + size=10, + side=BUY, + ), + options=PartialCreateOrderOptions(tick_size="0.01", neg_risk=False), + order_type=OrderType.GTC + ) + + print("Order ID:", response["orderID"]) + print("Status:", response["status"]) + ``` + + ```rust Rust theme={null} + use polymarket_client_sdk_v2::clob::types::Side; + use polymarket_client_sdk_v2::types::dec; + + let token_id = "TOKEN_ID".parse()?; + let order = client + .limit_order() + .token_id(token_id) + .price(dec!(0.50)) + .size(dec!(10)) + .side(Side::Buy) + .build() + .await?; + let signed = client.sign(&signer, order).await?; + let response = client.post_order(signed).await?; + + println!("Order ID: {}", response.order_id); + println!("Status: {:?}", response.status); + ``` + + +### Two-Step Sign Then Submit + +For more control, you can separate signing from submission. This is useful for batch orders or custom submission logic: + + + ```typescript TypeScript theme={null} + // Step 1: Create and sign locally + const signedOrder = await client.createOrder( + { + tokenID: "TOKEN_ID", + price: 0.5, + size: 10, + side: Side.BUY, + }, + { tickSize: "0.01", negRisk: false }, + ); + + // Step 2: Submit to the CLOB + const response = await client.postOrder(signedOrder, OrderType.GTC); + ``` + + ```python Python theme={null} + # Step 1: Create and sign locally + signed_order = client.create_order( + OrderArgs( + token_id="TOKEN_ID", + price=0.50, + size=10, + side=BUY, + ), + options=PartialCreateOrderOptions(tick_size="0.01", neg_risk=False) + ) + + # Step 2: Submit to the CLOB + response = client.post_order(signed_order, OrderType.GTC) + ``` + + ```rust Rust theme={null} + // Step 1: Create order (auto-fetches tick size, neg risk, fee rate) + let order = client + .limit_order() + .token_id("TOKEN_ID".parse()?) + .price(dec!(0.50)) + .size(dec!(10)) + .side(Side::Buy) + .build() + .await?; + + // Step 2: Sign and submit separately + let signed = client.sign(&signer, order).await?; + let response = client.post_order(signed).await?; + ``` + + +*** + +## GTD Orders + +GTD orders auto-expire at a specified time. Useful for quoting around known events. + + + ```typescript TypeScript theme={null} + // Expire in 1 hour (+ 60s security threshold buffer) + const expiration = Math.floor(Date.now() / 1000) + 60 + 3600; + + const response = await client.createAndPostOrder( + { + tokenID: "TOKEN_ID", + price: 0.5, + size: 10, + side: Side.BUY, + expiration, + }, + { tickSize: "0.01", negRisk: false }, + OrderType.GTD, + ); + ``` + + ```python Python theme={null} + import time + + # Expire in 1 hour (+ 60s security threshold buffer) + expiration = int(time.time()) + 60 + 3600 + + response = client.create_and_post_order( + OrderArgs( + token_id="TOKEN_ID", + price=0.50, + size=10, + side=BUY, + expiration=expiration, + ), + options=PartialCreateOrderOptions(tick_size="0.01", neg_risk=False), + order_type=OrderType.GTD + ) + ``` + + ```rust Rust theme={null} + use chrono::{TimeDelta, Utc}; + use polymarket_client_sdk_v2::clob::types::OrderType; + + let order = client + .limit_order() + .token_id("TOKEN_ID".parse()?) + .price(dec!(0.50)) + .size(dec!(10)) + .side(Side::Buy) + .order_type(OrderType::GTD) + .expiration(Utc::now() + TimeDelta::minutes(1) + TimeDelta::hours(1)) + .build() + .await?; + let signed = client.sign(&signer, order).await?; + let response = client.post_order(signed).await?; + ``` + + + + GTD orders expire one minute before their stated expiration as a security + threshold. To set an effective lifetime of N seconds, use `now + 60 + N`. + In addition, the expiration must be at least three minutes in the future — + orders expiring sooner are rejected — so the minimum effective lifetime is + about two minutes. + + +*** + +## Market Orders + +Market orders execute immediately against resting liquidity using FOK or FAK types: + + + ```typescript TypeScript theme={null} + import { Side, OrderType } from "@polymarket/clob-client-v2"; + + // FOK BUY: spend exactly $100 or cancel entirely + const buyOrder = await client.createMarketOrder( + { + tokenID: "TOKEN_ID", + side: Side.BUY, + amount: 100, // dollar amount + price: 0.5, // worst-price limit (slippage protection) + }, + { tickSize: "0.01", negRisk: false }, + ); + await client.postOrder(buyOrder, OrderType.FOK); + + // FOK SELL: sell exactly 200 shares or cancel entirely + const sellOrder = await client.createMarketOrder( + { + tokenID: "TOKEN_ID", + side: Side.SELL, + amount: 200, // number of shares + price: 0.45, // worst-price limit (slippage protection) + }, + { tickSize: "0.01", negRisk: false }, + ); + await client.postOrder(sellOrder, OrderType.FOK); + ``` + + ```python Python theme={null} + from py_clob_client_v2.order_builder.constants import BUY, SELL + from py_clob_client_v2 import MarketOrderArgs, OrderType, PartialCreateOrderOptions + + # FOK BUY: spend exactly $100 or cancel entirely + buy_order = client.create_market_order( + order_args=MarketOrderArgs( + token_id="TOKEN_ID", + side=BUY, + amount=100, # dollar amount + price=0.50, # worst-price limit (slippage protection) + ), + options=PartialCreateOrderOptions(tick_size="0.01", neg_risk=False), + ) + client.post_order(buy_order, OrderType.FOK) + + # FOK SELL: sell exactly 200 shares or cancel entirely + sell_order = client.create_market_order( + order_args=MarketOrderArgs( + token_id="TOKEN_ID", + side=SELL, + amount=200, # number of shares + price=0.45, # worst-price limit (slippage protection) + ), + options=PartialCreateOrderOptions(tick_size="0.01", neg_risk=False), + ) + client.post_order(sell_order, OrderType.FOK) + ``` + + ```rust Rust theme={null} + use polymarket_client_sdk_v2::clob::types::{Amount, OrderType, Side}; + + let token_id = "TOKEN_ID".parse()?; + + // FOK BUY: spend exactly $100 or cancel entirely + let buy = client + .market_order() + .token_id(token_id) + .amount(Amount::usdc(dec!(100))?) + .price(dec!(0.50)) // worst-price limit (slippage protection) + .side(Side::Buy) + .order_type(OrderType::FOK) + .build() + .await?; + let signed = client.sign(&signer, buy).await?; + client.post_order(signed).await?; + + // FOK SELL: sell exactly 200 shares or cancel entirely + let sell = client + .market_order() + .token_id(token_id) + .amount(Amount::shares(dec!(200))?) + .price(dec!(0.45)) // worst-price limit (slippage protection) + .side(Side::Sell) + .order_type(OrderType::FOK) + .build() + .await?; + let signed = client.sign(&signer, sell).await?; + client.post_order(signed).await?; + ``` + + +* **FOK** — fill entirely or cancel the whole order +* **FAK** — fill what's available, cancel the rest + +The `price` field on market orders acts as a **worst-price limit** (slippage protection), not a target execution price. + +### One-Step Market Order + +For convenience, `createAndPostMarketOrder` handles creation, signing, and submission in one call: + + + ```typescript TypeScript theme={null} + const response = await client.createAndPostMarketOrder( + { + tokenID: "TOKEN_ID", + side: Side.BUY, + amount: 100, + price: 0.5, + }, + { tickSize: "0.01", negRisk: false }, + OrderType.FOK, + ); + ``` + + ```python Python theme={null} + from py_clob_client_v2 import MarketOrderArgs, OrderType, PartialCreateOrderOptions + from py_clob_client_v2.order_builder.constants import BUY + + response = client.create_and_post_market_order( + order_args=MarketOrderArgs( + token_id="TOKEN_ID", + side=BUY, + amount=100, + price=0.50, + ), + options=PartialCreateOrderOptions(tick_size="0.01", neg_risk=False), + order_type=OrderType.FOK, + ) + ``` + + ```rust Rust theme={null} + let order = client + .market_order() + .token_id("TOKEN_ID".parse()?) + .amount(Amount::usdc(dec!(100))?) + .price(dec!(0.50)) + .side(Side::Buy) + .order_type(OrderType::FOK) + .build() + .await?; + let signed = client.sign(&signer, order).await?; + let response = client.post_order(signed).await?; + ``` + + +*** + +## Post-Only Orders + +Post-only orders guarantee you're always the maker. If the order would match immediately (cross the spread), it's rejected instead of executed. + + + ```typescript TypeScript theme={null} + const response = await client.postOrder(signedOrder, OrderType.GTC, true); + ``` + + ```python Python theme={null} + response = client.post_order(signed_order, OrderType.GTC, post_only=True) + ``` + + ```rust Rust theme={null} + let order = client + .limit_order() + .token_id("TOKEN_ID".parse()?) + .price(dec!(0.50)) + .size(dec!(10)) + .side(Side::Buy) + .post_only(true) + .build() + .await?; + let signed = client.sign(&signer, order).await?; + let response = client.post_order(signed).await?; + ``` + + +* Only works with **GTC** and **GTD** order types +* Rejected if combined with FOK or FAK + +*** + +## Batch Orders + +Place up to **15 orders** in a single request: + + + ```typescript TypeScript theme={null} + import { OrderType, Side, PostOrdersArgs } from "@polymarket/clob-client-v2"; + + const orders: PostOrdersArgs[] = [ + { + order: await client.createOrder( + { + tokenID: "TOKEN_ID", + price: 0.48, + side: Side.BUY, + size: 500, + }, + { tickSize: "0.01", negRisk: false }, + ), + orderType: OrderType.GTC, + }, + { + order: await client.createOrder( + { + tokenID: "TOKEN_ID", + price: 0.52, + side: Side.SELL, + size: 500, + }, + { tickSize: "0.01", negRisk: false }, + ), + orderType: OrderType.GTC, + }, + ]; + + const response = await client.postOrders(orders); + ``` + + ```python Python theme={null} + from py_clob_client_v2 import OrderArgs, OrderType, PostOrdersV2Args, PartialCreateOrderOptions + from py_clob_client_v2.order_builder.constants import BUY, SELL + + response = client.post_orders([ + PostOrdersV2Args( + order=client.create_order(OrderArgs( + price=0.48, + size=500, + side=BUY, + token_id="TOKEN_ID", + ), options=PartialCreateOrderOptions(tick_size="0.01", neg_risk=False)), + orderType=OrderType.GTC, + ), + PostOrdersV2Args( + order=client.create_order(OrderArgs( + price=0.52, + size=500, + side=SELL, + token_id="TOKEN_ID", + ), options=PartialCreateOrderOptions(tick_size="0.01", neg_risk=False)), + orderType=OrderType.GTC, + ), + ]) + ``` + + ```rust Rust theme={null} + let token_id = "TOKEN_ID".parse()?; + + let bid = client + .limit_order() + .token_id(token_id) + .price(dec!(0.48)) + .size(dec!(500)) + .side(Side::Buy) + .build() + .await?; + let ask = client + .limit_order() + .token_id(token_id) + .price(dec!(0.52)) + .size(dec!(500)) + .side(Side::Sell) + .build() + .await?; + + let signed_bid = client.sign(&signer, bid).await?; + let signed_ask = client.sign(&signer, ask).await?; + let response = client.post_orders(vec![signed_bid, signed_ask]).await?; + ``` + + +*** + +## Order Options + +Every order requires two market-specific options: `tickSize` and `negRisk`. For +details on signature types (`0` = EOA, `1` = POLY\_PROXY, `2` = GNOSIS\_SAFE, +`3` = POLY\_1271 deposit wallet), see +[Authentication](/api-reference/authentication#signature-types-and-funder). + +### Tick Sizes + +Your order price must conform to the market's tick size, or the order is rejected. + +| Tick Size | Precision | Example Prices | +| --------- | ----------- | ---------------------- | +| `0.1` | 1 decimal | 0.1, 0.2, 0.5 | +| `0.01` | 2 decimals | 0.01, 0.50, 0.99 | +| `0.001` | 3 decimals | 0.001, 0.500, 0.999 | +| `0.0001` | 4 decimals | 0.0001, 0.5000, 0.9999 | +| `0.0025` | 0.25¢ steps | 0.0025, 0.5000, 0.9975 | + + + The `0.0025` (0.25¢) tick size applies only to World Cup *to advance*, *moneyline*, *spreads*, and *totals* markets. Always fetch the market's tick size before quoting rather than assuming a value. + + + + ```typescript TypeScript theme={null} + const tickSize = await client.getTickSize("TOKEN_ID"); + ``` + + ```python Python theme={null} + tick_size = client.get_tick_size("TOKEN_ID") + ``` + + ```rust Rust theme={null} + let token_id = "TOKEN_ID".parse()?; + let tick_size = client.tick_size(token_id).await?; + ``` + + +### Negative Risk + +Multi-outcome events (3+ outcomes) use the Neg Risk CTF Exchange. Pass `negRisk: true` for these markets. + + + ```typescript TypeScript theme={null} + const isNegRisk = await client.getNegRisk("TOKEN_ID"); + ``` + + ```python Python theme={null} + is_neg_risk = client.get_neg_risk("TOKEN_ID") + ``` + + ```rust Rust theme={null} + let token_id = "TOKEN_ID".parse()?; + let is_neg_risk = client.neg_risk(token_id).await?; + ``` + + + + Both values are also available on the market object: `minimum_tick_size` and + `neg_risk`. In Rust, the order builder auto-fetches both — you don't need to + look them up manually. + + +*** + +## Prerequisites + +Before placing an order, your funder address must have approved the Exchange contract to spend the relevant tokens: + +* **BUY orders**: pUSD allowance >= spending amount +* **SELL orders**: conditional token allowance >= selling amount + +Order size is limited by your available balance minus amounts reserved by existing open orders: + +$$ +\text{maxOrderSize} = \text{balance} - \sum(\text{openOrderSize} - \text{filledAmount}) +$$ + + + Orders are continuously monitored for validity — balances and allowances are + tracked in real time. Any maker caught intentionally abusing these checks will + be blacklisted. + + +### Sports Markets + +Sports markets have additional behaviors: + +* Outstanding limit orders are **automatically cancelled** once the game begins, clearing the entire order book at the official start time +* Marketable orders have a **1-second placement delay** before matching +* Game start times can shift — monitor your orders closely, as they may not be cleared if the start time changes unexpectedly + +*** + +## Response + +A successful order placement returns: + +```json theme={null} +{ + "success": true, + "errorMsg": "", + "orderID": "0xabc123...", + "takingAmount": "", + "makingAmount": "", + "status": "live", + "transactionsHashes": [], + "tradeIDs": [] +} +``` + +### Statuses + +| Status | Description | +| ----------- | ------------------------------------------------------------- | +| `live` | Order resting on the book | +| `matched` | Order matched immediately with a resting order | +| `delayed` | Marketable order accepted into an asynchronous matching delay | +| `unmatched` | Marketable but failed to delay — placement still successful | + + + Selected crypto and finance up/down markets apply a 250 ms taker delay to + marketable orders. To check a specific market, call `GET + https://clob.polymarket.com/clob-markets/{condition_id}` or SDK + `getClobMarketInfo(conditionID)` and look for `itode: true`. The API waits for + this short hold and returns the final order result, so these orders usually + return `matched`, `live`, or `unmatched` rather than `delayed`. Orders cannot + be canceled while they are pending in the delay window. + + +### Error Messages + +| Error | Description | +| ---------------------------------- | ----------------------------------------------- | +| `INVALID_ORDER_MIN_TICK_SIZE` | Price doesn't conform to the market's tick size | +| `INVALID_ORDER_MIN_SIZE` | Order size below the minimum threshold | +| `INVALID_ORDER_DUPLICATED` | Identical order already placed | +| `INVALID_ORDER_NOT_ENOUGH_BALANCE` | Insufficient balance or allowance | +| `INVALID_ORDER_EXPIRATION` | Expiration timestamp is in the past | +| `INVALID_POST_ONLY_ORDER_TYPE` | Post-only used with FOK/FAK | +| `INVALID_POST_ONLY_ORDER` | Post-only order would cross the book | +| `FOK_ORDER_NOT_FILLED_ERROR` | FOK order couldn't be fully filled | +| `INVALID_ORDER_ERROR` | System error inserting the order | +| `EXECUTION_ERROR` | System error executing the trade | +| `ORDER_DELAYED` | Order match delayed due to market conditions | +| `DELAYING_ORDER_ERROR` | System error while delaying the order | +| `MARKET_NOT_READY` | Market not yet accepting orders | + +*** + +## Heartbeat + +The heartbeat endpoint maintains session liveness. If a valid heartbeat is not received within **10 seconds** (with a 5-second buffer), **all open orders are cancelled**. + + + ```typescript TypeScript theme={null} + let heartbeatId = ""; + setInterval(async () => { + const resp = await client.postHeartbeat(heartbeatId); + heartbeatId = resp.heartbeat_id; + }, 5000); + ``` + + ```python Python theme={null} + import time + + heartbeat_id = "" + while True: + resp = client.post_heartbeat(heartbeat_id) + heartbeat_id = resp["heartbeat_id"] + time.sleep(5) + ``` + + ```rust Rust theme={null} + // With the `heartbeats` feature, the Rust SDK can auto-send heartbeats + // in a background task — no manual loop needed: + Client::start_heartbeats(&mut client)?; + // ... your trading logic ... + client.stop_heartbeats().await?; + + // Or send manually: + let resp = client.post_heartbeat(None).await?; // None for first call + let resp = client.post_heartbeat(Some(resp.heartbeat_id)).await?; + ``` + + +* Include the most recent `heartbeat_id` in each request. Use an empty string for the first request. +* If you send an expired ID, the server responds with `400` and the correct ID. Update and retry. + +*** + +## Next Steps + + + + Cancel single, multiple, or all open orders + + + + Attribute orders to your builder account for volume credit + + diff --git a/PolymarketDocumentation-main/docs/developers/CLOB/orders/create-order.md b/PolymarketDocumentation-main/docs/developers/CLOB/orders/create-order.md new file mode 100644 index 00000000..7b25901c --- /dev/null +++ b/PolymarketDocumentation-main/docs/developers/CLOB/orders/create-order.md @@ -0,0 +1,706 @@ +> ## Documentation Index +> Fetch the complete documentation index at: https://docs.polymarket.com/llms.txt +> Use this file to discover all available pages before exploring further. + +# Create Order + +> Build, sign, and submit orders + +All orders on Polymarket are expressed as **limit orders**. Market orders are supported by submitting a limit order with a marketable price — your order executes immediately at the best available price on the book. + + + The SDK handles EIP-712 signing and submission for you. If you prefer the REST + API directly, see [Authentication](/api-reference/authentication) for + constructing the required headers and the [API + Reference](/api-reference/introduction) for full endpoint documentation + including the raw order object fields and request/response schemas. + + +*** + +## Order Types + +| Type | Behavior | Use Case | +| ------- | -------------------------------------------------------------------- | ------------------------------- | +| **GTC** | Good-Til-Cancelled — rests on the book until filled or cancelled | Default for limit orders | +| **GTD** | Good-Til-Date — active until a specified expiration time | Auto-expire before known events | +| **FOK** | Fill-Or-Kill — must fill immediately and entirely, or cancel | All-or-nothing market orders | +| **FAK** | Fill-And-Kill — fills what's available immediately, cancels the rest | Partial-fill market orders | + +* **GTC** and **GTD** are limit order types — they rest on the book at your specified price. +* **FOK** and **FAK** are market order types — they execute against resting liquidity immediately. + * **BUY**: specify the dollar amount you want to spend + * **SELL**: specify the number of shares you want to sell + +*** + +## Limit Orders + +The simplest way to place a limit order — create, sign, and submit in one call: + + + ```typescript TypeScript theme={null} + import { ClobClient, Side, OrderType } from "@polymarket/clob-client-v2"; + + const response = await client.createAndPostOrder( + { + tokenID: "TOKEN_ID", + price: 0.5, + size: 10, + side: Side.BUY, + }, + { + tickSize: "0.01", + negRisk: false, + }, + OrderType.GTC, + ); + + console.log("Order ID:", response.orderID); + console.log("Status:", response.status); + ``` + + ```python Python theme={null} + from py_clob_client_v2 import OrderArgs, OrderType, PartialCreateOrderOptions + from py_clob_client_v2.order_builder.constants import BUY + + response = client.create_and_post_order( + OrderArgs( + token_id="TOKEN_ID", + price=0.50, + size=10, + side=BUY, + ), + options=PartialCreateOrderOptions(tick_size="0.01", neg_risk=False), + order_type=OrderType.GTC + ) + + print("Order ID:", response["orderID"]) + print("Status:", response["status"]) + ``` + + ```rust Rust theme={null} + use polymarket_client_sdk_v2::clob::types::Side; + use polymarket_client_sdk_v2::types::dec; + + let token_id = "TOKEN_ID".parse()?; + let order = client + .limit_order() + .token_id(token_id) + .price(dec!(0.50)) + .size(dec!(10)) + .side(Side::Buy) + .build() + .await?; + let signed = client.sign(&signer, order).await?; + let response = client.post_order(signed).await?; + + println!("Order ID: {}", response.order_id); + println!("Status: {:?}", response.status); + ``` + + +### Two-Step Sign Then Submit + +For more control, you can separate signing from submission. This is useful for batch orders or custom submission logic: + + + ```typescript TypeScript theme={null} + // Step 1: Create and sign locally + const signedOrder = await client.createOrder( + { + tokenID: "TOKEN_ID", + price: 0.5, + size: 10, + side: Side.BUY, + }, + { tickSize: "0.01", negRisk: false }, + ); + + // Step 2: Submit to the CLOB + const response = await client.postOrder(signedOrder, OrderType.GTC); + ``` + + ```python Python theme={null} + # Step 1: Create and sign locally + signed_order = client.create_order( + OrderArgs( + token_id="TOKEN_ID", + price=0.50, + size=10, + side=BUY, + ), + options=PartialCreateOrderOptions(tick_size="0.01", neg_risk=False) + ) + + # Step 2: Submit to the CLOB + response = client.post_order(signed_order, OrderType.GTC) + ``` + + ```rust Rust theme={null} + // Step 1: Create order (auto-fetches tick size, neg risk, fee rate) + let order = client + .limit_order() + .token_id("TOKEN_ID".parse()?) + .price(dec!(0.50)) + .size(dec!(10)) + .side(Side::Buy) + .build() + .await?; + + // Step 2: Sign and submit separately + let signed = client.sign(&signer, order).await?; + let response = client.post_order(signed).await?; + ``` + + +*** + +## GTD Orders + +GTD orders auto-expire at a specified time. Useful for quoting around known events. + + + ```typescript TypeScript theme={null} + // Expire in 1 hour (+ 60s security threshold buffer) + const expiration = Math.floor(Date.now() / 1000) + 60 + 3600; + + const response = await client.createAndPostOrder( + { + tokenID: "TOKEN_ID", + price: 0.5, + size: 10, + side: Side.BUY, + expiration, + }, + { tickSize: "0.01", negRisk: false }, + OrderType.GTD, + ); + ``` + + ```python Python theme={null} + import time + + # Expire in 1 hour (+ 60s security threshold buffer) + expiration = int(time.time()) + 60 + 3600 + + response = client.create_and_post_order( + OrderArgs( + token_id="TOKEN_ID", + price=0.50, + size=10, + side=BUY, + expiration=expiration, + ), + options=PartialCreateOrderOptions(tick_size="0.01", neg_risk=False), + order_type=OrderType.GTD + ) + ``` + + ```rust Rust theme={null} + use chrono::{TimeDelta, Utc}; + use polymarket_client_sdk_v2::clob::types::OrderType; + + let order = client + .limit_order() + .token_id("TOKEN_ID".parse()?) + .price(dec!(0.50)) + .size(dec!(10)) + .side(Side::Buy) + .order_type(OrderType::GTD) + .expiration(Utc::now() + TimeDelta::minutes(1) + TimeDelta::hours(1)) + .build() + .await?; + let signed = client.sign(&signer, order).await?; + let response = client.post_order(signed).await?; + ``` + + + + GTD orders expire one minute before their stated expiration as a security + threshold. To set an effective lifetime of N seconds, use `now + 60 + N`. + In addition, the expiration must be at least three minutes in the future — + orders expiring sooner are rejected — so the minimum effective lifetime is + about two minutes. + + +*** + +## Market Orders + +Market orders execute immediately against resting liquidity using FOK or FAK types: + + + ```typescript TypeScript theme={null} + import { Side, OrderType } from "@polymarket/clob-client-v2"; + + // FOK BUY: spend exactly $100 or cancel entirely + const buyOrder = await client.createMarketOrder( + { + tokenID: "TOKEN_ID", + side: Side.BUY, + amount: 100, // dollar amount + price: 0.5, // worst-price limit (slippage protection) + }, + { tickSize: "0.01", negRisk: false }, + ); + await client.postOrder(buyOrder, OrderType.FOK); + + // FOK SELL: sell exactly 200 shares or cancel entirely + const sellOrder = await client.createMarketOrder( + { + tokenID: "TOKEN_ID", + side: Side.SELL, + amount: 200, // number of shares + price: 0.45, // worst-price limit (slippage protection) + }, + { tickSize: "0.01", negRisk: false }, + ); + await client.postOrder(sellOrder, OrderType.FOK); + ``` + + ```python Python theme={null} + from py_clob_client_v2.order_builder.constants import BUY, SELL + from py_clob_client_v2 import MarketOrderArgs, OrderType, PartialCreateOrderOptions + + # FOK BUY: spend exactly $100 or cancel entirely + buy_order = client.create_market_order( + order_args=MarketOrderArgs( + token_id="TOKEN_ID", + side=BUY, + amount=100, # dollar amount + price=0.50, # worst-price limit (slippage protection) + ), + options=PartialCreateOrderOptions(tick_size="0.01", neg_risk=False), + ) + client.post_order(buy_order, OrderType.FOK) + + # FOK SELL: sell exactly 200 shares or cancel entirely + sell_order = client.create_market_order( + order_args=MarketOrderArgs( + token_id="TOKEN_ID", + side=SELL, + amount=200, # number of shares + price=0.45, # worst-price limit (slippage protection) + ), + options=PartialCreateOrderOptions(tick_size="0.01", neg_risk=False), + ) + client.post_order(sell_order, OrderType.FOK) + ``` + + ```rust Rust theme={null} + use polymarket_client_sdk_v2::clob::types::{Amount, OrderType, Side}; + + let token_id = "TOKEN_ID".parse()?; + + // FOK BUY: spend exactly $100 or cancel entirely + let buy = client + .market_order() + .token_id(token_id) + .amount(Amount::usdc(dec!(100))?) + .price(dec!(0.50)) // worst-price limit (slippage protection) + .side(Side::Buy) + .order_type(OrderType::FOK) + .build() + .await?; + let signed = client.sign(&signer, buy).await?; + client.post_order(signed).await?; + + // FOK SELL: sell exactly 200 shares or cancel entirely + let sell = client + .market_order() + .token_id(token_id) + .amount(Amount::shares(dec!(200))?) + .price(dec!(0.45)) // worst-price limit (slippage protection) + .side(Side::Sell) + .order_type(OrderType::FOK) + .build() + .await?; + let signed = client.sign(&signer, sell).await?; + client.post_order(signed).await?; + ``` + + +* **FOK** — fill entirely or cancel the whole order +* **FAK** — fill what's available, cancel the rest + +The `price` field on market orders acts as a **worst-price limit** (slippage protection), not a target execution price. + +### One-Step Market Order + +For convenience, `createAndPostMarketOrder` handles creation, signing, and submission in one call: + + + ```typescript TypeScript theme={null} + const response = await client.createAndPostMarketOrder( + { + tokenID: "TOKEN_ID", + side: Side.BUY, + amount: 100, + price: 0.5, + }, + { tickSize: "0.01", negRisk: false }, + OrderType.FOK, + ); + ``` + + ```python Python theme={null} + from py_clob_client_v2 import MarketOrderArgs, OrderType, PartialCreateOrderOptions + from py_clob_client_v2.order_builder.constants import BUY + + response = client.create_and_post_market_order( + order_args=MarketOrderArgs( + token_id="TOKEN_ID", + side=BUY, + amount=100, + price=0.50, + ), + options=PartialCreateOrderOptions(tick_size="0.01", neg_risk=False), + order_type=OrderType.FOK, + ) + ``` + + ```rust Rust theme={null} + let order = client + .market_order() + .token_id("TOKEN_ID".parse()?) + .amount(Amount::usdc(dec!(100))?) + .price(dec!(0.50)) + .side(Side::Buy) + .order_type(OrderType::FOK) + .build() + .await?; + let signed = client.sign(&signer, order).await?; + let response = client.post_order(signed).await?; + ``` + + +*** + +## Post-Only Orders + +Post-only orders guarantee you're always the maker. If the order would match immediately (cross the spread), it's rejected instead of executed. + + + ```typescript TypeScript theme={null} + const response = await client.postOrder(signedOrder, OrderType.GTC, true); + ``` + + ```python Python theme={null} + response = client.post_order(signed_order, OrderType.GTC, post_only=True) + ``` + + ```rust Rust theme={null} + let order = client + .limit_order() + .token_id("TOKEN_ID".parse()?) + .price(dec!(0.50)) + .size(dec!(10)) + .side(Side::Buy) + .post_only(true) + .build() + .await?; + let signed = client.sign(&signer, order).await?; + let response = client.post_order(signed).await?; + ``` + + +* Only works with **GTC** and **GTD** order types +* Rejected if combined with FOK or FAK + +*** + +## Batch Orders + +Place up to **15 orders** in a single request: + + + ```typescript TypeScript theme={null} + import { OrderType, Side, PostOrdersArgs } from "@polymarket/clob-client-v2"; + + const orders: PostOrdersArgs[] = [ + { + order: await client.createOrder( + { + tokenID: "TOKEN_ID", + price: 0.48, + side: Side.BUY, + size: 500, + }, + { tickSize: "0.01", negRisk: false }, + ), + orderType: OrderType.GTC, + }, + { + order: await client.createOrder( + { + tokenID: "TOKEN_ID", + price: 0.52, + side: Side.SELL, + size: 500, + }, + { tickSize: "0.01", negRisk: false }, + ), + orderType: OrderType.GTC, + }, + ]; + + const response = await client.postOrders(orders); + ``` + + ```python Python theme={null} + from py_clob_client_v2 import OrderArgs, OrderType, PostOrdersV2Args, PartialCreateOrderOptions + from py_clob_client_v2.order_builder.constants import BUY, SELL + + response = client.post_orders([ + PostOrdersV2Args( + order=client.create_order(OrderArgs( + price=0.48, + size=500, + side=BUY, + token_id="TOKEN_ID", + ), options=PartialCreateOrderOptions(tick_size="0.01", neg_risk=False)), + orderType=OrderType.GTC, + ), + PostOrdersV2Args( + order=client.create_order(OrderArgs( + price=0.52, + size=500, + side=SELL, + token_id="TOKEN_ID", + ), options=PartialCreateOrderOptions(tick_size="0.01", neg_risk=False)), + orderType=OrderType.GTC, + ), + ]) + ``` + + ```rust Rust theme={null} + let token_id = "TOKEN_ID".parse()?; + + let bid = client + .limit_order() + .token_id(token_id) + .price(dec!(0.48)) + .size(dec!(500)) + .side(Side::Buy) + .build() + .await?; + let ask = client + .limit_order() + .token_id(token_id) + .price(dec!(0.52)) + .size(dec!(500)) + .side(Side::Sell) + .build() + .await?; + + let signed_bid = client.sign(&signer, bid).await?; + let signed_ask = client.sign(&signer, ask).await?; + let response = client.post_orders(vec![signed_bid, signed_ask]).await?; + ``` + + +*** + +## Order Options + +Every order requires two market-specific options: `tickSize` and `negRisk`. For +details on signature types (`0` = EOA, `1` = POLY\_PROXY, `2` = GNOSIS\_SAFE, +`3` = POLY\_1271 deposit wallet), see +[Authentication](/api-reference/authentication#signature-types-and-funder). + +### Tick Sizes + +Your order price must conform to the market's tick size, or the order is rejected. + +| Tick Size | Precision | Example Prices | +| --------- | ----------- | ---------------------- | +| `0.1` | 1 decimal | 0.1, 0.2, 0.5 | +| `0.01` | 2 decimals | 0.01, 0.50, 0.99 | +| `0.001` | 3 decimals | 0.001, 0.500, 0.999 | +| `0.0001` | 4 decimals | 0.0001, 0.5000, 0.9999 | +| `0.0025` | 0.25¢ steps | 0.0025, 0.5000, 0.9975 | + + + The `0.0025` (0.25¢) tick size applies only to World Cup *to advance*, *moneyline*, *spreads*, and *totals* markets. Always fetch the market's tick size before quoting rather than assuming a value. + + + + ```typescript TypeScript theme={null} + const tickSize = await client.getTickSize("TOKEN_ID"); + ``` + + ```python Python theme={null} + tick_size = client.get_tick_size("TOKEN_ID") + ``` + + ```rust Rust theme={null} + let token_id = "TOKEN_ID".parse()?; + let tick_size = client.tick_size(token_id).await?; + ``` + + +### Negative Risk + +Multi-outcome events (3+ outcomes) use the Neg Risk CTF Exchange. Pass `negRisk: true` for these markets. + + + ```typescript TypeScript theme={null} + const isNegRisk = await client.getNegRisk("TOKEN_ID"); + ``` + + ```python Python theme={null} + is_neg_risk = client.get_neg_risk("TOKEN_ID") + ``` + + ```rust Rust theme={null} + let token_id = "TOKEN_ID".parse()?; + let is_neg_risk = client.neg_risk(token_id).await?; + ``` + + + + Both values are also available on the market object: `minimum_tick_size` and + `neg_risk`. In Rust, the order builder auto-fetches both — you don't need to + look them up manually. + + +*** + +## Prerequisites + +Before placing an order, your funder address must have approved the Exchange contract to spend the relevant tokens: + +* **BUY orders**: pUSD allowance >= spending amount +* **SELL orders**: conditional token allowance >= selling amount + +Order size is limited by your available balance minus amounts reserved by existing open orders: + +$$ +\text{maxOrderSize} = \text{balance} - \sum(\text{openOrderSize} - \text{filledAmount}) +$$ + + + Orders are continuously monitored for validity — balances and allowances are + tracked in real time. Any maker caught intentionally abusing these checks will + be blacklisted. + + +### Sports Markets + +Sports markets have additional behaviors: + +* Outstanding limit orders are **automatically cancelled** once the game begins, clearing the entire order book at the official start time +* Marketable orders have a **1-second placement delay** before matching +* Game start times can shift — monitor your orders closely, as they may not be cleared if the start time changes unexpectedly + +*** + +## Response + +A successful order placement returns: + +```json theme={null} +{ + "success": true, + "errorMsg": "", + "orderID": "0xabc123...", + "takingAmount": "", + "makingAmount": "", + "status": "live", + "transactionsHashes": [], + "tradeIDs": [] +} +``` + +### Statuses + +| Status | Description | +| ----------- | ------------------------------------------------------------- | +| `live` | Order resting on the book | +| `matched` | Order matched immediately with a resting order | +| `delayed` | Marketable order accepted into an asynchronous matching delay | +| `unmatched` | Marketable but failed to delay — placement still successful | + + + Selected crypto and finance up/down markets apply a 250 ms taker delay to + marketable orders. To check a specific market, call `GET + https://clob.polymarket.com/clob-markets/{condition_id}` or SDK + `getClobMarketInfo(conditionID)` and look for `itode: true`. The API waits for + this short hold and returns the final order result, so these orders usually + return `matched`, `live`, or `unmatched` rather than `delayed`. Orders cannot + be canceled while they are pending in the delay window. + + +### Error Messages + +| Error | Description | +| ---------------------------------- | ----------------------------------------------- | +| `INVALID_ORDER_MIN_TICK_SIZE` | Price doesn't conform to the market's tick size | +| `INVALID_ORDER_MIN_SIZE` | Order size below the minimum threshold | +| `INVALID_ORDER_DUPLICATED` | Identical order already placed | +| `INVALID_ORDER_NOT_ENOUGH_BALANCE` | Insufficient balance or allowance | +| `INVALID_ORDER_EXPIRATION` | Expiration timestamp is in the past | +| `INVALID_POST_ONLY_ORDER_TYPE` | Post-only used with FOK/FAK | +| `INVALID_POST_ONLY_ORDER` | Post-only order would cross the book | +| `FOK_ORDER_NOT_FILLED_ERROR` | FOK order couldn't be fully filled | +| `INVALID_ORDER_ERROR` | System error inserting the order | +| `EXECUTION_ERROR` | System error executing the trade | +| `ORDER_DELAYED` | Order match delayed due to market conditions | +| `DELAYING_ORDER_ERROR` | System error while delaying the order | +| `MARKET_NOT_READY` | Market not yet accepting orders | + +*** + +## Heartbeat + +The heartbeat endpoint maintains session liveness. If a valid heartbeat is not received within **10 seconds** (with a 5-second buffer), **all open orders are cancelled**. + + + ```typescript TypeScript theme={null} + let heartbeatId = ""; + setInterval(async () => { + const resp = await client.postHeartbeat(heartbeatId); + heartbeatId = resp.heartbeat_id; + }, 5000); + ``` + + ```python Python theme={null} + import time + + heartbeat_id = "" + while True: + resp = client.post_heartbeat(heartbeat_id) + heartbeat_id = resp["heartbeat_id"] + time.sleep(5) + ``` + + ```rust Rust theme={null} + // With the `heartbeats` feature, the Rust SDK can auto-send heartbeats + // in a background task — no manual loop needed: + Client::start_heartbeats(&mut client)?; + // ... your trading logic ... + client.stop_heartbeats().await?; + + // Or send manually: + let resp = client.post_heartbeat(None).await?; // None for first call + let resp = client.post_heartbeat(Some(resp.heartbeat_id)).await?; + ``` + + +* Include the most recent `heartbeat_id` in each request. Use an empty string for the first request. +* If you send an expired ID, the server responds with `400` and the correct ID. Update and retry. + +*** + +## Next Steps + + + + Cancel single, multiple, or all open orders + + + + Attribute orders to your builder account for volume credit + + diff --git a/PolymarketDocumentation-main/docs/developers/CLOB/orders/get-active-order.md b/PolymarketDocumentation-main/docs/developers/CLOB/orders/get-active-order.md new file mode 100644 index 00000000..20013388 --- /dev/null +++ b/PolymarketDocumentation-main/docs/developers/CLOB/orders/get-active-order.md @@ -0,0 +1,550 @@ +> ## Documentation Index +> Fetch the complete documentation index at: https://docs.polymarket.com/llms.txt +> Use this file to discover all available pages before exploring further. + +# Overview + +> Order types, tick sizes, and querying orders + +All orders on Polymarket are expressed as **limit orders**. Market orders are supported by submitting a limit order with a marketable price — your order executes immediately at the best available price on the book. + +The underlying order primitive is structured, hashed, and signed using the [EIP-712](https://eips.ethereum.org/EIPS/eip-712) standard, then executed onchain via the Exchange contract. Preparing orders manually is involved, so we recommend using the open-source [TypeScript](https://github.com/Polymarket/clob-client-v2) or [Python](https://github.com/Polymarket/py-clob-client-v2) SDK clients, which handle signing and submission for you. + + + If you prefer to use the REST API directly, you'll need to manage order + signing yourself. See [Authentication](/api-reference/authentication) for details on + constructing the required headers. + + +*** + +## Order Types + +| Type | Behavior | Use Case | +| ---------------------------- | -------------------------------------------------------------------------------------------------- | -------------------------------------- | +| **GTC** (Good-Til-Cancelled) | Rests on the book until filled or cancelled | Default for passive limit orders | +| **GTD** (Good-Til-Date) | Active until a specified expiration time (UTC seconds timestamp), unless filled or cancelled first | Auto-expire orders before known events | +| **FOK** (Fill-Or-Kill) | Must be filled immediately and entirely, or the whole order is cancelled | All-or-nothing execution | +| **FAK** (Fill-And-Kill) | Fills as many shares as available immediately, then cancels any unfilled remainder | Partial immediate execution | + +* **FOK** and **FAK** are market order types — they execute against resting liquidity immediately. + * **BUY**: specify the dollar amount you want to spend + * **SELL**: specify the number of shares you want to sell +* **GTC** and **GTD** are limit order types — they rest on the book at your specified price. + + + **GTD expiration**: Orders expire one minute before their stated expiration + as a security threshold, and the expiration must be at least three minutes + in the future. For a 5-minute effective lifetime, the correct expiration + value is `now + 1 minute + 5 minutes`. + + +### Post-Only Orders + +Post-only orders are limit orders that will only rest on the book and not match immediately on entry. + +* If a post-only order would cross the spread (i.e., it is marketable), it will be **rejected** rather than executed. +* Post-only **cannot** be combined with market order types (FOK or FAK). If `postOnly = true` is sent with a market order type, the order will be rejected. +* Post-only can only be used with **GTC** and **GTD** order types. + +*** + +## Tick Sizes + +Markets have different minimum price increments (tick sizes). Your order price must conform to the market's tick size, or the order will be rejected. + +| Tick Size | Price Precision | Example Prices | +| --------- | --------------- | ---------------------- | +| `0.1` | 1 decimal | 0.1, 0.2, 0.5 | +| `0.01` | 2 decimals | 0.01, 0.50, 0.99 | +| `0.001` | 3 decimals | 0.001, 0.500, 0.999 | +| `0.0001` | 4 decimals | 0.0001, 0.5000, 0.9999 | +| `0.0025` | 0.25¢ steps | 0.0025, 0.5000, 0.9975 | + + + The `0.0025` (0.25¢) tick size applies only to World Cup *to advance*, *moneyline*, *spreads*, and *totals* markets. Always fetch the market's tick size before quoting rather than assuming a value. + + +Retrieve the tick size for a market using the SDK: + + + ```typescript TypeScript theme={null} + const tickSize = await client.getTickSize(tokenID); + // Returns: "0.1" | "0.01" | "0.001" | "0.0001" + ``` + + ```python Python theme={null} + tick_size = client.get_tick_size(token_id) + # Returns: "0.1" | "0.01" | "0.001" | "0.0001" + ``` + + ```rust Rust theme={null} + let resp = client.tick_size(token_id).await?; + // resp.minimum_tick_size: TickSize::Tenth | Hundredth | Thousandth | TenThousandth + ``` + + + + You can also check the `minimum_tick_size` field on a market object returned + by the [Markets API](/market-data/fetching-markets). + + +*** + +## Negative Risk + +Multi-outcome events (e.g., "Who will win the election?" with 3+ candidates) use a different exchange contract called the **Neg Risk CTF Exchange**. When placing orders on these markets, you must pass `negRisk: true` in the order options. + + + ```typescript TypeScript theme={null} + const response = await client.createAndPostOrder( + { + tokenID: "TOKEN_ID", + price: 0.5, + size: 10, + side: Side.BUY, + }, + { + tickSize: "0.01", + negRisk: true, // Required for multi-outcome markets + }, + ); + ``` + + ```python Python theme={null} + from py_clob_client_v2 import OrderArgs, PartialCreateOrderOptions + from py_clob_client_v2.order_builder.constants import BUY + + response = client.create_and_post_order( + OrderArgs( + token_id="TOKEN_ID", + price=0.50, + size=10, + side=BUY, + ), + options=PartialCreateOrderOptions( + tick_size="0.01", + neg_risk=True, # Required for multi-outcome markets + ) + ) + ``` + + ```rust Rust theme={null} + // The Rust SDK auto-detects neg risk from the token ID — no flag needed. + // The order builder fetches neg_risk and uses the correct exchange contract. + let order = client + .limit_order() + .token_id("TOKEN_ID".parse()?) + .price(dec!(0.50)) + .size(dec!(10)) + .side(Side::Buy) + .build() + .await?; + let signed = client.sign(&signer, order).await?; + let response = client.post_order(signed).await?; + ``` + + +You can check whether a market uses negative risk via the SDK or the market object's `neg_risk` field: + + + ```typescript TypeScript theme={null} + const isNegRisk = await client.getNegRisk(tokenID); + ``` + + ```python Python theme={null} + is_neg_risk = client.get_neg_risk(token_id) + ``` + + ```rust Rust theme={null} + let is_neg_risk = client.neg_risk(token_id).await?; + ``` + + +*** + +## Allowances + +Before placing an order, your funder address must have approved the Exchange contract to spend the relevant tokens: + +* **Buying**: the funder must have set a **pUSD** allowance greater than or equal to the spending amount. +* **Selling**: the funder must have set a **conditional token** allowance greater than or equal to the selling amount. + +This allows the Exchange contract to execute settlement according to your signed order instructions. + +*** + +## Validity Checks + +Orders are continually monitored to make sure they remain valid. This includes tracking: + +* Underlying balances +* Allowances + + + Any maker caught intentionally abusing these checks will be blacklisted. + + +There are also limits on order placement per market. You can only place orders that sum to less than or equal to your available balance for each market. For example, if you have 500 pUSD in your funding wallet, you can place one order to buy 1000 YES at \$0.50 — but any additional buy orders in that market will be rejected since your entire balance is reserved for the first order. + +The max size you can place for an order is: + +$$ +\text{maxOrderSize} = \text{underlyingAssetBalance} - \sum(\text{orderSize} - \text{orderFillAmount}) +$$ + +*** + +## Querying Orders + +All query endpoints require [L2 authentication](/api-reference/authentication). [Builder-authenticated](/trading/clients/builder) clients can also query orders attributed to their builder account using the same methods. + +### Get a Single Order + +Retrieve details for a specific order by its ID: + + + ```typescript TypeScript theme={null} + const order = await client.getOrder("0xb816482a..."); + console.log(order); + ``` + + ```python Python theme={null} + order = client.get_order("0xb816482a...") + print(order) + ``` + + ```rust Rust theme={null} + let order = client.order("0xb816482a...").await?; + println!("{order:?}"); + ``` + + +### Get Open Orders + +Retrieve your open orders, optionally filtered by market or asset: + + + ```typescript TypeScript theme={null} + // All open orders + const orders = await client.getOpenOrders(); + + // Filtered by market + const marketOrders = await client.getOpenOrders({ + market: "0xbd31dc8a...", + }); + + // Filtered by asset + const assetOrders = await client.getOpenOrders({ + asset_id: "52114319501245...", + }); + ``` + + ```python Python theme={null} + from py_clob_client_v2 import OpenOrderParams + + # All open orders + orders = client.get_orders() + + # Filtered by market + market_orders = client.get_orders( + OpenOrderParams( + market="0xbd31dc8a...", + ) + ) + ``` + + ```rust Rust theme={null} + use polymarket_client_sdk_v2::clob::types::request::OrdersRequest; + + // All open orders + let orders = client.orders(&OrdersRequest::default(), None).await?; + + // Filtered by market + let request = OrdersRequest::builder() + .market("0xbd31dc8a...".parse()?) + .build(); + let market_orders = client.orders(&request, None).await?; + + // Filtered by asset + let request = OrdersRequest::builder() + .asset_id("52114319501245...".parse()?) + .build(); + let asset_orders = client.orders(&request, None).await?; + ``` + + +### OpenOrder Object + +Each order returned contains these fields: + +| Field | Type | Description | +| ------------------ | --------- | ------------------------------------------------------------ | +| `id` | string | Order ID | +| `status` | string | Current order status | +| `market` | string | Market ID (condition ID) | +| `asset_id` | string | Token ID | +| `side` | string | `BUY` or `SELL` | +| `original_size` | string | Original order size at placement | +| `size_matched` | string | Amount that has been filled | +| `price` | string | Limit price | +| `outcome` | string | Human-readable outcome (e.g., "Yes", "No") | +| `order_type` | string | Order type (GTC, GTD, FOK, FAK) | +| `maker_address` | string | Funder address | +| `owner` | string | API key of the order owner | +| `expiration` | string | Unix timestamp when the order expires (`0` if no expiration) | +| `associate_trades` | string\[] | Trade IDs this order has been partially included in | +| `created_at` | string | Unix timestamp when the order was created | + +*** + +## Trade History + +When an order is matched, it creates a trade. Trades go through the following statuses: + +| Status | Terminal? | Description | +| ----------- | --------- | -------------------------------------------------------------------- | +| `MATCHED` | No | Matched and sent to the executor service for onchain submission | +| `MINED` | No | Observed as mined on the chain, no finality threshold yet | +| `CONFIRMED` | Yes | Achieved strong probabilistic finality — trade successful | +| `RETRYING` | No | Transaction failed (revert or reorg) — being retried by the operator | +| `FAILED` | Yes | Trade failed permanently and is not being retried | + +### Trade Object + +Each trade contains these fields: + +| Field | Type | Description | +| ------------------ | ------ | ------------------------------------------------------------ | +| `id` | string | Trade ID | +| `taker_order_id` | string | Taker order ID (hash) | +| `market` | string | Market ID (condition ID) | +| `asset_id` | string | Token ID | +| `side` | string | `BUY` or `SELL` | +| `size` | string | Trade size | +| `fee_rate_bps` | string | Fee rate in basis points | +| `price` | string | Trade price | +| `status` | string | Trade status (see table above) | +| `match_time` | string | Unix timestamp when the trade was matched | +| `last_update` | string | Unix timestamp of last status update | +| `outcome` | string | Human-readable outcome (e.g., "Yes", "No") | +| `owner` | string | API key ID of the trade owner | +| `maker_address` | string | Funder address | +| `trader_side` | string | Whether you were `TAKER` or `MAKER` in this trade | +| `transaction_hash` | string | Onchain transaction hash (available after mining) | +| `maker_orders` | array | Array of maker orders matched against this trade (see below) | + +### MakerOrder Fields + +Each entry in the `maker_orders` array contains: + +| Field | Type | Description | +| ---------------- | ------ | ---------------------------- | +| `order_id` | string | Maker order ID (hash) | +| `owner` | string | Maker's API key ID | +| `maker_address` | string | Maker's funder address | +| `matched_amount` | string | Amount matched in this trade | +| `price` | string | Maker order price | +| `fee_rate_bps` | string | Maker fee rate in bps | +| `asset_id` | string | Token ID | +| `outcome` | string | Outcome name | +| `side` | string | `BUY` or `SELL` | + +Retrieve your trades with the SDK: + + + ```typescript TypeScript theme={null} + // All trades + const trades = await client.getTrades(); + + // Filtered by market + const marketTrades = await client.getTrades({ + market: "0xbd31dc8a...", + }); + + // With pagination + const paginatedTrades = await client.getTradesPaginated({ + market: "0xbd31dc8a...", + }); + ``` + + ```python Python theme={null} + from py_clob_client_v2 import TradeParams + + # All trades + trades = client.get_trades() + + # Filtered by market + market_trades = client.get_trades( + TradeParams( + market="0xbd31dc8a...", + ) + ) + ``` + + ```rust Rust theme={null} + use polymarket_client_sdk_v2::clob::types::request::TradesRequest; + + // All trades + let trades = client.trades(&TradesRequest::default(), None).await?; + + // Filtered by market + let request = TradesRequest::builder() + .market("0xbd31dc8a...".parse()?) + .build(); + let market_trades = client.trades(&request, None).await?; + ``` + + +*** + +## Heartbeat + +The heartbeat endpoint maintains session liveness for order safety. If a valid heartbeat is not received within **10 seconds** (with up to a 5-second buffer), **all of your open orders will be cancelled**. + + + ```typescript TypeScript theme={null} + // Send heartbeats in a loop + let heartbeatId = ""; + setInterval(async () => { + const resp = await client.postHeartbeat(heartbeatId); + heartbeatId = resp.heartbeat_id; + }, 5000); + ``` + + ```python Python theme={null} + import time + + heartbeat_id = "" + while True: + resp = client.post_heartbeat(heartbeat_id) + heartbeat_id = resp["heartbeat_id"] + time.sleep(5) + ``` + + ```rust Rust theme={null} + // With the `heartbeats` feature, auto-send in background: + Client::start_heartbeats(&mut client)?; + + // Or manually: + let resp = client.post_heartbeat(None).await?; // None for first call + let resp = client.post_heartbeat(Some(resp.heartbeat_id)).await?; + ``` + + +* On each request, include the most recent `heartbeat_id` you received. For your first request, use an empty string. +* If you send an invalid or expired `heartbeat_id`, the server responds with a `400 Bad Request` and provides the correct `heartbeat_id` in the response. Update your client and retry. + +*** + +## Order Scoring + +Check if your resting orders are eligible for [maker rebates](/market-makers/maker-rebates) scoring: + + + ```typescript TypeScript theme={null} + // Single order + const scoring = await client.isOrderScoring({ orderId: "0x..." }); + console.log(scoring); // { scoring: true } + + // Multiple orders + const batchScoring = await client.areOrdersScoring({ + orderIds: ["0x...", "0x..."], + }); + ``` + + ```python Python theme={null} + from py_clob_client_v2 import OrderScoringParams, OrdersScoringParams + + # Single order + scoring = client.is_order_scoring( + OrderScoringParams(orderId="0x...") + ) + + # Multiple orders + batch_scoring = client.are_orders_scoring( + OrdersScoringParams(orderIds=["0x...", "0x..."]) + ) + ``` + + ```rust Rust theme={null} + // Single order + let scoring = client.is_order_scoring("0x...").await?; + println!("Scoring: {}", scoring.scoring); + + // Multiple orders + let batch = client.are_orders_scoring(&["0x...", "0x..."]).await?; + ``` + + +*** + +## Onchain Order Info + +When a trade is settled onchain, the Exchange contract emits an `OrderFilled` event with the following fields: + +| Field | Description | +| ------------------- | --------------------------------------------------------------------------------------------- | +| `orderHash` | Unique hash for the filled order | +| `maker` | The user who generated the order and source of funds | +| `taker` | The user filling the order, or the Exchange contract if multiple limit orders are filled | +| `makerAssetId` | ID of the asset given out. If `0`, the order is a **BUY** (giving pUSD for outcome tokens) | +| `takerAssetId` | ID of the asset received. If `0`, the order is a **SELL** (receiving pUSD for outcome tokens) | +| `makerAmountFilled` | Amount of the asset given out | +| `takerAmountFilled` | Amount of the asset received | +| `fee` | Fees paid by the order maker | + +*** + +## Error Messages + +When placing an order, the response may include an `errorMsg` if the order could not be placed. If `success` is `false`, there was a server-side error: + +| Error | Description | +| ---------------------------------- | ------------------------------------------------------ | +| `INVALID_ORDER_MIN_TICK_SIZE` | Price doesn't conform to the market's tick size | +| `INVALID_ORDER_MIN_SIZE` | Order size is below the minimum threshold | +| `INVALID_ORDER_DUPLICATED` | Identical order has already been placed | +| `INVALID_ORDER_NOT_ENOUGH_BALANCE` | Funder doesn't have sufficient balance or allowance | +| `INVALID_ORDER_EXPIRATION` | Expiration timestamp is in the past | +| `INVALID_ORDER_ERROR` | System error while inserting order | +| `INVALID_POST_ONLY_ORDER_TYPE` | Post-only flag used with a market order type (FOK/FAK) | +| `INVALID_POST_ONLY_ORDER` | Post-only order would cross the book | +| `EXECUTION_ERROR` | System error while executing trade | +| `ORDER_DELAYED` | Order placement delayed due to market conditions | +| `DELAYING_ORDER_ERROR` | System error while delaying order | +| `FOK_ORDER_NOT_FILLED_ERROR` | FOK order couldn't be fully filled | +| `MARKET_NOT_READY` | Market is not yet accepting orders | + +### Insert Statuses + +When an order is successfully placed, the response includes a `status` field: + +| Status | Description | +| ----------- | -------------------------------------------------------------------- | +| `matched` | Order placed and matched with a resting order | +| `live` | Order placed and resting on the book | +| `delayed` | Order is marketable but subject to a matching delay | +| `unmatched` | Order is marketable but failed to delay — placement still successful | + +*** + +## Security + +Polymarket's Exchange contract has been audited by Chainsecurity ([View Audit](https://github.com/Polymarket/ctf-exchange/blob/main/audit/ChainSecurity_Polymarket_Exchange_audit.pdf)). + +The operator's privileges are limited to order matching and ensuring correct ordering. Operators cannot set prices or execute unauthorized trades. + +*** + +## Next Steps + + + + Build, sign, and submit orders + + + + Cancel single, multiple, or all orders + + diff --git a/PolymarketDocumentation-main/docs/developers/CLOB/orders/get-order.md b/PolymarketDocumentation-main/docs/developers/CLOB/orders/get-order.md new file mode 100644 index 00000000..20013388 --- /dev/null +++ b/PolymarketDocumentation-main/docs/developers/CLOB/orders/get-order.md @@ -0,0 +1,550 @@ +> ## Documentation Index +> Fetch the complete documentation index at: https://docs.polymarket.com/llms.txt +> Use this file to discover all available pages before exploring further. + +# Overview + +> Order types, tick sizes, and querying orders + +All orders on Polymarket are expressed as **limit orders**. Market orders are supported by submitting a limit order with a marketable price — your order executes immediately at the best available price on the book. + +The underlying order primitive is structured, hashed, and signed using the [EIP-712](https://eips.ethereum.org/EIPS/eip-712) standard, then executed onchain via the Exchange contract. Preparing orders manually is involved, so we recommend using the open-source [TypeScript](https://github.com/Polymarket/clob-client-v2) or [Python](https://github.com/Polymarket/py-clob-client-v2) SDK clients, which handle signing and submission for you. + + + If you prefer to use the REST API directly, you'll need to manage order + signing yourself. See [Authentication](/api-reference/authentication) for details on + constructing the required headers. + + +*** + +## Order Types + +| Type | Behavior | Use Case | +| ---------------------------- | -------------------------------------------------------------------------------------------------- | -------------------------------------- | +| **GTC** (Good-Til-Cancelled) | Rests on the book until filled or cancelled | Default for passive limit orders | +| **GTD** (Good-Til-Date) | Active until a specified expiration time (UTC seconds timestamp), unless filled or cancelled first | Auto-expire orders before known events | +| **FOK** (Fill-Or-Kill) | Must be filled immediately and entirely, or the whole order is cancelled | All-or-nothing execution | +| **FAK** (Fill-And-Kill) | Fills as many shares as available immediately, then cancels any unfilled remainder | Partial immediate execution | + +* **FOK** and **FAK** are market order types — they execute against resting liquidity immediately. + * **BUY**: specify the dollar amount you want to spend + * **SELL**: specify the number of shares you want to sell +* **GTC** and **GTD** are limit order types — they rest on the book at your specified price. + + + **GTD expiration**: Orders expire one minute before their stated expiration + as a security threshold, and the expiration must be at least three minutes + in the future. For a 5-minute effective lifetime, the correct expiration + value is `now + 1 minute + 5 minutes`. + + +### Post-Only Orders + +Post-only orders are limit orders that will only rest on the book and not match immediately on entry. + +* If a post-only order would cross the spread (i.e., it is marketable), it will be **rejected** rather than executed. +* Post-only **cannot** be combined with market order types (FOK or FAK). If `postOnly = true` is sent with a market order type, the order will be rejected. +* Post-only can only be used with **GTC** and **GTD** order types. + +*** + +## Tick Sizes + +Markets have different minimum price increments (tick sizes). Your order price must conform to the market's tick size, or the order will be rejected. + +| Tick Size | Price Precision | Example Prices | +| --------- | --------------- | ---------------------- | +| `0.1` | 1 decimal | 0.1, 0.2, 0.5 | +| `0.01` | 2 decimals | 0.01, 0.50, 0.99 | +| `0.001` | 3 decimals | 0.001, 0.500, 0.999 | +| `0.0001` | 4 decimals | 0.0001, 0.5000, 0.9999 | +| `0.0025` | 0.25¢ steps | 0.0025, 0.5000, 0.9975 | + + + The `0.0025` (0.25¢) tick size applies only to World Cup *to advance*, *moneyline*, *spreads*, and *totals* markets. Always fetch the market's tick size before quoting rather than assuming a value. + + +Retrieve the tick size for a market using the SDK: + + + ```typescript TypeScript theme={null} + const tickSize = await client.getTickSize(tokenID); + // Returns: "0.1" | "0.01" | "0.001" | "0.0001" + ``` + + ```python Python theme={null} + tick_size = client.get_tick_size(token_id) + # Returns: "0.1" | "0.01" | "0.001" | "0.0001" + ``` + + ```rust Rust theme={null} + let resp = client.tick_size(token_id).await?; + // resp.minimum_tick_size: TickSize::Tenth | Hundredth | Thousandth | TenThousandth + ``` + + + + You can also check the `minimum_tick_size` field on a market object returned + by the [Markets API](/market-data/fetching-markets). + + +*** + +## Negative Risk + +Multi-outcome events (e.g., "Who will win the election?" with 3+ candidates) use a different exchange contract called the **Neg Risk CTF Exchange**. When placing orders on these markets, you must pass `negRisk: true` in the order options. + + + ```typescript TypeScript theme={null} + const response = await client.createAndPostOrder( + { + tokenID: "TOKEN_ID", + price: 0.5, + size: 10, + side: Side.BUY, + }, + { + tickSize: "0.01", + negRisk: true, // Required for multi-outcome markets + }, + ); + ``` + + ```python Python theme={null} + from py_clob_client_v2 import OrderArgs, PartialCreateOrderOptions + from py_clob_client_v2.order_builder.constants import BUY + + response = client.create_and_post_order( + OrderArgs( + token_id="TOKEN_ID", + price=0.50, + size=10, + side=BUY, + ), + options=PartialCreateOrderOptions( + tick_size="0.01", + neg_risk=True, # Required for multi-outcome markets + ) + ) + ``` + + ```rust Rust theme={null} + // The Rust SDK auto-detects neg risk from the token ID — no flag needed. + // The order builder fetches neg_risk and uses the correct exchange contract. + let order = client + .limit_order() + .token_id("TOKEN_ID".parse()?) + .price(dec!(0.50)) + .size(dec!(10)) + .side(Side::Buy) + .build() + .await?; + let signed = client.sign(&signer, order).await?; + let response = client.post_order(signed).await?; + ``` + + +You can check whether a market uses negative risk via the SDK or the market object's `neg_risk` field: + + + ```typescript TypeScript theme={null} + const isNegRisk = await client.getNegRisk(tokenID); + ``` + + ```python Python theme={null} + is_neg_risk = client.get_neg_risk(token_id) + ``` + + ```rust Rust theme={null} + let is_neg_risk = client.neg_risk(token_id).await?; + ``` + + +*** + +## Allowances + +Before placing an order, your funder address must have approved the Exchange contract to spend the relevant tokens: + +* **Buying**: the funder must have set a **pUSD** allowance greater than or equal to the spending amount. +* **Selling**: the funder must have set a **conditional token** allowance greater than or equal to the selling amount. + +This allows the Exchange contract to execute settlement according to your signed order instructions. + +*** + +## Validity Checks + +Orders are continually monitored to make sure they remain valid. This includes tracking: + +* Underlying balances +* Allowances + + + Any maker caught intentionally abusing these checks will be blacklisted. + + +There are also limits on order placement per market. You can only place orders that sum to less than or equal to your available balance for each market. For example, if you have 500 pUSD in your funding wallet, you can place one order to buy 1000 YES at \$0.50 — but any additional buy orders in that market will be rejected since your entire balance is reserved for the first order. + +The max size you can place for an order is: + +$$ +\text{maxOrderSize} = \text{underlyingAssetBalance} - \sum(\text{orderSize} - \text{orderFillAmount}) +$$ + +*** + +## Querying Orders + +All query endpoints require [L2 authentication](/api-reference/authentication). [Builder-authenticated](/trading/clients/builder) clients can also query orders attributed to their builder account using the same methods. + +### Get a Single Order + +Retrieve details for a specific order by its ID: + + + ```typescript TypeScript theme={null} + const order = await client.getOrder("0xb816482a..."); + console.log(order); + ``` + + ```python Python theme={null} + order = client.get_order("0xb816482a...") + print(order) + ``` + + ```rust Rust theme={null} + let order = client.order("0xb816482a...").await?; + println!("{order:?}"); + ``` + + +### Get Open Orders + +Retrieve your open orders, optionally filtered by market or asset: + + + ```typescript TypeScript theme={null} + // All open orders + const orders = await client.getOpenOrders(); + + // Filtered by market + const marketOrders = await client.getOpenOrders({ + market: "0xbd31dc8a...", + }); + + // Filtered by asset + const assetOrders = await client.getOpenOrders({ + asset_id: "52114319501245...", + }); + ``` + + ```python Python theme={null} + from py_clob_client_v2 import OpenOrderParams + + # All open orders + orders = client.get_orders() + + # Filtered by market + market_orders = client.get_orders( + OpenOrderParams( + market="0xbd31dc8a...", + ) + ) + ``` + + ```rust Rust theme={null} + use polymarket_client_sdk_v2::clob::types::request::OrdersRequest; + + // All open orders + let orders = client.orders(&OrdersRequest::default(), None).await?; + + // Filtered by market + let request = OrdersRequest::builder() + .market("0xbd31dc8a...".parse()?) + .build(); + let market_orders = client.orders(&request, None).await?; + + // Filtered by asset + let request = OrdersRequest::builder() + .asset_id("52114319501245...".parse()?) + .build(); + let asset_orders = client.orders(&request, None).await?; + ``` + + +### OpenOrder Object + +Each order returned contains these fields: + +| Field | Type | Description | +| ------------------ | --------- | ------------------------------------------------------------ | +| `id` | string | Order ID | +| `status` | string | Current order status | +| `market` | string | Market ID (condition ID) | +| `asset_id` | string | Token ID | +| `side` | string | `BUY` or `SELL` | +| `original_size` | string | Original order size at placement | +| `size_matched` | string | Amount that has been filled | +| `price` | string | Limit price | +| `outcome` | string | Human-readable outcome (e.g., "Yes", "No") | +| `order_type` | string | Order type (GTC, GTD, FOK, FAK) | +| `maker_address` | string | Funder address | +| `owner` | string | API key of the order owner | +| `expiration` | string | Unix timestamp when the order expires (`0` if no expiration) | +| `associate_trades` | string\[] | Trade IDs this order has been partially included in | +| `created_at` | string | Unix timestamp when the order was created | + +*** + +## Trade History + +When an order is matched, it creates a trade. Trades go through the following statuses: + +| Status | Terminal? | Description | +| ----------- | --------- | -------------------------------------------------------------------- | +| `MATCHED` | No | Matched and sent to the executor service for onchain submission | +| `MINED` | No | Observed as mined on the chain, no finality threshold yet | +| `CONFIRMED` | Yes | Achieved strong probabilistic finality — trade successful | +| `RETRYING` | No | Transaction failed (revert or reorg) — being retried by the operator | +| `FAILED` | Yes | Trade failed permanently and is not being retried | + +### Trade Object + +Each trade contains these fields: + +| Field | Type | Description | +| ------------------ | ------ | ------------------------------------------------------------ | +| `id` | string | Trade ID | +| `taker_order_id` | string | Taker order ID (hash) | +| `market` | string | Market ID (condition ID) | +| `asset_id` | string | Token ID | +| `side` | string | `BUY` or `SELL` | +| `size` | string | Trade size | +| `fee_rate_bps` | string | Fee rate in basis points | +| `price` | string | Trade price | +| `status` | string | Trade status (see table above) | +| `match_time` | string | Unix timestamp when the trade was matched | +| `last_update` | string | Unix timestamp of last status update | +| `outcome` | string | Human-readable outcome (e.g., "Yes", "No") | +| `owner` | string | API key ID of the trade owner | +| `maker_address` | string | Funder address | +| `trader_side` | string | Whether you were `TAKER` or `MAKER` in this trade | +| `transaction_hash` | string | Onchain transaction hash (available after mining) | +| `maker_orders` | array | Array of maker orders matched against this trade (see below) | + +### MakerOrder Fields + +Each entry in the `maker_orders` array contains: + +| Field | Type | Description | +| ---------------- | ------ | ---------------------------- | +| `order_id` | string | Maker order ID (hash) | +| `owner` | string | Maker's API key ID | +| `maker_address` | string | Maker's funder address | +| `matched_amount` | string | Amount matched in this trade | +| `price` | string | Maker order price | +| `fee_rate_bps` | string | Maker fee rate in bps | +| `asset_id` | string | Token ID | +| `outcome` | string | Outcome name | +| `side` | string | `BUY` or `SELL` | + +Retrieve your trades with the SDK: + + + ```typescript TypeScript theme={null} + // All trades + const trades = await client.getTrades(); + + // Filtered by market + const marketTrades = await client.getTrades({ + market: "0xbd31dc8a...", + }); + + // With pagination + const paginatedTrades = await client.getTradesPaginated({ + market: "0xbd31dc8a...", + }); + ``` + + ```python Python theme={null} + from py_clob_client_v2 import TradeParams + + # All trades + trades = client.get_trades() + + # Filtered by market + market_trades = client.get_trades( + TradeParams( + market="0xbd31dc8a...", + ) + ) + ``` + + ```rust Rust theme={null} + use polymarket_client_sdk_v2::clob::types::request::TradesRequest; + + // All trades + let trades = client.trades(&TradesRequest::default(), None).await?; + + // Filtered by market + let request = TradesRequest::builder() + .market("0xbd31dc8a...".parse()?) + .build(); + let market_trades = client.trades(&request, None).await?; + ``` + + +*** + +## Heartbeat + +The heartbeat endpoint maintains session liveness for order safety. If a valid heartbeat is not received within **10 seconds** (with up to a 5-second buffer), **all of your open orders will be cancelled**. + + + ```typescript TypeScript theme={null} + // Send heartbeats in a loop + let heartbeatId = ""; + setInterval(async () => { + const resp = await client.postHeartbeat(heartbeatId); + heartbeatId = resp.heartbeat_id; + }, 5000); + ``` + + ```python Python theme={null} + import time + + heartbeat_id = "" + while True: + resp = client.post_heartbeat(heartbeat_id) + heartbeat_id = resp["heartbeat_id"] + time.sleep(5) + ``` + + ```rust Rust theme={null} + // With the `heartbeats` feature, auto-send in background: + Client::start_heartbeats(&mut client)?; + + // Or manually: + let resp = client.post_heartbeat(None).await?; // None for first call + let resp = client.post_heartbeat(Some(resp.heartbeat_id)).await?; + ``` + + +* On each request, include the most recent `heartbeat_id` you received. For your first request, use an empty string. +* If you send an invalid or expired `heartbeat_id`, the server responds with a `400 Bad Request` and provides the correct `heartbeat_id` in the response. Update your client and retry. + +*** + +## Order Scoring + +Check if your resting orders are eligible for [maker rebates](/market-makers/maker-rebates) scoring: + + + ```typescript TypeScript theme={null} + // Single order + const scoring = await client.isOrderScoring({ orderId: "0x..." }); + console.log(scoring); // { scoring: true } + + // Multiple orders + const batchScoring = await client.areOrdersScoring({ + orderIds: ["0x...", "0x..."], + }); + ``` + + ```python Python theme={null} + from py_clob_client_v2 import OrderScoringParams, OrdersScoringParams + + # Single order + scoring = client.is_order_scoring( + OrderScoringParams(orderId="0x...") + ) + + # Multiple orders + batch_scoring = client.are_orders_scoring( + OrdersScoringParams(orderIds=["0x...", "0x..."]) + ) + ``` + + ```rust Rust theme={null} + // Single order + let scoring = client.is_order_scoring("0x...").await?; + println!("Scoring: {}", scoring.scoring); + + // Multiple orders + let batch = client.are_orders_scoring(&["0x...", "0x..."]).await?; + ``` + + +*** + +## Onchain Order Info + +When a trade is settled onchain, the Exchange contract emits an `OrderFilled` event with the following fields: + +| Field | Description | +| ------------------- | --------------------------------------------------------------------------------------------- | +| `orderHash` | Unique hash for the filled order | +| `maker` | The user who generated the order and source of funds | +| `taker` | The user filling the order, or the Exchange contract if multiple limit orders are filled | +| `makerAssetId` | ID of the asset given out. If `0`, the order is a **BUY** (giving pUSD for outcome tokens) | +| `takerAssetId` | ID of the asset received. If `0`, the order is a **SELL** (receiving pUSD for outcome tokens) | +| `makerAmountFilled` | Amount of the asset given out | +| `takerAmountFilled` | Amount of the asset received | +| `fee` | Fees paid by the order maker | + +*** + +## Error Messages + +When placing an order, the response may include an `errorMsg` if the order could not be placed. If `success` is `false`, there was a server-side error: + +| Error | Description | +| ---------------------------------- | ------------------------------------------------------ | +| `INVALID_ORDER_MIN_TICK_SIZE` | Price doesn't conform to the market's tick size | +| `INVALID_ORDER_MIN_SIZE` | Order size is below the minimum threshold | +| `INVALID_ORDER_DUPLICATED` | Identical order has already been placed | +| `INVALID_ORDER_NOT_ENOUGH_BALANCE` | Funder doesn't have sufficient balance or allowance | +| `INVALID_ORDER_EXPIRATION` | Expiration timestamp is in the past | +| `INVALID_ORDER_ERROR` | System error while inserting order | +| `INVALID_POST_ONLY_ORDER_TYPE` | Post-only flag used with a market order type (FOK/FAK) | +| `INVALID_POST_ONLY_ORDER` | Post-only order would cross the book | +| `EXECUTION_ERROR` | System error while executing trade | +| `ORDER_DELAYED` | Order placement delayed due to market conditions | +| `DELAYING_ORDER_ERROR` | System error while delaying order | +| `FOK_ORDER_NOT_FILLED_ERROR` | FOK order couldn't be fully filled | +| `MARKET_NOT_READY` | Market is not yet accepting orders | + +### Insert Statuses + +When an order is successfully placed, the response includes a `status` field: + +| Status | Description | +| ----------- | -------------------------------------------------------------------- | +| `matched` | Order placed and matched with a resting order | +| `live` | Order placed and resting on the book | +| `delayed` | Order is marketable but subject to a matching delay | +| `unmatched` | Order is marketable but failed to delay — placement still successful | + +*** + +## Security + +Polymarket's Exchange contract has been audited by Chainsecurity ([View Audit](https://github.com/Polymarket/ctf-exchange/blob/main/audit/ChainSecurity_Polymarket_Exchange_audit.pdf)). + +The operator's privileges are limited to order matching and ensuring correct ordering. Operators cannot set prices or execute unauthorized trades. + +*** + +## Next Steps + + + + Build, sign, and submit orders + + + + Cancel single, multiple, or all orders + + diff --git a/PolymarketDocumentation-main/docs/developers/CLOB/orders/onchain-order-info.md b/PolymarketDocumentation-main/docs/developers/CLOB/orders/onchain-order-info.md new file mode 100644 index 00000000..20013388 --- /dev/null +++ b/PolymarketDocumentation-main/docs/developers/CLOB/orders/onchain-order-info.md @@ -0,0 +1,550 @@ +> ## Documentation Index +> Fetch the complete documentation index at: https://docs.polymarket.com/llms.txt +> Use this file to discover all available pages before exploring further. + +# Overview + +> Order types, tick sizes, and querying orders + +All orders on Polymarket are expressed as **limit orders**. Market orders are supported by submitting a limit order with a marketable price — your order executes immediately at the best available price on the book. + +The underlying order primitive is structured, hashed, and signed using the [EIP-712](https://eips.ethereum.org/EIPS/eip-712) standard, then executed onchain via the Exchange contract. Preparing orders manually is involved, so we recommend using the open-source [TypeScript](https://github.com/Polymarket/clob-client-v2) or [Python](https://github.com/Polymarket/py-clob-client-v2) SDK clients, which handle signing and submission for you. + + + If you prefer to use the REST API directly, you'll need to manage order + signing yourself. See [Authentication](/api-reference/authentication) for details on + constructing the required headers. + + +*** + +## Order Types + +| Type | Behavior | Use Case | +| ---------------------------- | -------------------------------------------------------------------------------------------------- | -------------------------------------- | +| **GTC** (Good-Til-Cancelled) | Rests on the book until filled or cancelled | Default for passive limit orders | +| **GTD** (Good-Til-Date) | Active until a specified expiration time (UTC seconds timestamp), unless filled or cancelled first | Auto-expire orders before known events | +| **FOK** (Fill-Or-Kill) | Must be filled immediately and entirely, or the whole order is cancelled | All-or-nothing execution | +| **FAK** (Fill-And-Kill) | Fills as many shares as available immediately, then cancels any unfilled remainder | Partial immediate execution | + +* **FOK** and **FAK** are market order types — they execute against resting liquidity immediately. + * **BUY**: specify the dollar amount you want to spend + * **SELL**: specify the number of shares you want to sell +* **GTC** and **GTD** are limit order types — they rest on the book at your specified price. + + + **GTD expiration**: Orders expire one minute before their stated expiration + as a security threshold, and the expiration must be at least three minutes + in the future. For a 5-minute effective lifetime, the correct expiration + value is `now + 1 minute + 5 minutes`. + + +### Post-Only Orders + +Post-only orders are limit orders that will only rest on the book and not match immediately on entry. + +* If a post-only order would cross the spread (i.e., it is marketable), it will be **rejected** rather than executed. +* Post-only **cannot** be combined with market order types (FOK or FAK). If `postOnly = true` is sent with a market order type, the order will be rejected. +* Post-only can only be used with **GTC** and **GTD** order types. + +*** + +## Tick Sizes + +Markets have different minimum price increments (tick sizes). Your order price must conform to the market's tick size, or the order will be rejected. + +| Tick Size | Price Precision | Example Prices | +| --------- | --------------- | ---------------------- | +| `0.1` | 1 decimal | 0.1, 0.2, 0.5 | +| `0.01` | 2 decimals | 0.01, 0.50, 0.99 | +| `0.001` | 3 decimals | 0.001, 0.500, 0.999 | +| `0.0001` | 4 decimals | 0.0001, 0.5000, 0.9999 | +| `0.0025` | 0.25¢ steps | 0.0025, 0.5000, 0.9975 | + + + The `0.0025` (0.25¢) tick size applies only to World Cup *to advance*, *moneyline*, *spreads*, and *totals* markets. Always fetch the market's tick size before quoting rather than assuming a value. + + +Retrieve the tick size for a market using the SDK: + + + ```typescript TypeScript theme={null} + const tickSize = await client.getTickSize(tokenID); + // Returns: "0.1" | "0.01" | "0.001" | "0.0001" + ``` + + ```python Python theme={null} + tick_size = client.get_tick_size(token_id) + # Returns: "0.1" | "0.01" | "0.001" | "0.0001" + ``` + + ```rust Rust theme={null} + let resp = client.tick_size(token_id).await?; + // resp.minimum_tick_size: TickSize::Tenth | Hundredth | Thousandth | TenThousandth + ``` + + + + You can also check the `minimum_tick_size` field on a market object returned + by the [Markets API](/market-data/fetching-markets). + + +*** + +## Negative Risk + +Multi-outcome events (e.g., "Who will win the election?" with 3+ candidates) use a different exchange contract called the **Neg Risk CTF Exchange**. When placing orders on these markets, you must pass `negRisk: true` in the order options. + + + ```typescript TypeScript theme={null} + const response = await client.createAndPostOrder( + { + tokenID: "TOKEN_ID", + price: 0.5, + size: 10, + side: Side.BUY, + }, + { + tickSize: "0.01", + negRisk: true, // Required for multi-outcome markets + }, + ); + ``` + + ```python Python theme={null} + from py_clob_client_v2 import OrderArgs, PartialCreateOrderOptions + from py_clob_client_v2.order_builder.constants import BUY + + response = client.create_and_post_order( + OrderArgs( + token_id="TOKEN_ID", + price=0.50, + size=10, + side=BUY, + ), + options=PartialCreateOrderOptions( + tick_size="0.01", + neg_risk=True, # Required for multi-outcome markets + ) + ) + ``` + + ```rust Rust theme={null} + // The Rust SDK auto-detects neg risk from the token ID — no flag needed. + // The order builder fetches neg_risk and uses the correct exchange contract. + let order = client + .limit_order() + .token_id("TOKEN_ID".parse()?) + .price(dec!(0.50)) + .size(dec!(10)) + .side(Side::Buy) + .build() + .await?; + let signed = client.sign(&signer, order).await?; + let response = client.post_order(signed).await?; + ``` + + +You can check whether a market uses negative risk via the SDK or the market object's `neg_risk` field: + + + ```typescript TypeScript theme={null} + const isNegRisk = await client.getNegRisk(tokenID); + ``` + + ```python Python theme={null} + is_neg_risk = client.get_neg_risk(token_id) + ``` + + ```rust Rust theme={null} + let is_neg_risk = client.neg_risk(token_id).await?; + ``` + + +*** + +## Allowances + +Before placing an order, your funder address must have approved the Exchange contract to spend the relevant tokens: + +* **Buying**: the funder must have set a **pUSD** allowance greater than or equal to the spending amount. +* **Selling**: the funder must have set a **conditional token** allowance greater than or equal to the selling amount. + +This allows the Exchange contract to execute settlement according to your signed order instructions. + +*** + +## Validity Checks + +Orders are continually monitored to make sure they remain valid. This includes tracking: + +* Underlying balances +* Allowances + + + Any maker caught intentionally abusing these checks will be blacklisted. + + +There are also limits on order placement per market. You can only place orders that sum to less than or equal to your available balance for each market. For example, if you have 500 pUSD in your funding wallet, you can place one order to buy 1000 YES at \$0.50 — but any additional buy orders in that market will be rejected since your entire balance is reserved for the first order. + +The max size you can place for an order is: + +$$ +\text{maxOrderSize} = \text{underlyingAssetBalance} - \sum(\text{orderSize} - \text{orderFillAmount}) +$$ + +*** + +## Querying Orders + +All query endpoints require [L2 authentication](/api-reference/authentication). [Builder-authenticated](/trading/clients/builder) clients can also query orders attributed to their builder account using the same methods. + +### Get a Single Order + +Retrieve details for a specific order by its ID: + + + ```typescript TypeScript theme={null} + const order = await client.getOrder("0xb816482a..."); + console.log(order); + ``` + + ```python Python theme={null} + order = client.get_order("0xb816482a...") + print(order) + ``` + + ```rust Rust theme={null} + let order = client.order("0xb816482a...").await?; + println!("{order:?}"); + ``` + + +### Get Open Orders + +Retrieve your open orders, optionally filtered by market or asset: + + + ```typescript TypeScript theme={null} + // All open orders + const orders = await client.getOpenOrders(); + + // Filtered by market + const marketOrders = await client.getOpenOrders({ + market: "0xbd31dc8a...", + }); + + // Filtered by asset + const assetOrders = await client.getOpenOrders({ + asset_id: "52114319501245...", + }); + ``` + + ```python Python theme={null} + from py_clob_client_v2 import OpenOrderParams + + # All open orders + orders = client.get_orders() + + # Filtered by market + market_orders = client.get_orders( + OpenOrderParams( + market="0xbd31dc8a...", + ) + ) + ``` + + ```rust Rust theme={null} + use polymarket_client_sdk_v2::clob::types::request::OrdersRequest; + + // All open orders + let orders = client.orders(&OrdersRequest::default(), None).await?; + + // Filtered by market + let request = OrdersRequest::builder() + .market("0xbd31dc8a...".parse()?) + .build(); + let market_orders = client.orders(&request, None).await?; + + // Filtered by asset + let request = OrdersRequest::builder() + .asset_id("52114319501245...".parse()?) + .build(); + let asset_orders = client.orders(&request, None).await?; + ``` + + +### OpenOrder Object + +Each order returned contains these fields: + +| Field | Type | Description | +| ------------------ | --------- | ------------------------------------------------------------ | +| `id` | string | Order ID | +| `status` | string | Current order status | +| `market` | string | Market ID (condition ID) | +| `asset_id` | string | Token ID | +| `side` | string | `BUY` or `SELL` | +| `original_size` | string | Original order size at placement | +| `size_matched` | string | Amount that has been filled | +| `price` | string | Limit price | +| `outcome` | string | Human-readable outcome (e.g., "Yes", "No") | +| `order_type` | string | Order type (GTC, GTD, FOK, FAK) | +| `maker_address` | string | Funder address | +| `owner` | string | API key of the order owner | +| `expiration` | string | Unix timestamp when the order expires (`0` if no expiration) | +| `associate_trades` | string\[] | Trade IDs this order has been partially included in | +| `created_at` | string | Unix timestamp when the order was created | + +*** + +## Trade History + +When an order is matched, it creates a trade. Trades go through the following statuses: + +| Status | Terminal? | Description | +| ----------- | --------- | -------------------------------------------------------------------- | +| `MATCHED` | No | Matched and sent to the executor service for onchain submission | +| `MINED` | No | Observed as mined on the chain, no finality threshold yet | +| `CONFIRMED` | Yes | Achieved strong probabilistic finality — trade successful | +| `RETRYING` | No | Transaction failed (revert or reorg) — being retried by the operator | +| `FAILED` | Yes | Trade failed permanently and is not being retried | + +### Trade Object + +Each trade contains these fields: + +| Field | Type | Description | +| ------------------ | ------ | ------------------------------------------------------------ | +| `id` | string | Trade ID | +| `taker_order_id` | string | Taker order ID (hash) | +| `market` | string | Market ID (condition ID) | +| `asset_id` | string | Token ID | +| `side` | string | `BUY` or `SELL` | +| `size` | string | Trade size | +| `fee_rate_bps` | string | Fee rate in basis points | +| `price` | string | Trade price | +| `status` | string | Trade status (see table above) | +| `match_time` | string | Unix timestamp when the trade was matched | +| `last_update` | string | Unix timestamp of last status update | +| `outcome` | string | Human-readable outcome (e.g., "Yes", "No") | +| `owner` | string | API key ID of the trade owner | +| `maker_address` | string | Funder address | +| `trader_side` | string | Whether you were `TAKER` or `MAKER` in this trade | +| `transaction_hash` | string | Onchain transaction hash (available after mining) | +| `maker_orders` | array | Array of maker orders matched against this trade (see below) | + +### MakerOrder Fields + +Each entry in the `maker_orders` array contains: + +| Field | Type | Description | +| ---------------- | ------ | ---------------------------- | +| `order_id` | string | Maker order ID (hash) | +| `owner` | string | Maker's API key ID | +| `maker_address` | string | Maker's funder address | +| `matched_amount` | string | Amount matched in this trade | +| `price` | string | Maker order price | +| `fee_rate_bps` | string | Maker fee rate in bps | +| `asset_id` | string | Token ID | +| `outcome` | string | Outcome name | +| `side` | string | `BUY` or `SELL` | + +Retrieve your trades with the SDK: + + + ```typescript TypeScript theme={null} + // All trades + const trades = await client.getTrades(); + + // Filtered by market + const marketTrades = await client.getTrades({ + market: "0xbd31dc8a...", + }); + + // With pagination + const paginatedTrades = await client.getTradesPaginated({ + market: "0xbd31dc8a...", + }); + ``` + + ```python Python theme={null} + from py_clob_client_v2 import TradeParams + + # All trades + trades = client.get_trades() + + # Filtered by market + market_trades = client.get_trades( + TradeParams( + market="0xbd31dc8a...", + ) + ) + ``` + + ```rust Rust theme={null} + use polymarket_client_sdk_v2::clob::types::request::TradesRequest; + + // All trades + let trades = client.trades(&TradesRequest::default(), None).await?; + + // Filtered by market + let request = TradesRequest::builder() + .market("0xbd31dc8a...".parse()?) + .build(); + let market_trades = client.trades(&request, None).await?; + ``` + + +*** + +## Heartbeat + +The heartbeat endpoint maintains session liveness for order safety. If a valid heartbeat is not received within **10 seconds** (with up to a 5-second buffer), **all of your open orders will be cancelled**. + + + ```typescript TypeScript theme={null} + // Send heartbeats in a loop + let heartbeatId = ""; + setInterval(async () => { + const resp = await client.postHeartbeat(heartbeatId); + heartbeatId = resp.heartbeat_id; + }, 5000); + ``` + + ```python Python theme={null} + import time + + heartbeat_id = "" + while True: + resp = client.post_heartbeat(heartbeat_id) + heartbeat_id = resp["heartbeat_id"] + time.sleep(5) + ``` + + ```rust Rust theme={null} + // With the `heartbeats` feature, auto-send in background: + Client::start_heartbeats(&mut client)?; + + // Or manually: + let resp = client.post_heartbeat(None).await?; // None for first call + let resp = client.post_heartbeat(Some(resp.heartbeat_id)).await?; + ``` + + +* On each request, include the most recent `heartbeat_id` you received. For your first request, use an empty string. +* If you send an invalid or expired `heartbeat_id`, the server responds with a `400 Bad Request` and provides the correct `heartbeat_id` in the response. Update your client and retry. + +*** + +## Order Scoring + +Check if your resting orders are eligible for [maker rebates](/market-makers/maker-rebates) scoring: + + + ```typescript TypeScript theme={null} + // Single order + const scoring = await client.isOrderScoring({ orderId: "0x..." }); + console.log(scoring); // { scoring: true } + + // Multiple orders + const batchScoring = await client.areOrdersScoring({ + orderIds: ["0x...", "0x..."], + }); + ``` + + ```python Python theme={null} + from py_clob_client_v2 import OrderScoringParams, OrdersScoringParams + + # Single order + scoring = client.is_order_scoring( + OrderScoringParams(orderId="0x...") + ) + + # Multiple orders + batch_scoring = client.are_orders_scoring( + OrdersScoringParams(orderIds=["0x...", "0x..."]) + ) + ``` + + ```rust Rust theme={null} + // Single order + let scoring = client.is_order_scoring("0x...").await?; + println!("Scoring: {}", scoring.scoring); + + // Multiple orders + let batch = client.are_orders_scoring(&["0x...", "0x..."]).await?; + ``` + + +*** + +## Onchain Order Info + +When a trade is settled onchain, the Exchange contract emits an `OrderFilled` event with the following fields: + +| Field | Description | +| ------------------- | --------------------------------------------------------------------------------------------- | +| `orderHash` | Unique hash for the filled order | +| `maker` | The user who generated the order and source of funds | +| `taker` | The user filling the order, or the Exchange contract if multiple limit orders are filled | +| `makerAssetId` | ID of the asset given out. If `0`, the order is a **BUY** (giving pUSD for outcome tokens) | +| `takerAssetId` | ID of the asset received. If `0`, the order is a **SELL** (receiving pUSD for outcome tokens) | +| `makerAmountFilled` | Amount of the asset given out | +| `takerAmountFilled` | Amount of the asset received | +| `fee` | Fees paid by the order maker | + +*** + +## Error Messages + +When placing an order, the response may include an `errorMsg` if the order could not be placed. If `success` is `false`, there was a server-side error: + +| Error | Description | +| ---------------------------------- | ------------------------------------------------------ | +| `INVALID_ORDER_MIN_TICK_SIZE` | Price doesn't conform to the market's tick size | +| `INVALID_ORDER_MIN_SIZE` | Order size is below the minimum threshold | +| `INVALID_ORDER_DUPLICATED` | Identical order has already been placed | +| `INVALID_ORDER_NOT_ENOUGH_BALANCE` | Funder doesn't have sufficient balance or allowance | +| `INVALID_ORDER_EXPIRATION` | Expiration timestamp is in the past | +| `INVALID_ORDER_ERROR` | System error while inserting order | +| `INVALID_POST_ONLY_ORDER_TYPE` | Post-only flag used with a market order type (FOK/FAK) | +| `INVALID_POST_ONLY_ORDER` | Post-only order would cross the book | +| `EXECUTION_ERROR` | System error while executing trade | +| `ORDER_DELAYED` | Order placement delayed due to market conditions | +| `DELAYING_ORDER_ERROR` | System error while delaying order | +| `FOK_ORDER_NOT_FILLED_ERROR` | FOK order couldn't be fully filled | +| `MARKET_NOT_READY` | Market is not yet accepting orders | + +### Insert Statuses + +When an order is successfully placed, the response includes a `status` field: + +| Status | Description | +| ----------- | -------------------------------------------------------------------- | +| `matched` | Order placed and matched with a resting order | +| `live` | Order placed and resting on the book | +| `delayed` | Order is marketable but subject to a matching delay | +| `unmatched` | Order is marketable but failed to delay — placement still successful | + +*** + +## Security + +Polymarket's Exchange contract has been audited by Chainsecurity ([View Audit](https://github.com/Polymarket/ctf-exchange/blob/main/audit/ChainSecurity_Polymarket_Exchange_audit.pdf)). + +The operator's privileges are limited to order matching and ensuring correct ordering. Operators cannot set prices or execute unauthorized trades. + +*** + +## Next Steps + + + + Build, sign, and submit orders + + + + Cancel single, multiple, or all orders + + diff --git a/PolymarketDocumentation-main/docs/developers/CLOB/orders/orders.md b/PolymarketDocumentation-main/docs/developers/CLOB/orders/orders.md new file mode 100644 index 00000000..20013388 --- /dev/null +++ b/PolymarketDocumentation-main/docs/developers/CLOB/orders/orders.md @@ -0,0 +1,550 @@ +> ## Documentation Index +> Fetch the complete documentation index at: https://docs.polymarket.com/llms.txt +> Use this file to discover all available pages before exploring further. + +# Overview + +> Order types, tick sizes, and querying orders + +All orders on Polymarket are expressed as **limit orders**. Market orders are supported by submitting a limit order with a marketable price — your order executes immediately at the best available price on the book. + +The underlying order primitive is structured, hashed, and signed using the [EIP-712](https://eips.ethereum.org/EIPS/eip-712) standard, then executed onchain via the Exchange contract. Preparing orders manually is involved, so we recommend using the open-source [TypeScript](https://github.com/Polymarket/clob-client-v2) or [Python](https://github.com/Polymarket/py-clob-client-v2) SDK clients, which handle signing and submission for you. + + + If you prefer to use the REST API directly, you'll need to manage order + signing yourself. See [Authentication](/api-reference/authentication) for details on + constructing the required headers. + + +*** + +## Order Types + +| Type | Behavior | Use Case | +| ---------------------------- | -------------------------------------------------------------------------------------------------- | -------------------------------------- | +| **GTC** (Good-Til-Cancelled) | Rests on the book until filled or cancelled | Default for passive limit orders | +| **GTD** (Good-Til-Date) | Active until a specified expiration time (UTC seconds timestamp), unless filled or cancelled first | Auto-expire orders before known events | +| **FOK** (Fill-Or-Kill) | Must be filled immediately and entirely, or the whole order is cancelled | All-or-nothing execution | +| **FAK** (Fill-And-Kill) | Fills as many shares as available immediately, then cancels any unfilled remainder | Partial immediate execution | + +* **FOK** and **FAK** are market order types — they execute against resting liquidity immediately. + * **BUY**: specify the dollar amount you want to spend + * **SELL**: specify the number of shares you want to sell +* **GTC** and **GTD** are limit order types — they rest on the book at your specified price. + + + **GTD expiration**: Orders expire one minute before their stated expiration + as a security threshold, and the expiration must be at least three minutes + in the future. For a 5-minute effective lifetime, the correct expiration + value is `now + 1 minute + 5 minutes`. + + +### Post-Only Orders + +Post-only orders are limit orders that will only rest on the book and not match immediately on entry. + +* If a post-only order would cross the spread (i.e., it is marketable), it will be **rejected** rather than executed. +* Post-only **cannot** be combined with market order types (FOK or FAK). If `postOnly = true` is sent with a market order type, the order will be rejected. +* Post-only can only be used with **GTC** and **GTD** order types. + +*** + +## Tick Sizes + +Markets have different minimum price increments (tick sizes). Your order price must conform to the market's tick size, or the order will be rejected. + +| Tick Size | Price Precision | Example Prices | +| --------- | --------------- | ---------------------- | +| `0.1` | 1 decimal | 0.1, 0.2, 0.5 | +| `0.01` | 2 decimals | 0.01, 0.50, 0.99 | +| `0.001` | 3 decimals | 0.001, 0.500, 0.999 | +| `0.0001` | 4 decimals | 0.0001, 0.5000, 0.9999 | +| `0.0025` | 0.25¢ steps | 0.0025, 0.5000, 0.9975 | + + + The `0.0025` (0.25¢) tick size applies only to World Cup *to advance*, *moneyline*, *spreads*, and *totals* markets. Always fetch the market's tick size before quoting rather than assuming a value. + + +Retrieve the tick size for a market using the SDK: + + + ```typescript TypeScript theme={null} + const tickSize = await client.getTickSize(tokenID); + // Returns: "0.1" | "0.01" | "0.001" | "0.0001" + ``` + + ```python Python theme={null} + tick_size = client.get_tick_size(token_id) + # Returns: "0.1" | "0.01" | "0.001" | "0.0001" + ``` + + ```rust Rust theme={null} + let resp = client.tick_size(token_id).await?; + // resp.minimum_tick_size: TickSize::Tenth | Hundredth | Thousandth | TenThousandth + ``` + + + + You can also check the `minimum_tick_size` field on a market object returned + by the [Markets API](/market-data/fetching-markets). + + +*** + +## Negative Risk + +Multi-outcome events (e.g., "Who will win the election?" with 3+ candidates) use a different exchange contract called the **Neg Risk CTF Exchange**. When placing orders on these markets, you must pass `negRisk: true` in the order options. + + + ```typescript TypeScript theme={null} + const response = await client.createAndPostOrder( + { + tokenID: "TOKEN_ID", + price: 0.5, + size: 10, + side: Side.BUY, + }, + { + tickSize: "0.01", + negRisk: true, // Required for multi-outcome markets + }, + ); + ``` + + ```python Python theme={null} + from py_clob_client_v2 import OrderArgs, PartialCreateOrderOptions + from py_clob_client_v2.order_builder.constants import BUY + + response = client.create_and_post_order( + OrderArgs( + token_id="TOKEN_ID", + price=0.50, + size=10, + side=BUY, + ), + options=PartialCreateOrderOptions( + tick_size="0.01", + neg_risk=True, # Required for multi-outcome markets + ) + ) + ``` + + ```rust Rust theme={null} + // The Rust SDK auto-detects neg risk from the token ID — no flag needed. + // The order builder fetches neg_risk and uses the correct exchange contract. + let order = client + .limit_order() + .token_id("TOKEN_ID".parse()?) + .price(dec!(0.50)) + .size(dec!(10)) + .side(Side::Buy) + .build() + .await?; + let signed = client.sign(&signer, order).await?; + let response = client.post_order(signed).await?; + ``` + + +You can check whether a market uses negative risk via the SDK or the market object's `neg_risk` field: + + + ```typescript TypeScript theme={null} + const isNegRisk = await client.getNegRisk(tokenID); + ``` + + ```python Python theme={null} + is_neg_risk = client.get_neg_risk(token_id) + ``` + + ```rust Rust theme={null} + let is_neg_risk = client.neg_risk(token_id).await?; + ``` + + +*** + +## Allowances + +Before placing an order, your funder address must have approved the Exchange contract to spend the relevant tokens: + +* **Buying**: the funder must have set a **pUSD** allowance greater than or equal to the spending amount. +* **Selling**: the funder must have set a **conditional token** allowance greater than or equal to the selling amount. + +This allows the Exchange contract to execute settlement according to your signed order instructions. + +*** + +## Validity Checks + +Orders are continually monitored to make sure they remain valid. This includes tracking: + +* Underlying balances +* Allowances + + + Any maker caught intentionally abusing these checks will be blacklisted. + + +There are also limits on order placement per market. You can only place orders that sum to less than or equal to your available balance for each market. For example, if you have 500 pUSD in your funding wallet, you can place one order to buy 1000 YES at \$0.50 — but any additional buy orders in that market will be rejected since your entire balance is reserved for the first order. + +The max size you can place for an order is: + +$$ +\text{maxOrderSize} = \text{underlyingAssetBalance} - \sum(\text{orderSize} - \text{orderFillAmount}) +$$ + +*** + +## Querying Orders + +All query endpoints require [L2 authentication](/api-reference/authentication). [Builder-authenticated](/trading/clients/builder) clients can also query orders attributed to their builder account using the same methods. + +### Get a Single Order + +Retrieve details for a specific order by its ID: + + + ```typescript TypeScript theme={null} + const order = await client.getOrder("0xb816482a..."); + console.log(order); + ``` + + ```python Python theme={null} + order = client.get_order("0xb816482a...") + print(order) + ``` + + ```rust Rust theme={null} + let order = client.order("0xb816482a...").await?; + println!("{order:?}"); + ``` + + +### Get Open Orders + +Retrieve your open orders, optionally filtered by market or asset: + + + ```typescript TypeScript theme={null} + // All open orders + const orders = await client.getOpenOrders(); + + // Filtered by market + const marketOrders = await client.getOpenOrders({ + market: "0xbd31dc8a...", + }); + + // Filtered by asset + const assetOrders = await client.getOpenOrders({ + asset_id: "52114319501245...", + }); + ``` + + ```python Python theme={null} + from py_clob_client_v2 import OpenOrderParams + + # All open orders + orders = client.get_orders() + + # Filtered by market + market_orders = client.get_orders( + OpenOrderParams( + market="0xbd31dc8a...", + ) + ) + ``` + + ```rust Rust theme={null} + use polymarket_client_sdk_v2::clob::types::request::OrdersRequest; + + // All open orders + let orders = client.orders(&OrdersRequest::default(), None).await?; + + // Filtered by market + let request = OrdersRequest::builder() + .market("0xbd31dc8a...".parse()?) + .build(); + let market_orders = client.orders(&request, None).await?; + + // Filtered by asset + let request = OrdersRequest::builder() + .asset_id("52114319501245...".parse()?) + .build(); + let asset_orders = client.orders(&request, None).await?; + ``` + + +### OpenOrder Object + +Each order returned contains these fields: + +| Field | Type | Description | +| ------------------ | --------- | ------------------------------------------------------------ | +| `id` | string | Order ID | +| `status` | string | Current order status | +| `market` | string | Market ID (condition ID) | +| `asset_id` | string | Token ID | +| `side` | string | `BUY` or `SELL` | +| `original_size` | string | Original order size at placement | +| `size_matched` | string | Amount that has been filled | +| `price` | string | Limit price | +| `outcome` | string | Human-readable outcome (e.g., "Yes", "No") | +| `order_type` | string | Order type (GTC, GTD, FOK, FAK) | +| `maker_address` | string | Funder address | +| `owner` | string | API key of the order owner | +| `expiration` | string | Unix timestamp when the order expires (`0` if no expiration) | +| `associate_trades` | string\[] | Trade IDs this order has been partially included in | +| `created_at` | string | Unix timestamp when the order was created | + +*** + +## Trade History + +When an order is matched, it creates a trade. Trades go through the following statuses: + +| Status | Terminal? | Description | +| ----------- | --------- | -------------------------------------------------------------------- | +| `MATCHED` | No | Matched and sent to the executor service for onchain submission | +| `MINED` | No | Observed as mined on the chain, no finality threshold yet | +| `CONFIRMED` | Yes | Achieved strong probabilistic finality — trade successful | +| `RETRYING` | No | Transaction failed (revert or reorg) — being retried by the operator | +| `FAILED` | Yes | Trade failed permanently and is not being retried | + +### Trade Object + +Each trade contains these fields: + +| Field | Type | Description | +| ------------------ | ------ | ------------------------------------------------------------ | +| `id` | string | Trade ID | +| `taker_order_id` | string | Taker order ID (hash) | +| `market` | string | Market ID (condition ID) | +| `asset_id` | string | Token ID | +| `side` | string | `BUY` or `SELL` | +| `size` | string | Trade size | +| `fee_rate_bps` | string | Fee rate in basis points | +| `price` | string | Trade price | +| `status` | string | Trade status (see table above) | +| `match_time` | string | Unix timestamp when the trade was matched | +| `last_update` | string | Unix timestamp of last status update | +| `outcome` | string | Human-readable outcome (e.g., "Yes", "No") | +| `owner` | string | API key ID of the trade owner | +| `maker_address` | string | Funder address | +| `trader_side` | string | Whether you were `TAKER` or `MAKER` in this trade | +| `transaction_hash` | string | Onchain transaction hash (available after mining) | +| `maker_orders` | array | Array of maker orders matched against this trade (see below) | + +### MakerOrder Fields + +Each entry in the `maker_orders` array contains: + +| Field | Type | Description | +| ---------------- | ------ | ---------------------------- | +| `order_id` | string | Maker order ID (hash) | +| `owner` | string | Maker's API key ID | +| `maker_address` | string | Maker's funder address | +| `matched_amount` | string | Amount matched in this trade | +| `price` | string | Maker order price | +| `fee_rate_bps` | string | Maker fee rate in bps | +| `asset_id` | string | Token ID | +| `outcome` | string | Outcome name | +| `side` | string | `BUY` or `SELL` | + +Retrieve your trades with the SDK: + + + ```typescript TypeScript theme={null} + // All trades + const trades = await client.getTrades(); + + // Filtered by market + const marketTrades = await client.getTrades({ + market: "0xbd31dc8a...", + }); + + // With pagination + const paginatedTrades = await client.getTradesPaginated({ + market: "0xbd31dc8a...", + }); + ``` + + ```python Python theme={null} + from py_clob_client_v2 import TradeParams + + # All trades + trades = client.get_trades() + + # Filtered by market + market_trades = client.get_trades( + TradeParams( + market="0xbd31dc8a...", + ) + ) + ``` + + ```rust Rust theme={null} + use polymarket_client_sdk_v2::clob::types::request::TradesRequest; + + // All trades + let trades = client.trades(&TradesRequest::default(), None).await?; + + // Filtered by market + let request = TradesRequest::builder() + .market("0xbd31dc8a...".parse()?) + .build(); + let market_trades = client.trades(&request, None).await?; + ``` + + +*** + +## Heartbeat + +The heartbeat endpoint maintains session liveness for order safety. If a valid heartbeat is not received within **10 seconds** (with up to a 5-second buffer), **all of your open orders will be cancelled**. + + + ```typescript TypeScript theme={null} + // Send heartbeats in a loop + let heartbeatId = ""; + setInterval(async () => { + const resp = await client.postHeartbeat(heartbeatId); + heartbeatId = resp.heartbeat_id; + }, 5000); + ``` + + ```python Python theme={null} + import time + + heartbeat_id = "" + while True: + resp = client.post_heartbeat(heartbeat_id) + heartbeat_id = resp["heartbeat_id"] + time.sleep(5) + ``` + + ```rust Rust theme={null} + // With the `heartbeats` feature, auto-send in background: + Client::start_heartbeats(&mut client)?; + + // Or manually: + let resp = client.post_heartbeat(None).await?; // None for first call + let resp = client.post_heartbeat(Some(resp.heartbeat_id)).await?; + ``` + + +* On each request, include the most recent `heartbeat_id` you received. For your first request, use an empty string. +* If you send an invalid or expired `heartbeat_id`, the server responds with a `400 Bad Request` and provides the correct `heartbeat_id` in the response. Update your client and retry. + +*** + +## Order Scoring + +Check if your resting orders are eligible for [maker rebates](/market-makers/maker-rebates) scoring: + + + ```typescript TypeScript theme={null} + // Single order + const scoring = await client.isOrderScoring({ orderId: "0x..." }); + console.log(scoring); // { scoring: true } + + // Multiple orders + const batchScoring = await client.areOrdersScoring({ + orderIds: ["0x...", "0x..."], + }); + ``` + + ```python Python theme={null} + from py_clob_client_v2 import OrderScoringParams, OrdersScoringParams + + # Single order + scoring = client.is_order_scoring( + OrderScoringParams(orderId="0x...") + ) + + # Multiple orders + batch_scoring = client.are_orders_scoring( + OrdersScoringParams(orderIds=["0x...", "0x..."]) + ) + ``` + + ```rust Rust theme={null} + // Single order + let scoring = client.is_order_scoring("0x...").await?; + println!("Scoring: {}", scoring.scoring); + + // Multiple orders + let batch = client.are_orders_scoring(&["0x...", "0x..."]).await?; + ``` + + +*** + +## Onchain Order Info + +When a trade is settled onchain, the Exchange contract emits an `OrderFilled` event with the following fields: + +| Field | Description | +| ------------------- | --------------------------------------------------------------------------------------------- | +| `orderHash` | Unique hash for the filled order | +| `maker` | The user who generated the order and source of funds | +| `taker` | The user filling the order, or the Exchange contract if multiple limit orders are filled | +| `makerAssetId` | ID of the asset given out. If `0`, the order is a **BUY** (giving pUSD for outcome tokens) | +| `takerAssetId` | ID of the asset received. If `0`, the order is a **SELL** (receiving pUSD for outcome tokens) | +| `makerAmountFilled` | Amount of the asset given out | +| `takerAmountFilled` | Amount of the asset received | +| `fee` | Fees paid by the order maker | + +*** + +## Error Messages + +When placing an order, the response may include an `errorMsg` if the order could not be placed. If `success` is `false`, there was a server-side error: + +| Error | Description | +| ---------------------------------- | ------------------------------------------------------ | +| `INVALID_ORDER_MIN_TICK_SIZE` | Price doesn't conform to the market's tick size | +| `INVALID_ORDER_MIN_SIZE` | Order size is below the minimum threshold | +| `INVALID_ORDER_DUPLICATED` | Identical order has already been placed | +| `INVALID_ORDER_NOT_ENOUGH_BALANCE` | Funder doesn't have sufficient balance or allowance | +| `INVALID_ORDER_EXPIRATION` | Expiration timestamp is in the past | +| `INVALID_ORDER_ERROR` | System error while inserting order | +| `INVALID_POST_ONLY_ORDER_TYPE` | Post-only flag used with a market order type (FOK/FAK) | +| `INVALID_POST_ONLY_ORDER` | Post-only order would cross the book | +| `EXECUTION_ERROR` | System error while executing trade | +| `ORDER_DELAYED` | Order placement delayed due to market conditions | +| `DELAYING_ORDER_ERROR` | System error while delaying order | +| `FOK_ORDER_NOT_FILLED_ERROR` | FOK order couldn't be fully filled | +| `MARKET_NOT_READY` | Market is not yet accepting orders | + +### Insert Statuses + +When an order is successfully placed, the response includes a `status` field: + +| Status | Description | +| ----------- | -------------------------------------------------------------------- | +| `matched` | Order placed and matched with a resting order | +| `live` | Order placed and resting on the book | +| `delayed` | Order is marketable but subject to a matching delay | +| `unmatched` | Order is marketable but failed to delay — placement still successful | + +*** + +## Security + +Polymarket's Exchange contract has been audited by Chainsecurity ([View Audit](https://github.com/Polymarket/ctf-exchange/blob/main/audit/ChainSecurity_Polymarket_Exchange_audit.pdf)). + +The operator's privileges are limited to order matching and ensuring correct ordering. Operators cannot set prices or execute unauthorized trades. + +*** + +## Next Steps + + + + Build, sign, and submit orders + + + + Cancel single, multiple, or all orders + + diff --git a/PolymarketDocumentation-main/docs/developers/CLOB/quickstart.md b/PolymarketDocumentation-main/docs/developers/CLOB/quickstart.md new file mode 100644 index 00000000..46dfaa1a --- /dev/null +++ b/PolymarketDocumentation-main/docs/developers/CLOB/quickstart.md @@ -0,0 +1,299 @@ +> ## Documentation Index +> Fetch the complete documentation index at: https://docs.polymarket.com/llms.txt +> Use this file to discover all available pages before exploring further. + +# Quickstart + +> Place your first order on Polymarket + +This guide walks you through placing an order on Polymarket end-to-end. + + + + + ```bash TypeScript theme={null} + npm install @polymarket/clob-client-v2 viem + ``` + + ```bash Python theme={null} + pip install py-clob-client-v2 + ``` + + ```bash Rust theme={null} + cargo add polymarket_client_sdk_v2 --features clob + ``` + + + + + Derive your API credentials and initialize the trading client. This example uses + a deposit wallet with signature type `3` (`POLY_1271`), which is the wallet path + for new API users: + + + ```typescript TypeScript theme={null} + import { ClobClient, SignatureTypeV2 } from "@polymarket/clob-client-v2"; + import { createWalletClient, http } from "viem"; + import { privateKeyToAccount } from "viem/accounts"; + + const HOST = "https://clob.polymarket.com"; + const CHAIN_ID = 137; // Polygon mainnet + const account = privateKeyToAccount(process.env.PRIVATE_KEY as `0x${string}`); + const signer = createWalletClient({ account, transport: http() }); + const depositWalletAddress = process.env.DEPOSIT_WALLET_ADDRESS!; + + // Derive API credentials + const tempClient = new ClobClient({ host: HOST, chain: CHAIN_ID, signer }); + const apiCreds = await tempClient.createOrDeriveApiKey(); + + // Initialize trading client + const client = new ClobClient({ + host: HOST, + chain: CHAIN_ID, + signer, + creds: apiCreds, + signatureType: SignatureTypeV2.POLY_1271, + funderAddress: depositWalletAddress, + }); + ``` + + ```python Python theme={null} + from py_clob_client_v2 import ClobClient, SignatureTypeV2 + import os + + host = "https://clob.polymarket.com" + chain = 137 # Polygon mainnet + private_key = os.getenv("PRIVATE_KEY") + deposit_wallet_address = os.getenv("DEPOSIT_WALLET_ADDRESS") + + # Derive API credentials + temp_client = ClobClient(host, key=private_key, chain_id=chain) + api_creds = temp_client.create_or_derive_api_key() + + # Initialize trading client + client = ClobClient( + host, + key=private_key, + chain_id=chain, + creds=api_creds, + signature_type=SignatureTypeV2.POLY_1271, + funder=deposit_wallet_address + ) + ``` + + ```rust Rust theme={null} + use std::str::FromStr; + use polymarket_client_sdk_v2::POLYGON; + use polymarket_client_sdk_v2::auth::{LocalSigner, Signer}; + use polymarket_client_sdk_v2::clob::types::SignatureType; + use polymarket_client_sdk_v2::clob::{Client, Config}; + + let private_key = std::env::var("POLYMARKET_PRIVATE_KEY")?; + let signer = LocalSigner::from_str(&private_key)? + .with_chain_id(Some(POLYGON)); + let deposit_wallet = std::env::var("DEPOSIT_WALLET_ADDRESS")?.parse()?; + + // Derive API credentials and initialize client + let client = Client::new("https://clob.polymarket.com", Config::default())? + .authentication_builder(&signer) + .funder(deposit_wallet) + .signature_type(SignatureType::Poly1271) + .authenticate() + .await?; + ``` + + + + Existing EOA, Safe, and Proxy integrations can keep using their current + signature type and funder address. See [Signature + Types](/trading/overview#signature-types) for all wallet types. + + + + Before trading from a deposit wallet, the deposit wallet needs **pUSD** and + the required trading approvals. See the [Deposit Wallet + Guide](/trading/deposit-wallets) for wallet creation, funding, approvals, and + balance sync. + + + + + Get a token ID from the [Markets API](/market-data/fetching-markets), then create and submit your order: + + + ```typescript TypeScript theme={null} + import { Side, OrderType } from "@polymarket/clob-client-v2"; + + const response = await client.createAndPostOrder( + { + tokenID: "YOUR_TOKEN_ID", + price: 0.5, + size: 10, + side: Side.BUY, + }, + { + tickSize: "0.01", + negRisk: false, // Set to true for multi-outcome markets + }, + OrderType.GTC, + ); + + console.log("Order ID:", response.orderID); + console.log("Status:", response.status); + ``` + + ```python Python theme={null} + from py_clob_client_v2 import OrderArgs, OrderType, PartialCreateOrderOptions + from py_clob_client_v2.order_builder.constants import BUY + + response = client.create_and_post_order( + OrderArgs( + token_id="YOUR_TOKEN_ID", + price=0.50, + size=10, + side=BUY, + ), + options=PartialCreateOrderOptions( + tick_size="0.01", + neg_risk=False, # Set to True for multi-outcome markets + ), + order_type=OrderType.GTC + ) + + print("Order ID:", response["orderID"]) + print("Status:", response["status"]) + ``` + + ```rust Rust theme={null} + use polymarket_client_sdk_v2::clob::types::Side; + use polymarket_client_sdk_v2::types::dec; + + let token_id = "YOUR_TOKEN_ID".parse()?; + + // Tick size and neg risk are auto-fetched by the order builder + let order = client + .limit_order() + .token_id(token_id) + .price(dec!(0.50)) + .size(dec!(10)) + .side(Side::Buy) + .build() + .await?; + let signed_order = client.sign(&signer, order).await?; + let response = client.post_order(signed_order).await?; + + println!("Order ID: {}", response.order_id); + println!("Status: {:?}", response.status); + ``` + + + + Look up a market's `tickSize` and `negRisk` values using the SDK's + `getTickSize()` and `getNegRisk()` methods, or from the market object returned + by the API. + + + + + + ```typescript TypeScript theme={null} + // View all open orders + const openOrders = await client.getOpenOrders(); + console.log(`You have ${openOrders.length} open orders`); + + // View your trade history + const trades = await client.getTrades(); + console.log(`You've made ${trades.length} trades`); + + // Cancel an order + await client.cancelOrder(response.orderID); + ``` + + ```python Python theme={null} + # View all open orders + open_orders = client.get_orders() + print(f"You have {len(open_orders)} open orders") + + # View your trade history + trades = client.get_trades() + print(f"You've made {len(trades)} trades") + + # Cancel an order + client.cancel(order_id=response["orderID"]) + ``` + + ```rust Rust theme={null} + use polymarket_client_sdk_v2::clob::types::request::{OrdersRequest, TradesRequest}; + + // View all open orders + let open_orders = client.orders(&OrdersRequest::default(), None).await?; + println!("You have {} open orders", open_orders.data.len()); + + // View your trade history + let trades = client.trades(&TradesRequest::default(), None).await?; + println!("You've made {} trades", trades.data.len()); + + // Cancel an order + client.cancel_order(&response.order_id).await?; + ``` + + + + +*** + +## Troubleshooting + + + + Wrong private key, signature type, or funder address for the derived API credentials. + + * Check that `signatureType` matches your account type (`0`, `1`, `2`, or `3`) + * Ensure `funder` is correct for your wallet type + * Re-derive credentials with `createOrDeriveApiKey()` if unsure + + + + Your funder address doesn't have enough tokens: + + * **BUY orders**: need pUSD in your funder address + * **SELL orders**: need outcome tokens in your funder address + * Ensure you have more pUSD than what's committed in open orders + + + + You need to approve the Exchange contract to spend your tokens. Deposit wallet + approvals must be executed from the deposit wallet through a relayer `WALLET` + batch. Existing Safe and Proxy users should use their current relayer approval + flow. + + + + Your funder address is the wallet where your funds are held: + + * **EOA (type 0)**: Your wallet address directly + * **Deposit wallet (type 3)**: The deposit wallet deployed for the owner or session signer + * **Proxy/Safe wallet (type 1 or 2)**: Existing Polymarket.com wallet address + + New API users should create a deposit wallet. Existing Proxy and Safe users + can continue using their current wallet address. + + + + You're trying to place a trade from a restricted region. See [Geographic Restrictions](/api-reference/geoblock) for details. + + + +*** + +## Next Steps + + + + Order types, tick sizes, and error handling + + + + Attribute orders to your builder account for volume credit + + diff --git a/PolymarketDocumentation-main/docs/developers/CLOB/status.md b/PolymarketDocumentation-main/docs/developers/CLOB/status.md new file mode 100644 index 00000000..6ead3014 --- /dev/null +++ b/PolymarketDocumentation-main/docs/developers/CLOB/status.md @@ -0,0 +1,134 @@ +Polymarket - Status

Polymarket - Status Page

Website - Operational

100% - uptime

CLOB API - Operational

100% - uptime

Markets API - Operational

100% - uptime

Polygon (RPC) - Operational

100% - uptime

User auth - Operational

100% - uptime

Sports API - Operational

100% - uptime

Recent notices

Show notice history
\ No newline at end of file diff --git a/PolymarketDocumentation-main/docs/developers/CLOB/timeseries.md b/PolymarketDocumentation-main/docs/developers/CLOB/timeseries.md new file mode 100644 index 00000000..d49f48b7 --- /dev/null +++ b/PolymarketDocumentation-main/docs/developers/CLOB/timeseries.md @@ -0,0 +1,143 @@ +> ## Documentation Index +> Fetch the complete documentation index at: https://docs.polymarket.com/llms.txt +> Use this file to discover all available pages before exploring further. + +# Get prices history + +> Retrieve historical price data for a market. + + + +## OpenAPI + +````yaml /api-spec/clob-openapi.yaml get /prices-history +openapi: 3.1.0 +info: + title: Polymarket CLOB API + description: Polymarket CLOB API Reference + license: + name: MIT + identifier: MIT + version: 1.0.0 +servers: + - url: https://clob.polymarket.com + description: Production CLOB API + - url: https://clob-staging.polymarket.com + description: Staging CLOB API +security: [] +tags: + - name: Trade + description: Trade endpoints + - name: Markets + description: Market data endpoints + - name: Account + description: Account and authentication endpoints + - name: Notifications + description: User notification endpoints + - name: Rewards + description: Rewards and earnings endpoints + - name: Rebates + description: Maker rebate endpoints +paths: + /prices-history: + get: + tags: + - Markets + summary: Get prices history + description: Retrieve historical price data for a market. + operationId: getPricesHistory + parameters: + - name: market + in: query + required: true + description: The market (asset id) to query. + schema: + type: string + - name: startTs + in: query + required: false + description: Filter by items after this unix timestamp. + schema: + type: number + format: double + - name: endTs + in: query + required: false + description: Filter by items before this unix timestamp. + schema: + type: number + format: double + - name: interval + in: query + required: false + description: Time interval for data aggregation. + schema: + type: string + enum: + - max + - all + - 1m + - 1w + - 1d + - 6h + - 1h + - name: fidelity + in: query + required: false + description: Accuracy of the data expressed in minutes. Default is 1 minute. + schema: + type: integer + responses: + '200': + description: Successful response with price history + content: + application/json: + schema: + $ref: '#/components/schemas/PricesHistoryResponse' + '400': + description: Bad Request - Missing or invalid query parameters + content: + application/json: + schema: + $ref: '#/components/schemas/ErrorResponse' + '500': + description: Internal server error + content: + application/json: + schema: + $ref: '#/components/schemas/ErrorResponse' + security: [] +components: + schemas: + PricesHistoryResponse: + type: object + properties: + history: + type: array + items: + $ref: '#/components/schemas/MarketPrice' + ErrorResponse: + type: object + required: + - error + properties: + error: + type: string + description: Error message + code: + type: string + description: Machine-readable error code, when provided + retry_after_seconds: + type: integer + description: Number of seconds to wait before retrying, when provided + MarketPrice: + type: object + properties: + t: + type: integer + format: uint32 + p: + type: number + format: float + +```` \ No newline at end of file diff --git a/PolymarketDocumentation-main/docs/developers/CLOB/trades/trades-overview.md b/PolymarketDocumentation-main/docs/developers/CLOB/trades/trades-overview.md new file mode 100644 index 00000000..52a2176c --- /dev/null +++ b/PolymarketDocumentation-main/docs/developers/CLOB/trades/trades-overview.md @@ -0,0 +1,265 @@ +> ## Documentation Index +> Fetch the complete documentation index at: https://docs.polymarket.com/llms.txt +> Use this file to discover all available pages before exploring further. + +# Overview + +> Trading on the Polymarket CLOB + +Polymarket's CLOB (Central Limit Order Book) is a hybrid-decentralized trading system — offchain order matching with onchain settlement via the [Exchange contract](https://github.com/Polymarket/ctf-exchange/tree/main/src) ([audited by Chainsecurity](https://github.com/Polymarket/ctf-exchange/blob/main/audit/ChainSecurity_Polymarket_Exchange_audit.pdf)). All trading is non-custodial. Orders are [EIP-712](https://eips.ethereum.org/EIPS/eip-712) signed messages, and matched trades settle atomically on Polygon. The operator cannot set prices or execute unauthorized trades. + +We recommend using the open-source SDK clients, which handle order signing, authentication, and submission: + + + +

+ npm install @polymarket/clob-client-v2 viem +

+
+ + +

pip install py-clob-client-v2

+
+ + +

+ cargo add polymarket\_client\_sdk\_v2 --features clob +

+
+
+ + + You can also use the REST API directly, but you'll need to manage [EIP-712 + order + signing](https://github.com/Polymarket/clob-client-v2/blob/main/src/signing/eip712.ts) + and [HMAC authentication + headers](https://github.com/Polymarket/clob-client-v2/blob/main/src/signing/hmac.ts) + yourself. See [REST API Headers](#rest-api-headers) below. + + +*** + +## Authentication + +The CLOB uses two levels of authentication: + +| Level | Method | Purpose | +| ------ | ------------------------------- | ----------------------------------------- | +| **L1** | EIP-712 signature (private key) | Create or derive API credentials | +| **L2** | HMAC-SHA256 (API credentials) | Place orders, cancel orders, query trades | + +You use your private key once to derive **L2 credentials** (API key, secret, passphrase), which authenticate all subsequent trading requests. + + + ```typescript TypeScript theme={null} + import { ClobClient } from "@polymarket/clob-client-v2"; + import { createWalletClient, http } from "viem"; + import { privateKeyToAccount } from "viem/accounts"; + + const account = privateKeyToAccount(process.env.PRIVATE_KEY as `0x${string}`); + const signer = createWalletClient({ account, transport: http() }); + + // Derive L2 API credentials + const tempClient = new ClobClient({ + host: "https://clob.polymarket.com", + chain: 137, + signer, + }); + const apiCreds = await tempClient.createOrDeriveApiKey(); + ``` + + ```python Python theme={null} + from py_clob_client_v2 import ClobClient + import os + + private_key = os.getenv("PRIVATE_KEY") + + # Derive L2 API credentials + temp_client = ClobClient("https://clob.polymarket.com", key=private_key, chain_id=137) + api_creds = temp_client.create_or_derive_api_key() + ``` + + ```rust Rust theme={null} + use std::str::FromStr; + use polymarket_client_sdk_v2::POLYGON; + use polymarket_client_sdk_v2::auth::{LocalSigner, Signer}; + use polymarket_client_sdk_v2::clob::{Client, Config}; + + let private_key = std::env::var("POLYMARKET_PRIVATE_KEY")?; + let signer = LocalSigner::from_str(&private_key)? + .with_chain_id(Some(POLYGON)); + + // Derive L2 API credentials and initialize client in one step + let client = Client::new("https://clob.polymarket.com", Config::default())? + .authentication_builder(&signer) + .authenticate() + .await?; + ``` + + +*** + +## Signature Types + +When initializing the trading client, you must specify your wallet's **signature type** and **funder address**: + +| Wallet Type | ID | When to Use | Funder Address | +| ---------------- | --- | -------------------------------------------------------------------------------------------------------------- | --------------------------- | +| **EOA** | `0` | Standalone wallet — you pay your own gas (POL for gas) | Your EOA wallet address | +| **POLY\_PROXY** | `1` | Existing Polymarket proxy wallet flow | Your proxy wallet address | +| **GNOSIS\_SAFE** | `2` | Existing Gnosis Safe wallet flow | Your Safe wallet address | +| **POLY\_1271** | `3` | Deposit wallet flow for new API users. Orders are signed by the owner/session signer and validated by ERC-1271 | Your deposit wallet address | + + + New API users should use deposit wallets with signature type `3`. Existing + Proxy and Safe users are unaffected and can keep using signature types `1` and + `2`. Type `0` is for standalone EOA wallets only. + + +### Initialize the Trading Client + + + ```typescript TypeScript theme={null} + const depositWalletAddress = process.env.DEPOSIT_WALLET_ADDRESS!; + + const client = new ClobClient({ + host: "https://clob.polymarket.com", + chain: 137, + signer, + creds: apiCreds, + signatureType: 3, // POLY_1271 + funderAddress: depositWalletAddress, + }); + ``` + + ```python Python theme={null} + deposit_wallet_address = os.getenv("DEPOSIT_WALLET_ADDRESS") + + client = ClobClient( + "https://clob.polymarket.com", + key=private_key, + chain_id=137, + creds=api_creds, + signature_type=3, # POLY_1271 + funder=deposit_wallet_address + ) + ``` + + ```rust Rust theme={null} + use polymarket_client_sdk_v2::clob::types::SignatureType; + + let deposit_wallet = std::env::var("DEPOSIT_WALLET_ADDRESS")?.parse()?; + + let client = Client::new("https://clob.polymarket.com", Config::default())? + .authentication_builder(&signer) + .funder(deposit_wallet) + .signature_type(SignatureType::Poly1271) + .authenticate() + .await?; + ``` + + +*** + +## REST API Headers + +If you're using the REST API directly (without the SDK), you need to attach authentication headers to each request. + +**L1 Headers** — for creating or deriving API credentials: + +| Header | Description | +| ---------------- | ------------------- | +| `POLY_ADDRESS` | Your wallet address | +| `POLY_SIGNATURE` | EIP-712 signature | +| `POLY_TIMESTAMP` | Unix timestamp | +| `POLY_NONCE` | Request nonce | + +**L2 Headers** — for all trading operations (orders, cancellations, queries): + +| Header | Description | +| ----------------- | ------------------------------------ | +| `POLY_ADDRESS` | Your wallet address | +| `POLY_SIGNATURE` | HMAC-SHA256 signature of the request | +| `POLY_TIMESTAMP` | Unix timestamp | +| `POLY_API_KEY` | Your API key | +| `POLY_PASSPHRASE` | Your API passphrase | + + + Even with L2 authentication, methods that create orders still require the + user's private key for EIP-712 order payload signing. L2 credentials + authenticate the request, but the order itself must be signed by the key. + + +*** + +## Client Methods + + + + Market data, orderbooks, prices, and spreads — no auth required. + + + + Sign orders and derive API credentials with your private key. + + + + Place orders, cancel orders, query trades, and manage notifications. + + + + Track orders and trades attributed to your builder code. + + + +*** + +## Server Infrastructure + +The CLOB matching engine runs in the following regions: + +* **Primary Servers**: eu-west-2 +* **Closest Non-Georestricted Region**: eu-west-1 + + + **Direct co-location available.** Users who complete the [KYC/KYB + form](https://docs.google.com/forms/d/e/1FAIpQLSfY-3Dl3yxq8HKFjFad8YzKZmm0k3Gdg29HD6gL-K-AmI6KXw/viewform) can get access to co-locate + directly in `eu-west-2` for the lowest possible latency to Polymarket's + primary servers. See [Geographic + Restrictions](/api-reference/geoblock#server-infrastructure) for full + geographic availability details. + + +*** + +## What Is in This Section + + + + Place your first order end-to-end + + + + Reading the orderbook, prices, spreads, and midpoints + + + + Order types, tick sizes, creating, cancelling, and querying orders + + + + Fee structure, fee-enabled markets, and maker rebates + + + + Execute onchain operations without paying gas + + + + Split, merge, and redeem outcome tokens + + + + Deposit and withdraw funds across chains + + diff --git a/PolymarketDocumentation-main/docs/developers/CLOB/trades/trades.md b/PolymarketDocumentation-main/docs/developers/CLOB/trades/trades.md new file mode 100644 index 00000000..52a2176c --- /dev/null +++ b/PolymarketDocumentation-main/docs/developers/CLOB/trades/trades.md @@ -0,0 +1,265 @@ +> ## Documentation Index +> Fetch the complete documentation index at: https://docs.polymarket.com/llms.txt +> Use this file to discover all available pages before exploring further. + +# Overview + +> Trading on the Polymarket CLOB + +Polymarket's CLOB (Central Limit Order Book) is a hybrid-decentralized trading system — offchain order matching with onchain settlement via the [Exchange contract](https://github.com/Polymarket/ctf-exchange/tree/main/src) ([audited by Chainsecurity](https://github.com/Polymarket/ctf-exchange/blob/main/audit/ChainSecurity_Polymarket_Exchange_audit.pdf)). All trading is non-custodial. Orders are [EIP-712](https://eips.ethereum.org/EIPS/eip-712) signed messages, and matched trades settle atomically on Polygon. The operator cannot set prices or execute unauthorized trades. + +We recommend using the open-source SDK clients, which handle order signing, authentication, and submission: + + + +

+ npm install @polymarket/clob-client-v2 viem +

+
+ + +

pip install py-clob-client-v2

+
+ + +

+ cargo add polymarket\_client\_sdk\_v2 --features clob +

+
+
+ + + You can also use the REST API directly, but you'll need to manage [EIP-712 + order + signing](https://github.com/Polymarket/clob-client-v2/blob/main/src/signing/eip712.ts) + and [HMAC authentication + headers](https://github.com/Polymarket/clob-client-v2/blob/main/src/signing/hmac.ts) + yourself. See [REST API Headers](#rest-api-headers) below. + + +*** + +## Authentication + +The CLOB uses two levels of authentication: + +| Level | Method | Purpose | +| ------ | ------------------------------- | ----------------------------------------- | +| **L1** | EIP-712 signature (private key) | Create or derive API credentials | +| **L2** | HMAC-SHA256 (API credentials) | Place orders, cancel orders, query trades | + +You use your private key once to derive **L2 credentials** (API key, secret, passphrase), which authenticate all subsequent trading requests. + + + ```typescript TypeScript theme={null} + import { ClobClient } from "@polymarket/clob-client-v2"; + import { createWalletClient, http } from "viem"; + import { privateKeyToAccount } from "viem/accounts"; + + const account = privateKeyToAccount(process.env.PRIVATE_KEY as `0x${string}`); + const signer = createWalletClient({ account, transport: http() }); + + // Derive L2 API credentials + const tempClient = new ClobClient({ + host: "https://clob.polymarket.com", + chain: 137, + signer, + }); + const apiCreds = await tempClient.createOrDeriveApiKey(); + ``` + + ```python Python theme={null} + from py_clob_client_v2 import ClobClient + import os + + private_key = os.getenv("PRIVATE_KEY") + + # Derive L2 API credentials + temp_client = ClobClient("https://clob.polymarket.com", key=private_key, chain_id=137) + api_creds = temp_client.create_or_derive_api_key() + ``` + + ```rust Rust theme={null} + use std::str::FromStr; + use polymarket_client_sdk_v2::POLYGON; + use polymarket_client_sdk_v2::auth::{LocalSigner, Signer}; + use polymarket_client_sdk_v2::clob::{Client, Config}; + + let private_key = std::env::var("POLYMARKET_PRIVATE_KEY")?; + let signer = LocalSigner::from_str(&private_key)? + .with_chain_id(Some(POLYGON)); + + // Derive L2 API credentials and initialize client in one step + let client = Client::new("https://clob.polymarket.com", Config::default())? + .authentication_builder(&signer) + .authenticate() + .await?; + ``` + + +*** + +## Signature Types + +When initializing the trading client, you must specify your wallet's **signature type** and **funder address**: + +| Wallet Type | ID | When to Use | Funder Address | +| ---------------- | --- | -------------------------------------------------------------------------------------------------------------- | --------------------------- | +| **EOA** | `0` | Standalone wallet — you pay your own gas (POL for gas) | Your EOA wallet address | +| **POLY\_PROXY** | `1` | Existing Polymarket proxy wallet flow | Your proxy wallet address | +| **GNOSIS\_SAFE** | `2` | Existing Gnosis Safe wallet flow | Your Safe wallet address | +| **POLY\_1271** | `3` | Deposit wallet flow for new API users. Orders are signed by the owner/session signer and validated by ERC-1271 | Your deposit wallet address | + + + New API users should use deposit wallets with signature type `3`. Existing + Proxy and Safe users are unaffected and can keep using signature types `1` and + `2`. Type `0` is for standalone EOA wallets only. + + +### Initialize the Trading Client + + + ```typescript TypeScript theme={null} + const depositWalletAddress = process.env.DEPOSIT_WALLET_ADDRESS!; + + const client = new ClobClient({ + host: "https://clob.polymarket.com", + chain: 137, + signer, + creds: apiCreds, + signatureType: 3, // POLY_1271 + funderAddress: depositWalletAddress, + }); + ``` + + ```python Python theme={null} + deposit_wallet_address = os.getenv("DEPOSIT_WALLET_ADDRESS") + + client = ClobClient( + "https://clob.polymarket.com", + key=private_key, + chain_id=137, + creds=api_creds, + signature_type=3, # POLY_1271 + funder=deposit_wallet_address + ) + ``` + + ```rust Rust theme={null} + use polymarket_client_sdk_v2::clob::types::SignatureType; + + let deposit_wallet = std::env::var("DEPOSIT_WALLET_ADDRESS")?.parse()?; + + let client = Client::new("https://clob.polymarket.com", Config::default())? + .authentication_builder(&signer) + .funder(deposit_wallet) + .signature_type(SignatureType::Poly1271) + .authenticate() + .await?; + ``` + + +*** + +## REST API Headers + +If you're using the REST API directly (without the SDK), you need to attach authentication headers to each request. + +**L1 Headers** — for creating or deriving API credentials: + +| Header | Description | +| ---------------- | ------------------- | +| `POLY_ADDRESS` | Your wallet address | +| `POLY_SIGNATURE` | EIP-712 signature | +| `POLY_TIMESTAMP` | Unix timestamp | +| `POLY_NONCE` | Request nonce | + +**L2 Headers** — for all trading operations (orders, cancellations, queries): + +| Header | Description | +| ----------------- | ------------------------------------ | +| `POLY_ADDRESS` | Your wallet address | +| `POLY_SIGNATURE` | HMAC-SHA256 signature of the request | +| `POLY_TIMESTAMP` | Unix timestamp | +| `POLY_API_KEY` | Your API key | +| `POLY_PASSPHRASE` | Your API passphrase | + + + Even with L2 authentication, methods that create orders still require the + user's private key for EIP-712 order payload signing. L2 credentials + authenticate the request, but the order itself must be signed by the key. + + +*** + +## Client Methods + + + + Market data, orderbooks, prices, and spreads — no auth required. + + + + Sign orders and derive API credentials with your private key. + + + + Place orders, cancel orders, query trades, and manage notifications. + + + + Track orders and trades attributed to your builder code. + + + +*** + +## Server Infrastructure + +The CLOB matching engine runs in the following regions: + +* **Primary Servers**: eu-west-2 +* **Closest Non-Georestricted Region**: eu-west-1 + + + **Direct co-location available.** Users who complete the [KYC/KYB + form](https://docs.google.com/forms/d/e/1FAIpQLSfY-3Dl3yxq8HKFjFad8YzKZmm0k3Gdg29HD6gL-K-AmI6KXw/viewform) can get access to co-locate + directly in `eu-west-2` for the lowest possible latency to Polymarket's + primary servers. See [Geographic + Restrictions](/api-reference/geoblock#server-infrastructure) for full + geographic availability details. + + +*** + +## What Is in This Section + + + + Place your first order end-to-end + + + + Reading the orderbook, prices, spreads, and midpoints + + + + Order types, tick sizes, creating, cancelling, and querying orders + + + + Fee structure, fee-enabled markets, and maker rebates + + + + Execute onchain operations without paying gas + + + + Split, merge, and redeem outcome tokens + + + + Deposit and withdraw funds across chains + + diff --git a/PolymarketDocumentation-main/docs/developers/CLOB/websocket/market-channel.md b/PolymarketDocumentation-main/docs/developers/CLOB/websocket/market-channel.md new file mode 100644 index 00000000..bd7708f3 --- /dev/null +++ b/PolymarketDocumentation-main/docs/developers/CLOB/websocket/market-channel.md @@ -0,0 +1,235 @@ +> ## Documentation Index +> Fetch the complete documentation index at: https://docs.polymarket.com/llms.txt +> Use this file to discover all available pages before exploring further. + +# Market Channel + +> Real-time orderbook, price, and trade data + +Public channel for market data updates (level 2 price data). Subscribe with asset IDs to receive orderbook snapshots, price changes, trade executions, and market events. + +## Endpoint + +``` +wss://ws-subscriptions-clob.polymarket.com/ws/market +``` + +## Subscription + +```json theme={null} +{ + "assets_ids": ["", ""], + "type": "market", + "custom_feature_enabled": true +} +``` + +Set `custom_feature_enabled: true` to receive `best_bid_ask`, `new_market`, and `market_resolved` events. + +## Message Types + +Each message includes an `event_type` field identifying the type. + +### book + +Emitted when first subscribed to a market and when there is a trade that affects the book. + +```json theme={null} +{ + "event_type": "book", + "asset_id": "65818619657568813474341868652308942079804919287380422192892211131408793125422", + "market": "0xbd31dc8a20211944f6b70f31557f1001557b59905b7738480ca09bd4532f84af", + "bids": [ + { "price": ".48", "size": "30" }, + { "price": ".49", "size": "20" }, + { "price": ".50", "size": "15" } + ], + "asks": [ + { "price": ".52", "size": "25" }, + { "price": ".53", "size": "60" }, + { "price": ".54", "size": "10" } + ], + "timestamp": "123456789000", + "hash": "0x0...." +} +``` + +### price\_change + +Emitted when a new order is placed or an order is cancelled. + +```json theme={null} +{ + "market": "0x5f65177b394277fd294cd75650044e32ba009a95022d88a0c1d565897d72f8f1", + "price_changes": [ + { + "asset_id": "71321045679252212594626385532706912750332728571942532289631379312455583992563", + "price": "0.5", + "size": "200", + "side": "BUY", + "hash": "56621a121a47ed9333273e21c83b660cff37ae50", + "best_bid": "0.5", + "best_ask": "1" + }, + { + "asset_id": "52114319501245915516055106046884209969926127482827954674443846427813813222426", + "price": "0.5", + "size": "200", + "side": "SELL", + "hash": "1895759e4df7a796bf4f1c5a5950b748306923e2", + "best_bid": "0", + "best_ask": "0.5" + } + ], + "timestamp": "1757908892351", + "event_type": "price_change" +} +``` + +A `size` of `"0"` means the price level has been removed from the book. + +### tick\_size\_change + +Emitted when the minimum tick size of a market changes. This happens when the book's price reaches the limits: price > 0.96 or price \< 0.04. + +```json theme={null} +{ + "event_type": "tick_size_change", + "asset_id": "65818619657568813474341868652308942079804919287380422192892211131408793125422", + "market": "0xbd31dc8a20211944f6b70f31557f1001557b59905b7738480ca09bd4532f84af", + "old_tick_size": "0.01", + "new_tick_size": "0.001", + "timestamp": "100000000" +} +``` + +### last\_trade\_price + +Emitted when a maker and taker order is matched, creating a trade event. + +```json theme={null} +{ + "asset_id": "114122071509644379678018727908709560226618148003371446110114509806601493071694", + "event_type": "last_trade_price", + "fee_rate_bps": "0", + "market": "0x6a67b9d828d53862160e470329ffea5246f338ecfffdf2cab45211ec578b0347", + "price": "0.456", + "side": "BUY", + "size": "219.217767", + "timestamp": "1750428146322" +} +``` + +### best\_bid\_ask + +Requires `custom_feature_enabled: true`. + +Emitted when the best bid or ask prices for a market change. + +```json theme={null} +{ + "event_type": "best_bid_ask", + "market": "0x0005c0d312de0be897668695bae9f32b624b4a1ae8b140c49f08447fcc74f442", + "asset_id": "85354956062430465315924116860125388538595433819574542752031640332592237464430", + "best_bid": "0.73", + "best_ask": "0.77", + "spread": "0.04", + "timestamp": "1766789469958" +} +``` + +### new\_market + +Requires `custom_feature_enabled: true`. + +Emitted when a new market is created. + +The payload also includes market metadata fields such as `tags`, +`condition_id`, `active`, `clob_token_ids`, `sports_market_type`, `line`, +`game_start_time`, `order_price_min_tick_size`, `group_item_title`, +`taker_base_fee`, `fees_enabled`, and `fee_schedule`. + +Where a `FeeSchedule` object is of the form: + +| Name | Type | Description | +| ------------ | ------- | --------------------------------- | +| exponent | string | fee curve exponent | +| rate | string | fee rate | +| taker\_only | boolean | whether fee applies to taker only | +| rebate\_rate | string | maker rebate rate | + +```json theme={null} +{ + "id": "1031769", + "question": "Will NVIDIA (NVDA) close above $240 end of January?", + "market": "0x311d0c4b6671ab54af4970c06fcf58662516f5168997bdda209ec3db5aa6b0c1", + "slug": "nvda-above-240-on-january-30-2026", + "description": "This market will resolve to \"Yes\" if the official closing price...", + "assets_ids": [ + "76043073756653678226373981964075571318267289248134717369284518995922789326425", + "31690934263385727664202099278545688007799199447969475608906331829650099442770" + ], + "outcomes": ["Yes", "No"], + "event_message": { + "id": "125819", + "ticker": "nvda-above-in-january-2026", + "slug": "nvda-above-in-january-2026", + "title": "Will NVIDIA (NVDA) close above ___ end of January?", + "description": "This market will resolve to \"Yes\" if the official closing price..." + }, + "timestamp": "1766790415550", + "event_type": "new_market", + "tags": ["stocks"], + "condition_id": "0x311d0c4b6671ab54af4970c06fcf58662516f5168997bdda209ec3db5aa6b0c1", + "active": true, + "clob_token_ids": [ + "76043073756653678226373981964075571318267289248134717369284518995922789326425", + "31690934263385727664202099278545688007799199447969475608906331829650099442770" + ], + "sports_market_type": "", + "line": "", + "game_start_time": "", + "order_price_min_tick_size": "0.01", + "group_item_title": "NVDA above $240", + "taker_base_fee": "0", + "fees_enabled": true, + "fee_schedule": { + "exponent": "2", + "rate": "0.02", + "taker_only": true, + "rebate_rate": "0" + } +} +``` + +### market\_resolved + +Requires `custom_feature_enabled: true`. + +Emitted when a market is resolved. + +```json theme={null} +{ + "id": "1031769", + "question": "Will NVIDIA (NVDA) close above $240 end of January?", + "market": "0x311d0c4b6671ab54af4970c06fcf58662516f5168997bdda209ec3db5aa6b0c1", + "slug": "nvda-above-240-on-january-30-2026", + "description": "This market will resolve to \"Yes\" if the official closing price...", + "assets_ids": [ + "76043073756653678226373981964075571318267289248134717369284518995922789326425", + "31690934263385727664202099278545688007799199447969475608906331829650099442770" + ], + "outcomes": ["Yes", "No"], + "winning_asset_id": "76043073756653678226373981964075571318267289248134717369284518995922789326425", + "winning_outcome": "Yes", + "event_message": { + "id": "125819", + "ticker": "nvda-above-in-january-2026", + "slug": "nvda-above-in-january-2026", + "title": "Will NVIDIA (NVDA) close above ___ end of January?", + "description": "This market will resolve to \"Yes\" if the official closing price..." + }, + "timestamp": "1766790415550", + "event_type": "market_resolved" +} +``` diff --git a/PolymarketDocumentation-main/docs/developers/CLOB/websocket/user-channel.md b/PolymarketDocumentation-main/docs/developers/CLOB/websocket/user-channel.md new file mode 100644 index 00000000..8e8fff43 --- /dev/null +++ b/PolymarketDocumentation-main/docs/developers/CLOB/websocket/user-channel.md @@ -0,0 +1,124 @@ +> ## Documentation Index +> Fetch the complete documentation index at: https://docs.polymarket.com/llms.txt +> Use this file to discover all available pages before exploring further. + +# User Channel + +> Authenticated order and trade updates + +Authenticated channel for updates related to your orders and trades, filtered by API key. + +## Endpoint + +``` +wss://ws-subscriptions-clob.polymarket.com/ws/user +``` + +## Authentication + +Include API credentials in your subscription message: + +```json theme={null} +{ + "auth": { + "apiKey": "your-api-key", + "secret": "your-api-secret", + "passphrase": "your-passphrase" + }, + "markets": ["0x1234...condition_id"], + "type": "user" +} +``` + + + Never expose your API credentials in client-side code. Use the user channel + only from server environments. + + +## Message Types + +Each message includes a `type` field identifying the event. + +### trade + +Emitted when: + +* A market order is matched (`MATCHED`) +* A limit order for the user is included in a trade (`MATCHED`) +* Subsequent status changes for the trade (`MINED`, `CONFIRMED`, `RETRYING`, `FAILED`) + +```json theme={null} +{ + "asset_id": "52114319501245915516055106046884209969926127482827954674443846427813813222426", + "event_type": "trade", + "id": "28c4d2eb-bbea-40e7-a9f0-b2fdb56b2c2e", + "last_update": "1672290701", + "maker_orders": [ + { + "asset_id": "52114319501245915516055106046884209969926127482827954674443846427813813222426", + "matched_amount": "10", + "order_id": "0xff354cd7ca7539dfa9c28d90943ab5779a4eac34b9b37a757d7b32bdfb11790b", + "outcome": "YES", + "owner": "9180014b-33c8-9240-a14b-bdca11c0a465", + "price": "0.57" + } + ], + "market": "0xbd31dc8a20211944f6b70f31557f1001557b59905b7738480ca09bd4532f84af", + "match_time": "1672290701", + "outcome": "YES", + "owner": "9180014b-33c8-9240-a14b-bdca11c0a465", + "price": "0.57", + "side": "BUY", + "size": "10", + "status": "MATCHED", + "taker_order_id": "0x06bc63e346ed4ceddce9efd6b3af37c8f8f440c92fe7da6b2d0f9e4ccbc50c42", + "timestamp": "1672290701", + "trade_owner": "9180014b-33c8-9240-a14b-bdca11c0a465", + "type": "TRADE" +} +``` + +#### Trade Statuses + +``` +MATCHED → MINED → CONFIRMED + ↓ ↑ +RETRYING ───┘ + ↓ + FAILED +``` + +| Status | Terminal | Description | +| ----------- | -------- | ----------------------------------------------------------------------------------------------- | +| `MATCHED` | No | Trade has been matched and sent to the executor service by the operator | +| `MINED` | No | Trade observed to be mined into the chain, no finality threshold established | +| `CONFIRMED` | Yes | Trade has achieved strong probabilistic finality and was successful | +| `RETRYING` | No | Trade transaction has failed (revert or reorg) and is being retried/resubmitted by the operator | +| `FAILED` | Yes | Trade has failed and is not being retried | + +### order + +Emitted when: + +* An order is placed (`PLACEMENT`) +* An order is updated — some of it is matched (`UPDATE`) +* An order is cancelled (`CANCELLATION`) + +```json theme={null} +{ + "asset_id": "52114319501245915516055106046884209969926127482827954674443846427813813222426", + "associate_trades": null, + "event_type": "order", + "id": "0xff354cd7ca7539dfa9c28d90943ab5779a4eac34b9b37a757d7b32bdfb11790b", + "market": "0xbd31dc8a20211944f6b70f31557f1001557b59905b7738480ca09bd4532f84af", + "order_owner": "9180014b-33c8-9240-a14b-bdca11c0a465", + "original_size": "10", + "outcome": "YES", + "owner": "9180014b-33c8-9240-a14b-bdca11c0a465", + "price": "0.57", + "side": "SELL", + "size_matched": "0", + "timestamp": "1672290687", + "type": "PLACEMENT" +} +``` diff --git a/PolymarketDocumentation-main/docs/developers/CLOB/websocket/wss-auth.md b/PolymarketDocumentation-main/docs/developers/CLOB/websocket/wss-auth.md new file mode 100644 index 00000000..578a7d66 --- /dev/null +++ b/PolymarketDocumentation-main/docs/developers/CLOB/websocket/wss-auth.md @@ -0,0 +1,181 @@ +> ## Documentation Index +> Fetch the complete documentation index at: https://docs.polymarket.com/llms.txt +> Use this file to discover all available pages before exploring further. + +# Overview + +> Real-time market data and trading updates via WebSocket + +Polymarket provides WebSocket channels for near real-time streaming of orderbook data, trades, and personal order activity. There are four available channels: `market`, `user`, `sports`, and `RTDS` (Real-Time Data Socket). + +## Channels + +| Channel | Endpoint | Auth | +| ----------------------------------- | ------------------------------------------------------ | -------- | +| Market | `wss://ws-subscriptions-clob.polymarket.com/ws/market` | No | +| User | `wss://ws-subscriptions-clob.polymarket.com/ws/user` | Yes | +| Sports | `wss://sports-api.polymarket.com/ws` | No | +| [RTDS](/market-data/websocket/rtds) | `wss://ws-live-data.polymarket.com` | Optional | + +### Market Channel + +| Type | Description | Custom Feature | +| ------------------ | ----------------------- | -------------- | +| `book` | Full orderbook snapshot | No | +| `price_change` | Price level updates | No | +| `tick_size_change` | Tick size changes | No | +| `last_trade_price` | Trade executions | No | +| `best_bid_ask` | Best prices update | Yes | +| `new_market` | New market created | Yes | +| `market_resolved` | Market resolution | Yes | + +Types marked "Custom Feature" require `custom_feature_enabled: true` in your subscription. + +### User Channel + +| Type | Description | +| ------- | --------------------------------------------- | +| `trade` | Trade lifecycle updates (MATCHED → CONFIRMED) | +| `order` | Order placements, updates, and cancellations | + +### Sports + +| Type | Description | +| -------------- | ------------------------------------- | +| `sport_result` | Live game scores, periods, and status | + +## Subscribing + +Send a subscription message after connecting to specify which data you want to receive. + +### Market Channel + +```json theme={null} +{ + "assets_ids": [ + "21742633143463906290569050155826241533067272736897614950488156847949938836455", + "48331043336612883890938759509493159234755048973500640148014422747788308965732" + ], + "type": "market", + "custom_feature_enabled": true +} +``` + +| Field | Type | Description | +| ------------------------ | --------- | ----------------------------------------------------------------- | +| `assets_ids` | string\[] | Token IDs to subscribe to | +| `type` | string | Channel identifier | +| `custom_feature_enabled` | boolean | Enable `best_bid_ask`, `new_market`, and `market_resolved` events | + +### User Channel + +```json theme={null} +{ + "auth": { + "apiKey": "your-api-key", + "secret": "your-api-secret", + "passphrase": "your-passphrase" + }, + "markets": ["0x1234...condition_id"], + "type": "user" +} +``` + + + The `auth` fields (`apiKey`, `secret`, `passphrase`) are **only required for + the user channel**. For the market channel, these fields are optional and can + be omitted. + + +| Field | Type | Description | +| --------- | --------- | -------------------------------------------------- | +| `auth` | object | API credentials (`apiKey`, `secret`, `passphrase`) | +| `markets` | string\[] | Condition IDs to receive events for | +| `type` | string | Channel identifier | + + + The user channel subscribes by **condition IDs** (market identifiers), not + asset IDs. Each market has one condition ID but two asset IDs (Yes and No + tokens). + + +### Sports Channel + +No subscription message required. Connect and start receiving data for all active sports events. + +## Dynamic Subscription + +Modify subscriptions without reconnecting. + +### Subscribe to more assets + +```json theme={null} +{ + "assets_ids": ["new_asset_id_1", "new_asset_id_2"], + "operation": "subscribe", + "custom_feature_enabled": true +} +``` + +### Unsubscribe from assets + +```json theme={null} +{ + "assets_ids": ["asset_id_to_remove"], + "operation": "unsubscribe" +} +``` + +For the user channel, use `markets` instead of `assets_ids`: + +```json theme={null} +{ + "markets": ["0x1234...condition_id"], + "operation": "subscribe" +} +``` + +## Heartbeats + +### Market and User Channels + +Send `PING` every 10 seconds. The server responds with `PONG`. + +``` +PING +``` + +### Sports Channel + +The server sends `ping` every 5 seconds. Respond with `pong` within 10 seconds. + +``` +pong +``` + + + If you don't respond to the server's ping within 10 seconds, the connection + will be closed. + + +## Troubleshooting + + + Send a valid subscription message immediately after connecting. The server may + close connections that don't subscribe within a timeout period. + + + + You're not sending heartbeats. Send `PING` every 10 seconds for market/user + channels, or respond to server `ping` with `pong` for the sports channel. + + + + 1. Verify your asset IDs or condition IDs are correct 2. Check that the + markets are active (not resolved) 3. Set `custom_feature_enabled: true` if + expecting `best_bid_ask`, `new_market`, or `market_resolved` events + + + + Verify your API credentials are correct and haven't expired. + diff --git a/PolymarketDocumentation-main/docs/developers/CLOB/websocket/wss-overview.md b/PolymarketDocumentation-main/docs/developers/CLOB/websocket/wss-overview.md new file mode 100644 index 00000000..578a7d66 --- /dev/null +++ b/PolymarketDocumentation-main/docs/developers/CLOB/websocket/wss-overview.md @@ -0,0 +1,181 @@ +> ## Documentation Index +> Fetch the complete documentation index at: https://docs.polymarket.com/llms.txt +> Use this file to discover all available pages before exploring further. + +# Overview + +> Real-time market data and trading updates via WebSocket + +Polymarket provides WebSocket channels for near real-time streaming of orderbook data, trades, and personal order activity. There are four available channels: `market`, `user`, `sports`, and `RTDS` (Real-Time Data Socket). + +## Channels + +| Channel | Endpoint | Auth | +| ----------------------------------- | ------------------------------------------------------ | -------- | +| Market | `wss://ws-subscriptions-clob.polymarket.com/ws/market` | No | +| User | `wss://ws-subscriptions-clob.polymarket.com/ws/user` | Yes | +| Sports | `wss://sports-api.polymarket.com/ws` | No | +| [RTDS](/market-data/websocket/rtds) | `wss://ws-live-data.polymarket.com` | Optional | + +### Market Channel + +| Type | Description | Custom Feature | +| ------------------ | ----------------------- | -------------- | +| `book` | Full orderbook snapshot | No | +| `price_change` | Price level updates | No | +| `tick_size_change` | Tick size changes | No | +| `last_trade_price` | Trade executions | No | +| `best_bid_ask` | Best prices update | Yes | +| `new_market` | New market created | Yes | +| `market_resolved` | Market resolution | Yes | + +Types marked "Custom Feature" require `custom_feature_enabled: true` in your subscription. + +### User Channel + +| Type | Description | +| ------- | --------------------------------------------- | +| `trade` | Trade lifecycle updates (MATCHED → CONFIRMED) | +| `order` | Order placements, updates, and cancellations | + +### Sports + +| Type | Description | +| -------------- | ------------------------------------- | +| `sport_result` | Live game scores, periods, and status | + +## Subscribing + +Send a subscription message after connecting to specify which data you want to receive. + +### Market Channel + +```json theme={null} +{ + "assets_ids": [ + "21742633143463906290569050155826241533067272736897614950488156847949938836455", + "48331043336612883890938759509493159234755048973500640148014422747788308965732" + ], + "type": "market", + "custom_feature_enabled": true +} +``` + +| Field | Type | Description | +| ------------------------ | --------- | ----------------------------------------------------------------- | +| `assets_ids` | string\[] | Token IDs to subscribe to | +| `type` | string | Channel identifier | +| `custom_feature_enabled` | boolean | Enable `best_bid_ask`, `new_market`, and `market_resolved` events | + +### User Channel + +```json theme={null} +{ + "auth": { + "apiKey": "your-api-key", + "secret": "your-api-secret", + "passphrase": "your-passphrase" + }, + "markets": ["0x1234...condition_id"], + "type": "user" +} +``` + + + The `auth` fields (`apiKey`, `secret`, `passphrase`) are **only required for + the user channel**. For the market channel, these fields are optional and can + be omitted. + + +| Field | Type | Description | +| --------- | --------- | -------------------------------------------------- | +| `auth` | object | API credentials (`apiKey`, `secret`, `passphrase`) | +| `markets` | string\[] | Condition IDs to receive events for | +| `type` | string | Channel identifier | + + + The user channel subscribes by **condition IDs** (market identifiers), not + asset IDs. Each market has one condition ID but two asset IDs (Yes and No + tokens). + + +### Sports Channel + +No subscription message required. Connect and start receiving data for all active sports events. + +## Dynamic Subscription + +Modify subscriptions without reconnecting. + +### Subscribe to more assets + +```json theme={null} +{ + "assets_ids": ["new_asset_id_1", "new_asset_id_2"], + "operation": "subscribe", + "custom_feature_enabled": true +} +``` + +### Unsubscribe from assets + +```json theme={null} +{ + "assets_ids": ["asset_id_to_remove"], + "operation": "unsubscribe" +} +``` + +For the user channel, use `markets` instead of `assets_ids`: + +```json theme={null} +{ + "markets": ["0x1234...condition_id"], + "operation": "subscribe" +} +``` + +## Heartbeats + +### Market and User Channels + +Send `PING` every 10 seconds. The server responds with `PONG`. + +``` +PING +``` + +### Sports Channel + +The server sends `ping` every 5 seconds. Respond with `pong` within 10 seconds. + +``` +pong +``` + + + If you don't respond to the server's ping within 10 seconds, the connection + will be closed. + + +## Troubleshooting + + + Send a valid subscription message immediately after connecting. The server may + close connections that don't subscribe within a timeout period. + + + + You're not sending heartbeats. Send `PING` every 10 seconds for market/user + channels, or respond to server `ping` with `pong` for the sports channel. + + + + 1. Verify your asset IDs or condition IDs are correct 2. Check that the + markets are active (not resolved) 3. Set `custom_feature_enabled: true` if + expecting `best_bid_ask`, `new_market`, or `market_resolved` events + + + + Verify your API credentials are correct and haven't expired. + diff --git a/PolymarketDocumentation-main/docs/developers/CTF/deployment-resources.md b/PolymarketDocumentation-main/docs/developers/CTF/deployment-resources.md new file mode 100644 index 00000000..4bea7456 --- /dev/null +++ b/PolymarketDocumentation-main/docs/developers/CTF/deployment-resources.md @@ -0,0 +1,100 @@ +> ## Documentation Index +> Fetch the complete documentation index at: https://docs.polymarket.com/llms.txt +> Use this file to discover all available pages before exploring further. + +# Contracts + +> All Polymarket smart contract addresses, audits, and security resources + +All Polymarket contracts are deployed on **Polygon mainnet** (Chain ID: 137). This is the single source of truth for all contract addresses used across the platform. + +*** + +## Core Trading Contracts + +| Contract | Address | +| ------------------------ | -------------------------------------------------------------------------------------------------------------------------- | +| CTF Exchange | [`0xE111180000d2663C0091e4f400237545B87B996B`](https://polygonscan.com/address/0xE111180000d2663C0091e4f400237545B87B996B) | +| Neg Risk CTF Exchange | [`0xe2222d279d744050d28e00520010520000310F59`](https://polygonscan.com/address/0xe2222d279d744050d28e00520010520000310F59) | +| Neg Risk Adapter | [`0xd91E80cF2E7be2e162c6513ceD06f1dD0dA35296`](https://polygonscan.com/address/0xd91E80cF2E7be2e162c6513ceD06f1dD0dA35296) | +| Conditional Tokens (CTF) | [`0x4D97DCd97eC945f40cF65F87097ACe5EA0476045`](https://polygonscan.com/address/0x4D97DCd97eC945f40cF65F87097ACe5EA0476045) | + +*** + +## Combos Contracts + +| Contract | Address | +| --------------------------- | -------------------------------------------------------------------------------------------------------------------------- | +| PositionManager (proxy) | [`0x006F54F7f9A22e0000CC2AB60031000000ae9fEF`](https://polygonscan.com/address/0x006F54F7f9A22e0000CC2AB60031000000ae9fEF) | +| PositionManager (impl) | [`0x30c038F0Dae8dcC3E6AD51D016F50821D32Cb87e`](https://polygonscan.com/address/0x30c038F0Dae8dcC3E6AD51D016F50821D32Cb87e) | +| BinaryModule (proxy) | [`0x1000008dD9001B968442c1000017eaE6E0dA00Ba`](https://polygonscan.com/address/0x1000008dD9001B968442c1000017eaE6E0dA00Ba) | +| BinaryModule (impl) | [`0x492FEc596eC347459E1Ebe30b9245EB3B49B1BBa`](https://polygonscan.com/address/0x492FEc596eC347459E1Ebe30b9245EB3B49B1BBa) | +| NegRiskModule (proxy) | [`0x200000900045e3B6259600682756002200028933`](https://polygonscan.com/address/0x200000900045e3B6259600682756002200028933) | +| NegRiskModule (impl) | [`0xA61e7ca374F721D5b9FD5b0FEe6Fb90f27d448d7`](https://polygonscan.com/address/0xA61e7ca374F721D5b9FD5b0FEe6Fb90f27d448d7) | +| CombinatorialModule (proxy) | [`0x30000034706C7d8e12009DAB006Be20000c031A8`](https://polygonscan.com/address/0x30000034706C7d8e12009DAB006Be20000c031A8) | +| CombinatorialModule (impl) | [`0xb529b2430d78868422C47934d9d61cC9D0C53dBb`](https://polygonscan.com/address/0xb529b2430d78868422C47934d9d61cC9D0C53dBb) | +| Exchange (proxy) | [`0xe3333700cA9d93003F00f0F71f8515005F6c00Aa`](https://polygonscan.com/address/0xe3333700cA9d93003F00f0F71f8515005F6c00Aa) | +| Exchange (impl) | [`0x7345C6842b244926125ed4054905cAc49620B5dc`](https://polygonscan.com/address/0x7345C6842b244926125ed4054905cAc49620B5dc) | +| AutoRedeemer (proxy) | [`0xa1200000d0002264C9a1698e001292D00E1b00af`](https://polygonscan.com/address/0xa1200000d0002264C9a1698e001292D00E1b00af) | +| AutoRedeemer (impl) | [`0x64860bFD14fCcaAc09cd36f347784a9616AfB66C`](https://polygonscan.com/address/0x64860bFD14fCcaAc09cd36f347784a9616AfB66C) | + +*** + +## Collateral Contracts + +| Contract | Address | +| ------------------------------ | -------------------------------------------------------------------------------------------------------------------------- | +| pUSD — CollateralToken (proxy) | [`0xC011a7E12a19f7B1f670d46F03B03f3342E82DFB`](https://polygonscan.com/address/0xC011a7E12a19f7B1f670d46F03B03f3342E82DFB) | +| pUSD — CollateralToken (impl) | [`0x6bBCef9f7ef3B6C592c99e0f206a0DE94Ad0925f`](https://polygonscan.com/address/0x6bBCef9f7ef3B6C592c99e0f206a0DE94Ad0925f) | +| CollateralOnramp | [`0x93070a847efEf7F70739046A929D47a521F5B8ee`](https://polygonscan.com/address/0x93070a847efEf7F70739046A929D47a521F5B8ee) | +| CollateralOfframp | [`0x2957922Eb93258b93368531d39fAcCA3B4dC5854`](https://polygonscan.com/address/0x2957922Eb93258b93368531d39fAcCA3B4dC5854) | +| PermissionedRamp | [`0xebC2459Ec962869ca4c0bd1E06368272732BCb08`](https://polygonscan.com/address/0xebC2459Ec962869ca4c0bd1E06368272732BCb08) | +| CtfCollateralAdapter | [`0xAdA100Db00Ca00073811820692005400218FcE1f`](https://polygonscan.com/address/0xAdA100Db00Ca00073811820692005400218FcE1f) | +| NegRiskCtfCollateralAdapter | [`0xadA2005600Dec949baf300f4C6120000bDB6eAab`](https://polygonscan.com/address/0xadA2005600Dec949baf300f4C6120000bDB6eAab) | + +*** + +## Wallet Factory Contracts + +| Contract | Address | +| ------------------------ | -------------------------------------------------------------------------------------------------------------------------- | +| Deposit Wallet Factory | [`0x00000000000Fb5C9ADea0298D729A0CB3823Cc07`](https://polygonscan.com/address/0x00000000000Fb5C9ADea0298D729A0CB3823Cc07) | +| Deposit Wallet Beacon | [`0x7A18EDfe055488A3128f01F563e5B479D92ffc3a`](https://polygonscan.com/address/0x7A18EDfe055488A3128f01F563e5B479D92ffc3a) | +| Gnosis Safe Factory | [`0xaacfeea03eb1561c4e67d661e40682bd20e3541b`](https://polygonscan.com/address/0xaacfeea03eb1561c4e67d661e40682bd20e3541b) | +| Polymarket Proxy Factory | [`0xaB45c5A4B0c941a2F231C04C3f49182e1A254052`](https://polygonscan.com/address/0xaB45c5A4B0c941a2F231C04C3f49182e1A254052) | + +*** + +## Resolution Contracts + +| Contract | Address | +| --------------------- | -------------------------------------------------------------------------------------------------------------------------- | +| UMA Adapter | [`0x6A9D222616C90FcA5754cd1333cFD9b7fb6a4F74`](https://polygonscan.com/address/0x6A9D222616C90FcA5754cd1333cFD9b7fb6a4F74) | +| UMA Optimistic Oracle | [`0xCB1822859cEF82Cd2Eb4E6276C7916e692995130`](https://polygonscan.com/address/0xCB1822859cEF82Cd2Eb4E6276C7916e692995130) | + +*** + +## Security + +### Audits + +CTF Exchange V2 has been audited by two independent firms: + +| Auditor | Report | +| ---------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| Quantstamp | [CTF Exchange V2 — Quantstamp — March 2026](https://github.com/Polymarket/ctf-exchange-v2/blob/main/audits/CTF%20Exchange%20V2%20-%20Quantstamp%20-%20March%202026.pdf) | +| Cantina | [CTF Exchange V2 — Cantina — March 2026](https://github.com/Polymarket/ctf-exchange-v2/blob/main/audits/CTF%20Exchange%20V2%20-%20Cantina%20-%20March%202026.pdf) | + +### Bug Bounty + +Security vulnerabilities can be reported through the [Cantina bug bounty program](https://cantina.xyz/bounties/ff945ca2-2a6e-4b83-b1b6-7a0cd3b94bea). + +*** + +## Source Code + + + + Order matching and settlement contracts + + diff --git a/PolymarketDocumentation-main/docs/developers/CTF/merge.md b/PolymarketDocumentation-main/docs/developers/CTF/merge.md new file mode 100644 index 00000000..8016aa19 --- /dev/null +++ b/PolymarketDocumentation-main/docs/developers/CTF/merge.md @@ -0,0 +1,71 @@ +> ## Documentation Index +> Fetch the complete documentation index at: https://docs.polymarket.com/llms.txt +> Use this file to discover all available pages before exploring further. + +# Merge Tokens + +> Convert outcome token pairs back to pUSD + +**Merging** is the inverse of splitting — it converts a full set of outcome tokens back into pUSD collateral. For every 1 Yes token and 1 No token you merge, you receive \$1 pUSD. The condition must already be prepared on the CTF contract (via `prepareCondition`). + +``` +100 Yes tokens + 100 No tokens → $100 pUSD +``` + +## Prerequisites + +Before merging, you need: + +1. **Equal amounts** of both Yes and No tokens +2. **Condition ID** of the market +3. **Sufficient gas** for the transaction + + + Polymarket uses thin collateral adapter contracts for pUSD-native CTF actions. + Approve the adapter once, then route split, merge, and redeem actions through + it. For merge flows, the adapter calls the underlying CTF contract, receives + the released USDC.e collateral, wraps it into pUSD, and returns pUSD to your + wallet automatically. + + +## How It Works + +1. You call the adapter's merge flow with the amount and market details +2. One unit of each position in a full set is burned in return for 1 collateral unit +3. The adapter converts the released collateral into pUSD and returns pUSD to your wallet + +The operation is atomic — if you don't have enough of both tokens, the transaction reverts. + +## Function Parameters + + + pUSD (Polymarket USD) contract address: `0xC011a7E12a19f7B1f670d46F03B03f3342E82DFB` + + + + Always `0x0000...0000` (32 zero bytes) for Polymarket markets + + + + The market's condition ID, available from the Markets API + + + + Array of index sets: `[1, 2]` for binary markets + + + + The number of full sets to merge. Also the amount of collateral to receive. + + +## Next Steps + + + + Exchange winning tokens for pUSD after resolution + + + + Learn more about the Conditional Token Framework + + diff --git a/PolymarketDocumentation-main/docs/developers/CTF/overview.md b/PolymarketDocumentation-main/docs/developers/CTF/overview.md new file mode 100644 index 00000000..110ab18e --- /dev/null +++ b/PolymarketDocumentation-main/docs/developers/CTF/overview.md @@ -0,0 +1,140 @@ +> ## Documentation Index +> Fetch the complete documentation index at: https://docs.polymarket.com/llms.txt +> Use this file to discover all available pages before exploring further. + +# Conditional Token Framework + +> Onchain token mechanics powering Polymarket positions + +All outcomes on Polymarket are tokenized using the **Conditional Token Framework (CTF)**, an open standard developed by Gnosis. Understanding CTF operations enables advanced trading strategies, market making, and direct smart contract interactions. + +## What is CTF + +The Conditional Token Framework creates **ERC1155 tokens** representing outcomes of prediction markets. Each binary market has two tokens: + +| Token | Redeems for | Condition | +| ------- | ----------- | -------------------- | +| **Yes** | \$1.00 pUSD | Event occurs | +| **No** | \$1.00 pUSD | Event does not occur | + +These tokens are always **fully collateralized** — every Yes/No pair is backed by exactly \$1.00 pUSD locked in the CTF contract. + +## Core Operations + +CTF provides three fundamental operations: + + + + Convert pUSD into Yes + No token pairs + + + + Convert Yes + No pairs back to pUSD + + + + Exchange winning tokens for pUSD after resolution + + + +## Token Flow + + + + + + + +## Token Identifiers + +Each outcome token has a unique **position ID** (also called token ID or asset ID), computed onchain in three steps. + +### Step 1 - Condition ID + +``` +getConditionId(oracle, questionId, outcomeSlotCount) +``` + +| Parameter | Type | Value | +| ------------------ | --------- | ---------------------------------------------------------------- | +| `oracle` | `address` | [UMA CTF Adapter](https://github.com/Polymarket/uma-ctf-adapter) | +| `questionId` | `bytes32` | Hash of the UMA ancillary data | +| `outcomeSlotCount` | `uint` | `2` for all binary markets | + +### Step 2 - Collection IDs + +``` +getCollectionId(parentCollectionId, conditionId, indexSet) +``` + +| Parameter | Type | Value | +| -------------------- | --------- | --------------------------------------------------------------- | +| `parentCollectionId` | `bytes32` | `bytes32(0)` — always zero for top-level positions | +| `conditionId` | `bytes32` | The condition ID from step 1 | +| `indexSet` | `uint` | `1` (`0b01`) for the first outcome, `2` (`0b10`) for the second | + +The `indexSet` is a bitmask denoting which outcome slots belong to a collection. It must be a nonempty proper subset of the condition's outcome slots. Binary markets always have exactly two collections — one per outcome. + +### Step 3 - Position IDs + +``` +getPositionId(collateralToken, collectionId) +``` + +| Parameter | Type | Value | +| ----------------- | --------- | ----------------------------------------- | +| `collateralToken` | `IERC20` | pUSD contract address on Polygon | +| `collectionId` | `bytes32` | One of the two collection IDs from step 2 | + +The two resulting position IDs are the ERC1155 token IDs for the Yes and No outcomes of the market. + + + You can look up token IDs directly via the Gamma API (`GET /markets` or `GET /events` + — the `tokens` array on each market contains both outcome token IDs). Computing them + manually is only necessary for direct smart contract integration. + + +## Standard vs Neg Risk Markets + +Polymarket has two market types with different CTF configurations: + +| Feature | Standard Markets | Neg Risk Markets | +| ----------------- | ------------------- | --------------------- | +| CTF Contract | ConditionalTokens | ConditionalTokens | +| Exchange Contract | CTF Exchange | Neg Risk CTF Exchange | +| Multi-outcome | Independent markets | Linked via conversion | +| `negRisk` flag | `false` | `true` | + +For neg risk markets, an additional **conversion** operation allows exchanging a No token for Yes tokens in all other outcomes. See [Negative Risk Markets](/advanced/neg-risk) for details. + +## Contract Addresses + +See [Contracts](/resources/contracts) for all Polymarket smart contract addresses on Polygon. + +## Resources + + + + Gnosis Conditional Tokens smart contracts + + + + Python and TypeScript examples for onchain operations + + + +## Next Steps + + + + Create outcome token pairs from pUSD + + + + Convert token pairs back to pUSD + + + + Collect winnings after resolution + + diff --git a/PolymarketDocumentation-main/docs/developers/CTF/redeem.md b/PolymarketDocumentation-main/docs/developers/CTF/redeem.md new file mode 100644 index 00000000..0c602ad1 --- /dev/null +++ b/PolymarketDocumentation-main/docs/developers/CTF/redeem.md @@ -0,0 +1,102 @@ +> ## Documentation Index +> Fetch the complete documentation index at: https://docs.polymarket.com/llms.txt +> Use this file to discover all available pages before exploring further. + +# Redeem Tokens + +> Exchange winning tokens for pUSD after market resolution + +**Redeeming** converts winning outcome tokens into pUSD after a market resolves. Each winning token is worth exactly $1.00 — the losing token is worth $0. + +``` +Market resolves YES: + 100 Yes tokens → $100 pUSD + 100 No tokens → $0 +``` + +## When to Redeem + +Redemption is only available **after a market resolves**. Once the oracle reports the outcome: + +* **Winning tokens** can be redeemed for \$1.00 pUSD each +* **Losing tokens** are worth \$0 and produce no payout + + + You can redeem at any time after resolution — there's no deadline. Your + winning tokens will always be redeemable. + + +## How Resolution Works + +1. The market's end condition is met (event occurs, date passes, etc.) +2. The UMA Adapter oracle reports the outcome via `reportPayouts()` +3. The CTF contract records the payout vector +4. Redemption becomes available for winning tokens + +## Prerequisites + +Before redeeming: + +1. **Market must be resolved** — check the market's `resolved` status +2. **Hold winning tokens** — only the winning outcome can be redeemed +3. **Know the condition ID** — required for the redemption call + + + Polymarket uses thin collateral adapter contracts for pUSD-native CTF actions. + Approve the adapter once, then route split, merge, and redeem actions through + it. On redeem, the adapter burns the ERC1155 outcome tokens through the CTF + contract, receives USDC.e collateral, wraps it into pUSD, and returns pUSD to + your wallet automatically. + + +## Function Parameters + + + pUSD (Polymarket USD) contract address: `0xC011a7E12a19f7B1f670d46F03B03f3342E82DFB` + + + + Always `0x0000...0000` (32 zero bytes) for Polymarket markets + + + + The market's condition ID + + + + Array of index sets to redeem: `[1, 2]` redeems both outcomes (only winning + pays) + + + + Redemption burns your entire token balance for the condition — there is no + amount parameter. + + +## Payout Mechanics + +The CTF uses a **payout vector** to determine redemption values: + +| Outcome | Payout Vector | Redemption | +| -------- | ------------- | ----------------- | +| Yes wins | `[1, 0]` | Yes = $1, No = $0 | +| No wins | `[0, 1]` | Yes = $0, No = $1 | + +When you redeem through the adapter: + +* Your token balance is multiplied by the payout +* Winning tokens are burned +* The released collateral is wrapped into pUSD and transferred to your wallet +* Losing tokens are burned as well, but produce a \$0 payout + +## Next Steps + + + + Learn more about the Conditional Token Framework + + + + Understand how markets are resolved + + diff --git a/PolymarketDocumentation-main/docs/developers/CTF/split.md b/PolymarketDocumentation-main/docs/developers/CTF/split.md new file mode 100644 index 00000000..6e3f8bb5 --- /dev/null +++ b/PolymarketDocumentation-main/docs/developers/CTF/split.md @@ -0,0 +1,76 @@ +> ## Documentation Index +> Fetch the complete documentation index at: https://docs.polymarket.com/llms.txt +> Use this file to discover all available pages before exploring further. + +# Split Tokens + +> Convert pUSD into outcome token pairs + +**Splitting** converts pUSD collateral into a full (position) set of outcome tokens. For every \$1 pUSD you split, you receive 1 Yes token and 1 No token. + +``` +$100 pUSD → 100 Yes tokens + 100 No tokens +``` + +## Prerequisites + +Before splitting, ensure you have: + +1. **pUSD balance** on Polygon +2. **pUSD approval** for the CTF collateral adapter to spend your tokens +3. **Condition ID** of the market — the condition must already be prepared on the CTF contract (via `prepareCondition`) + + + Polymarket uses thin collateral adapter contracts for pUSD-native CTF actions. + Approve the adapter once, then route split, merge, and redeem actions through + it. The adapter handles the CTF collateral plumbing so user-facing flows stay + in pUSD. + + + + If the partition is trivial, invalid, or refers to more slots than the + condition is prepared with, the transaction will revert. + + +## How It Works + +1. You approve the CTF collateral adapter to spend your pUSD +2. You call the adapter's split flow with the amount and market details +3. The adapter calls the underlying CTF contract and mints both outcome tokens + +The operation is atomic — if any step fails, the entire transaction reverts. + +## Function Parameters + + + pUSD (Polymarket USD) contract address: `0xC011a7E12a19f7B1f670d46F03B03f3342E82DFB` + + + + Always `0x0000...0000` (32 zero bytes) for Polymarket markets + + + + The market's condition ID, available from the Markets API + + + + Array of index sets: `[1, 2]` for binary markets (Yes = 1, No = 2) + + + + The amount of collateral or stake to split. Also the number of full sets to + receive. + + +## Next Steps + + + + Convert token pairs back to pUSD + + + + Place orders using your newly split tokens + + diff --git a/PolymarketDocumentation-main/docs/developers/RTDS/RTDS-comments.md b/PolymarketDocumentation-main/docs/developers/RTDS/RTDS-comments.md new file mode 100644 index 00000000..0e274231 --- /dev/null +++ b/PolymarketDocumentation-main/docs/developers/RTDS/RTDS-comments.md @@ -0,0 +1,554 @@ +> ## Documentation Index +> Fetch the complete documentation index at: https://docs.polymarket.com/llms.txt +> Use this file to discover all available pages before exploring further. + +# Real-Time Data Socket + +> Stream comments, crypto prices, and equity prices via WebSocket + +The Polymarket Real-Time Data Socket (RTDS) is a WebSocket-based streaming service that provides real-time updates for **comments**, **crypto prices**, and **equity prices**. + + + Official RTDS TypeScript client (`real-time-data-client`). + + +## Endpoint + +``` +wss://ws-live-data.polymarket.com +``` + +Some user-specific streams may require `gamma_auth` with your wallet address. + +## Subscribing + +Send a JSON message to subscribe to data streams: + +```json theme={null} +{ + "action": "subscribe", + "subscriptions": [ + { + "topic": "topic_name", + "type": "message_type", + "filters": "optional_filter_string", + "gamma_auth": { + "address": "wallet_address" + } + } + ] +} +``` + +To unsubscribe, send the same structure with `"action": "unsubscribe"`. + +Subscriptions can be added, removed, and modified without disconnecting. Send `PING` messages every 5 seconds to maintain the connection. + +Only the subscription types documented below are supported. + +## Message Structure + +All messages follow this structure: + +```json theme={null} +{ + "topic": "string", + "type": "string", + "timestamp": "number", + "payload": "object" +} +``` + +| Field | Type | Description | +| ----------- | ------ | --------------------------------------------------------------------------- | +| `topic` | string | The subscription topic (e.g., `crypto_prices`, `equity_prices`, `comments`) | +| `type` | string | The message type/event (e.g., `update`, `reaction_created`) | +| `timestamp` | number | Unix timestamp in milliseconds when the message was sent | +| `payload` | object | Event-specific data object | + +## Crypto Prices + +Real-time cryptocurrency price data from two sources: **Binance** and **Chainlink**. No authentication required. + +### Binance Source + +Subscribe to all symbols: + +```json theme={null} +{ + "action": "subscribe", + "subscriptions": [ + { + "topic": "crypto_prices", + "type": "update" + } + ] +} +``` + +Subscribe to specific symbols with a comma-separated filter: + +```json theme={null} +{ + "action": "subscribe", + "subscriptions": [ + { + "topic": "crypto_prices", + "type": "update", + "filters": "solusdt,btcusdt,ethusdt" + } + ] +} +``` + +Symbols use lowercase concatenated format (e.g., `solusdt`, `btcusdt`). + +**Solana price update:** + +```json theme={null} +{ + "topic": "crypto_prices", + "type": "update", + "timestamp": 1753314064237, + "payload": { + "symbol": "solusdt", + "timestamp": 1753314064213, + "value": 189.55 + } +} +``` + +**Bitcoin price update:** + +```json theme={null} +{ + "topic": "crypto_prices", + "type": "update", + "timestamp": 1753314088421, + "payload": { + "symbol": "btcusdt", + "timestamp": 1753314088395, + "value": 67234.50 + } +} +``` + +### Chainlink Source + + + **Trading 15m Crypto Markets?** Get a sponsored Chainlink API key with onboarding support from Chainlink. Fill out [this form](https://pm-ds-request.streams.chain.link/). + + +Subscribe to all symbols: + +```json theme={null} +{ + "action": "subscribe", + "subscriptions": [ + { + "topic": "crypto_prices_chainlink", + "type": "*", + "filters": "" + } + ] +} +``` + +Subscribe to a specific symbol with a JSON filter: + +```json theme={null} +{ + "action": "subscribe", + "subscriptions": [ + { + "topic": "crypto_prices_chainlink", + "type": "*", + "filters": "{\"symbol\":\"eth/usd\"}" + } + ] +} +``` + +Symbols use slash-separated format (e.g., `eth/usd`, `btc/usd`). + +**Ethereum price update:** + +```json theme={null} +{ + "topic": "crypto_prices_chainlink", + "type": "update", + "timestamp": 1753314064237, + "payload": { + "symbol": "eth/usd", + "timestamp": 1753314064213, + "value": 3456.78 + } +} +``` + +**Bitcoin price update:** + +```json theme={null} +{ + "topic": "crypto_prices_chainlink", + "type": "update", + "timestamp": 1753314088421, + "payload": { + "symbol": "btc/usd", + "timestamp": 1753314088395, + "value": 67234.50 + } +} +``` + +### Price Payload Fields + +| Field | Type | Description | +| ----------- | ------ | -------------------------------------------------------------------------------------------------------------------------------------------------- | +| `symbol` | string | Trading pair symbol. **Binance**: lowercase concatenated (e.g., `solusdt`, `btcusdt`). **Chainlink**: slash-separated (e.g., `eth/usd`, `btc/usd`) | +| `timestamp` | number | When the price was recorded, in Unix milliseconds | +| `value` | number | Current price value in the quote currency | + +### Supported Symbols + +**Binance Source** — lowercase concatenated format: + +* `btcusdt` — Bitcoin to USDT +* `ethusdt` — Ethereum to USDT +* `solusdt` — Solana to USDT +* `xrpusdt` — XRP to USDT + +**Chainlink Source** — slash-separated format: + +* `btc/usd` — Bitcoin to USD +* `eth/usd` — Ethereum to USD +* `sol/usd` — Solana to USD +* `xrp/usd` — XRP to USD + +## Equity Prices + +Real-time price data for stocks, ETFs, forex pairs, precious metals, and commodities sourced from **Pyth Network**. No authentication required. + + + **Trading Equity Markets?** Get a Pyth Network data feed - first 30 days free, then \$99/month. [Subscribe here](https://buy.stripe.com/cNi8wPeiq76FgQrbsD4ZG09). + + +All asset classes stream through a single `equity_prices` topic. When you subscribe with a symbol filter, the server sends a historical snapshot (last 2 minutes of data), then continues streaming live updates. + +### Subscribe + +Subscribe to a specific symbol with a JSON filter: + +```json theme={null} +{ + "action": "subscribe", + "subscriptions": [ + { + "topic": "equity_prices", + "type": "update", + "filters": "{\"symbol\":\"AAPL\"}" + } + ] +} +``` + +Subscribe to multiple symbols across asset classes: + +```json theme={null} +{ + "action": "subscribe", + "subscriptions": [ + { "topic": "equity_prices", "type": "update", "filters": "{\"symbol\":\"AAPL\"}" }, + { "topic": "equity_prices", "type": "update", "filters": "{\"symbol\":\"EURUSD\"}" }, + { "topic": "equity_prices", "type": "update", "filters": "{\"symbol\":\"XAUUSD\"}" }, + { "topic": "equity_prices", "type": "update", "filters": "{\"symbol\":\"WTI\"}" } + ] +} +``` + +Use `type: "*"` to receive all message types (live updates and snapshots): + +```json theme={null} +{ + "action": "subscribe", + "subscriptions": [ + { + "topic": "equity_prices", + "type": "*", + "filters": "{\"symbol\":\"GOOGL\"}" + } + ] +} +``` + +Filter values are case-insensitive on subscribe, but the `symbol` field in payloads is always returned lowercase. + + + **Need the price-to-beat value?** Pass the market slug to the price-to-beat endpoint: + + `GET https://polymarket.com/api/equity/price-to-beat/{slug}` + + Example: `https://polymarket.com/api/equity/price-to-beat/wti-up-or-down-on-april-7-2026` + + +### Live Price Update + +**Apple stock update:** + +```json theme={null} +{ + "topic": "equity_prices", + "type": "update", + "timestamp": 1711382400000, + "payload": { + "symbol": "aapl", + "value": 198.45, + "full_accuracy_value": "198.4523", + "timestamp": 1711382400000, + "received_at": 1711382400005 + } +} +``` + +**Gold price update (market closed):** + +```json theme={null} +{ + "topic": "equity_prices", + "type": "update", + "timestamp": 1711400000000, + "payload": { + "symbol": "xauusd", + "value": 2175.30, + "full_accuracy_value": "2175.3012", + "timestamp": 1711399000000, + "received_at": 1711400000002, + "is_carried_forward": true + } +} +``` + +### Historical Snapshot + +On subscribe, the server delivers a backfill of the last 2 minutes of price data. Use the `type` field to distinguish: `"subscribe"` for the initial snapshot vs `"update"` for live ticks. + +```json theme={null} +{ + "topic": "equity_prices", + "type": "subscribe", + "timestamp": 1711382400000, + "payload": { + "symbol": "aapl", + "data": [ + { "timestamp": 1711382280000, "value": 198.30 }, + { "timestamp": 1711382281000, "value": 198.32 }, + { "timestamp": 1711382340000, "value": 198.41 } + ] + } +} +``` + +### Equity Price Payload Fields + +| Field | Type | Description | +| --------------------- | ------- | --------------------------------------------------------------------------------------------------------- | +| `symbol` | string | Lowercase symbol identifier (e.g., `aapl`, `eurusd`, `xauusd`) | +| `value` | number | Spot price as a float | +| `full_accuracy_value` | string | Full-precision price as a string | +| `timestamp` | number | Price measurement timestamp in Unix milliseconds | +| `received_at` | number | When the system received the price, in Unix milliseconds. Only present when non-zero. | +| `is_carried_forward` | boolean | `true` when the market session is closed and the value is the last known price. Only present when `true`. | + +### Supported Symbols + +**Stocks:** + +| Symbol | Name | +| ------- | -------------- | +| `AAPL` | Apple | +| `TSLA` | Tesla | +| `MSFT` | Microsoft | +| `GOOGL` | Alphabet | +| `AMZN` | Amazon | +| `META` | Meta Platforms | +| `NVDA` | NVIDIA | +| `NFLX` | Netflix | +| `PLTR` | Palantir | +| `OPEN` | Opendoor | +| `RKLB` | Rocket Lab | +| `ABNB` | Airbnb | +| `COIN` | Coinbase | +| `HOOD` | Robinhood | + +**ETFs:** + +| Symbol | Name | +| ------ | ------------------------------------ | +| `QQQ` | Invesco QQQ ETF | +| `SPY` | S\&P 500 ETF | +| `EWY` | iShares MSCI South Korea ETF | +| `VXX` | Barclays iPath Series B S\&P 500 VIX | + +**Forex:** + +| Symbol | Pair | +| -------- | ---------------------------- | +| `EURUSD` | Euro / US Dollar | +| `GBPUSD` | British Pound / US Dollar | +| `USDCAD` | US Dollar / Canadian Dollar | +| `USDJPY` | US Dollar / Japanese Yen | +| `USDKRW` | US Dollar / South Korean Won | + +**Precious Metals:** + +| Symbol | Name | +| -------- | ------ | +| `XAUUSD` | Gold | +| `XAGUSD` | Silver | + +**Commodities** (rolling front-month futures): + +| Symbol | Name | +| ------ | --------------- | +| `WTI` | Crude Oil (WTI) | +| `CC` | Cocoa | +| `NGD` | Natural Gas | + +### Market Hours + +When a market session is closed, the stream continues with the last known price and `is_carried_forward: true`. This lets you distinguish stale prices from live ticks. Update frequency is sub-second (up to 5 per second per feed) during market hours. + +## Comments + +Real-time comment events on the Polymarket platform, including new comments, replies, reactions, and removals. May require Gamma authentication for user-specific data. + +### Subscribe + +```json theme={null} +{ + "action": "subscribe", + "subscriptions": [ + { + "topic": "comments", + "type": "comment_created" + } + ] +} +``` + +### Message Types + +| Type | Description | +| ------------------ | ------------------------------------- | +| `comment_created` | A user creates a new comment or reply | +| `comment_removed` | A comment is removed or deleted | +| `reaction_created` | A user adds a reaction to a comment | +| `reaction_removed` | A reaction is removed from a comment | + +### comment\_created + +Emitted when a user posts a new comment or replies to an existing one. + +```json theme={null} +{ + "topic": "comments", + "type": "comment_created", + "timestamp": 1753454975808, + "payload": { + "body": "That's a good point about the definition.", + "createdAt": "2025-07-25T14:49:35.801298Z", + "id": "1763355", + "parentCommentID": "1763325", + "parentEntityID": 18396, + "parentEntityType": "Event", + "profile": { + "baseAddress": "0xce533188d53a16ed580fd5121dedf166d3482677", + "displayUsernamePublic": true, + "name": "salted.caramel", + "proxyWallet": "0x4ca749dcfa93c87e5ee23e2d21ff4422c7a4c1ee", + "pseudonym": "Adored-Disparity" + }, + "reactionCount": 0, + "replyAddress": "0x0bda5d16f76cd1d3485bcc7a44bc6fa7db004cdd", + "reportCount": 0, + "userAddress": "0xce533188d53a16ed580fd5121dedf166d3482677" + } +} +``` + +A reply to the above comment — note `parentCommentID` references the parent: + +```json theme={null} +{ + "topic": "comments", + "type": "comment_created", + "timestamp": 1753454985123, + "payload": { + "body": "I agree, the resolution criteria should be clearer.", + "createdAt": "2025-07-25T14:49:45.120000Z", + "id": "1763356", + "parentCommentID": "1763355", + "parentEntityID": 18396, + "parentEntityType": "Event", + "profile": { + "baseAddress": "0x1234567890abcdef1234567890abcdef12345678", + "displayUsernamePublic": true, + "name": "trader", + "proxyWallet": "0x9876543210fedcba9876543210fedcba98765432", + "pseudonym": "Bright-Analysis" + }, + "reactionCount": 0, + "replyAddress": "0x0bda5d16f76cd1d3485bcc7a44bc6fa7db004cdd", + "reportCount": 0, + "userAddress": "0x1234567890abcdef1234567890abcdef12345678" + } +} +``` + +### Comment Payload Fields + +| Field | Type | Description | +| ------------------ | ------ | ------------------------------------------------------------------------- | +| `body` | string | The text content of the comment | +| `createdAt` | string | ISO 8601 timestamp when the comment was created | +| `id` | string | Unique identifier for this comment | +| `parentCommentID` | string | ID of the parent comment if this is a reply (null for top-level comments) | +| `parentEntityID` | number | ID of the parent entity (event, market, etc.) | +| `parentEntityType` | string | Type of parent entity (`Event`, `Market`) | +| `profile` | object | Profile information of the comment author | +| `reactionCount` | number | Current number of reactions on this comment | +| `replyAddress` | string | Polygon address for replies (may differ from userAddress) | +| `reportCount` | number | Current number of reports on this comment | +| `userAddress` | string | Polygon address of the comment author | + +### Profile Object Fields + +| Field | Type | Description | +| ----------------------- | ------- | ------------------------------------------ | +| `baseAddress` | string | User profile address | +| `displayUsernamePublic` | boolean | Whether the username is displayed publicly | +| `name` | string | User's display name | +| `proxyWallet` | string | Proxy wallet address used for transactions | +| `pseudonym` | string | Generated pseudonym for the user | + +### Comment Hierarchy + +Comments support nested threading: + +* **Top-level comments**: `parentCommentID` is null or empty +* **Reply comments**: `parentCommentID` contains the ID of the parent comment +* All comments are associated with a `parentEntityID` and `parentEntityType` (`Event` or `Market`) + +## Troubleshooting + + + Send `PING` messages every 5 seconds to keep the connection alive. Connection errors will trigger automatic reconnection attempts. + + + + Verify your subscription message is valid JSON with the correct `action`, `topic`, and `type` fields. Invalid subscription messages may result in connection closure. + + + + If subscribing to user-specific streams, ensure your `gamma_auth` object includes a valid wallet `address`. Authentication failures will prevent subscription to protected topics. + diff --git a/PolymarketDocumentation-main/docs/developers/RTDS/RTDS-crypto-prices.md b/PolymarketDocumentation-main/docs/developers/RTDS/RTDS-crypto-prices.md new file mode 100644 index 00000000..0e274231 --- /dev/null +++ b/PolymarketDocumentation-main/docs/developers/RTDS/RTDS-crypto-prices.md @@ -0,0 +1,554 @@ +> ## Documentation Index +> Fetch the complete documentation index at: https://docs.polymarket.com/llms.txt +> Use this file to discover all available pages before exploring further. + +# Real-Time Data Socket + +> Stream comments, crypto prices, and equity prices via WebSocket + +The Polymarket Real-Time Data Socket (RTDS) is a WebSocket-based streaming service that provides real-time updates for **comments**, **crypto prices**, and **equity prices**. + + + Official RTDS TypeScript client (`real-time-data-client`). + + +## Endpoint + +``` +wss://ws-live-data.polymarket.com +``` + +Some user-specific streams may require `gamma_auth` with your wallet address. + +## Subscribing + +Send a JSON message to subscribe to data streams: + +```json theme={null} +{ + "action": "subscribe", + "subscriptions": [ + { + "topic": "topic_name", + "type": "message_type", + "filters": "optional_filter_string", + "gamma_auth": { + "address": "wallet_address" + } + } + ] +} +``` + +To unsubscribe, send the same structure with `"action": "unsubscribe"`. + +Subscriptions can be added, removed, and modified without disconnecting. Send `PING` messages every 5 seconds to maintain the connection. + +Only the subscription types documented below are supported. + +## Message Structure + +All messages follow this structure: + +```json theme={null} +{ + "topic": "string", + "type": "string", + "timestamp": "number", + "payload": "object" +} +``` + +| Field | Type | Description | +| ----------- | ------ | --------------------------------------------------------------------------- | +| `topic` | string | The subscription topic (e.g., `crypto_prices`, `equity_prices`, `comments`) | +| `type` | string | The message type/event (e.g., `update`, `reaction_created`) | +| `timestamp` | number | Unix timestamp in milliseconds when the message was sent | +| `payload` | object | Event-specific data object | + +## Crypto Prices + +Real-time cryptocurrency price data from two sources: **Binance** and **Chainlink**. No authentication required. + +### Binance Source + +Subscribe to all symbols: + +```json theme={null} +{ + "action": "subscribe", + "subscriptions": [ + { + "topic": "crypto_prices", + "type": "update" + } + ] +} +``` + +Subscribe to specific symbols with a comma-separated filter: + +```json theme={null} +{ + "action": "subscribe", + "subscriptions": [ + { + "topic": "crypto_prices", + "type": "update", + "filters": "solusdt,btcusdt,ethusdt" + } + ] +} +``` + +Symbols use lowercase concatenated format (e.g., `solusdt`, `btcusdt`). + +**Solana price update:** + +```json theme={null} +{ + "topic": "crypto_prices", + "type": "update", + "timestamp": 1753314064237, + "payload": { + "symbol": "solusdt", + "timestamp": 1753314064213, + "value": 189.55 + } +} +``` + +**Bitcoin price update:** + +```json theme={null} +{ + "topic": "crypto_prices", + "type": "update", + "timestamp": 1753314088421, + "payload": { + "symbol": "btcusdt", + "timestamp": 1753314088395, + "value": 67234.50 + } +} +``` + +### Chainlink Source + + + **Trading 15m Crypto Markets?** Get a sponsored Chainlink API key with onboarding support from Chainlink. Fill out [this form](https://pm-ds-request.streams.chain.link/). + + +Subscribe to all symbols: + +```json theme={null} +{ + "action": "subscribe", + "subscriptions": [ + { + "topic": "crypto_prices_chainlink", + "type": "*", + "filters": "" + } + ] +} +``` + +Subscribe to a specific symbol with a JSON filter: + +```json theme={null} +{ + "action": "subscribe", + "subscriptions": [ + { + "topic": "crypto_prices_chainlink", + "type": "*", + "filters": "{\"symbol\":\"eth/usd\"}" + } + ] +} +``` + +Symbols use slash-separated format (e.g., `eth/usd`, `btc/usd`). + +**Ethereum price update:** + +```json theme={null} +{ + "topic": "crypto_prices_chainlink", + "type": "update", + "timestamp": 1753314064237, + "payload": { + "symbol": "eth/usd", + "timestamp": 1753314064213, + "value": 3456.78 + } +} +``` + +**Bitcoin price update:** + +```json theme={null} +{ + "topic": "crypto_prices_chainlink", + "type": "update", + "timestamp": 1753314088421, + "payload": { + "symbol": "btc/usd", + "timestamp": 1753314088395, + "value": 67234.50 + } +} +``` + +### Price Payload Fields + +| Field | Type | Description | +| ----------- | ------ | -------------------------------------------------------------------------------------------------------------------------------------------------- | +| `symbol` | string | Trading pair symbol. **Binance**: lowercase concatenated (e.g., `solusdt`, `btcusdt`). **Chainlink**: slash-separated (e.g., `eth/usd`, `btc/usd`) | +| `timestamp` | number | When the price was recorded, in Unix milliseconds | +| `value` | number | Current price value in the quote currency | + +### Supported Symbols + +**Binance Source** — lowercase concatenated format: + +* `btcusdt` — Bitcoin to USDT +* `ethusdt` — Ethereum to USDT +* `solusdt` — Solana to USDT +* `xrpusdt` — XRP to USDT + +**Chainlink Source** — slash-separated format: + +* `btc/usd` — Bitcoin to USD +* `eth/usd` — Ethereum to USD +* `sol/usd` — Solana to USD +* `xrp/usd` — XRP to USD + +## Equity Prices + +Real-time price data for stocks, ETFs, forex pairs, precious metals, and commodities sourced from **Pyth Network**. No authentication required. + + + **Trading Equity Markets?** Get a Pyth Network data feed - first 30 days free, then \$99/month. [Subscribe here](https://buy.stripe.com/cNi8wPeiq76FgQrbsD4ZG09). + + +All asset classes stream through a single `equity_prices` topic. When you subscribe with a symbol filter, the server sends a historical snapshot (last 2 minutes of data), then continues streaming live updates. + +### Subscribe + +Subscribe to a specific symbol with a JSON filter: + +```json theme={null} +{ + "action": "subscribe", + "subscriptions": [ + { + "topic": "equity_prices", + "type": "update", + "filters": "{\"symbol\":\"AAPL\"}" + } + ] +} +``` + +Subscribe to multiple symbols across asset classes: + +```json theme={null} +{ + "action": "subscribe", + "subscriptions": [ + { "topic": "equity_prices", "type": "update", "filters": "{\"symbol\":\"AAPL\"}" }, + { "topic": "equity_prices", "type": "update", "filters": "{\"symbol\":\"EURUSD\"}" }, + { "topic": "equity_prices", "type": "update", "filters": "{\"symbol\":\"XAUUSD\"}" }, + { "topic": "equity_prices", "type": "update", "filters": "{\"symbol\":\"WTI\"}" } + ] +} +``` + +Use `type: "*"` to receive all message types (live updates and snapshots): + +```json theme={null} +{ + "action": "subscribe", + "subscriptions": [ + { + "topic": "equity_prices", + "type": "*", + "filters": "{\"symbol\":\"GOOGL\"}" + } + ] +} +``` + +Filter values are case-insensitive on subscribe, but the `symbol` field in payloads is always returned lowercase. + + + **Need the price-to-beat value?** Pass the market slug to the price-to-beat endpoint: + + `GET https://polymarket.com/api/equity/price-to-beat/{slug}` + + Example: `https://polymarket.com/api/equity/price-to-beat/wti-up-or-down-on-april-7-2026` + + +### Live Price Update + +**Apple stock update:** + +```json theme={null} +{ + "topic": "equity_prices", + "type": "update", + "timestamp": 1711382400000, + "payload": { + "symbol": "aapl", + "value": 198.45, + "full_accuracy_value": "198.4523", + "timestamp": 1711382400000, + "received_at": 1711382400005 + } +} +``` + +**Gold price update (market closed):** + +```json theme={null} +{ + "topic": "equity_prices", + "type": "update", + "timestamp": 1711400000000, + "payload": { + "symbol": "xauusd", + "value": 2175.30, + "full_accuracy_value": "2175.3012", + "timestamp": 1711399000000, + "received_at": 1711400000002, + "is_carried_forward": true + } +} +``` + +### Historical Snapshot + +On subscribe, the server delivers a backfill of the last 2 minutes of price data. Use the `type` field to distinguish: `"subscribe"` for the initial snapshot vs `"update"` for live ticks. + +```json theme={null} +{ + "topic": "equity_prices", + "type": "subscribe", + "timestamp": 1711382400000, + "payload": { + "symbol": "aapl", + "data": [ + { "timestamp": 1711382280000, "value": 198.30 }, + { "timestamp": 1711382281000, "value": 198.32 }, + { "timestamp": 1711382340000, "value": 198.41 } + ] + } +} +``` + +### Equity Price Payload Fields + +| Field | Type | Description | +| --------------------- | ------- | --------------------------------------------------------------------------------------------------------- | +| `symbol` | string | Lowercase symbol identifier (e.g., `aapl`, `eurusd`, `xauusd`) | +| `value` | number | Spot price as a float | +| `full_accuracy_value` | string | Full-precision price as a string | +| `timestamp` | number | Price measurement timestamp in Unix milliseconds | +| `received_at` | number | When the system received the price, in Unix milliseconds. Only present when non-zero. | +| `is_carried_forward` | boolean | `true` when the market session is closed and the value is the last known price. Only present when `true`. | + +### Supported Symbols + +**Stocks:** + +| Symbol | Name | +| ------- | -------------- | +| `AAPL` | Apple | +| `TSLA` | Tesla | +| `MSFT` | Microsoft | +| `GOOGL` | Alphabet | +| `AMZN` | Amazon | +| `META` | Meta Platforms | +| `NVDA` | NVIDIA | +| `NFLX` | Netflix | +| `PLTR` | Palantir | +| `OPEN` | Opendoor | +| `RKLB` | Rocket Lab | +| `ABNB` | Airbnb | +| `COIN` | Coinbase | +| `HOOD` | Robinhood | + +**ETFs:** + +| Symbol | Name | +| ------ | ------------------------------------ | +| `QQQ` | Invesco QQQ ETF | +| `SPY` | S\&P 500 ETF | +| `EWY` | iShares MSCI South Korea ETF | +| `VXX` | Barclays iPath Series B S\&P 500 VIX | + +**Forex:** + +| Symbol | Pair | +| -------- | ---------------------------- | +| `EURUSD` | Euro / US Dollar | +| `GBPUSD` | British Pound / US Dollar | +| `USDCAD` | US Dollar / Canadian Dollar | +| `USDJPY` | US Dollar / Japanese Yen | +| `USDKRW` | US Dollar / South Korean Won | + +**Precious Metals:** + +| Symbol | Name | +| -------- | ------ | +| `XAUUSD` | Gold | +| `XAGUSD` | Silver | + +**Commodities** (rolling front-month futures): + +| Symbol | Name | +| ------ | --------------- | +| `WTI` | Crude Oil (WTI) | +| `CC` | Cocoa | +| `NGD` | Natural Gas | + +### Market Hours + +When a market session is closed, the stream continues with the last known price and `is_carried_forward: true`. This lets you distinguish stale prices from live ticks. Update frequency is sub-second (up to 5 per second per feed) during market hours. + +## Comments + +Real-time comment events on the Polymarket platform, including new comments, replies, reactions, and removals. May require Gamma authentication for user-specific data. + +### Subscribe + +```json theme={null} +{ + "action": "subscribe", + "subscriptions": [ + { + "topic": "comments", + "type": "comment_created" + } + ] +} +``` + +### Message Types + +| Type | Description | +| ------------------ | ------------------------------------- | +| `comment_created` | A user creates a new comment or reply | +| `comment_removed` | A comment is removed or deleted | +| `reaction_created` | A user adds a reaction to a comment | +| `reaction_removed` | A reaction is removed from a comment | + +### comment\_created + +Emitted when a user posts a new comment or replies to an existing one. + +```json theme={null} +{ + "topic": "comments", + "type": "comment_created", + "timestamp": 1753454975808, + "payload": { + "body": "That's a good point about the definition.", + "createdAt": "2025-07-25T14:49:35.801298Z", + "id": "1763355", + "parentCommentID": "1763325", + "parentEntityID": 18396, + "parentEntityType": "Event", + "profile": { + "baseAddress": "0xce533188d53a16ed580fd5121dedf166d3482677", + "displayUsernamePublic": true, + "name": "salted.caramel", + "proxyWallet": "0x4ca749dcfa93c87e5ee23e2d21ff4422c7a4c1ee", + "pseudonym": "Adored-Disparity" + }, + "reactionCount": 0, + "replyAddress": "0x0bda5d16f76cd1d3485bcc7a44bc6fa7db004cdd", + "reportCount": 0, + "userAddress": "0xce533188d53a16ed580fd5121dedf166d3482677" + } +} +``` + +A reply to the above comment — note `parentCommentID` references the parent: + +```json theme={null} +{ + "topic": "comments", + "type": "comment_created", + "timestamp": 1753454985123, + "payload": { + "body": "I agree, the resolution criteria should be clearer.", + "createdAt": "2025-07-25T14:49:45.120000Z", + "id": "1763356", + "parentCommentID": "1763355", + "parentEntityID": 18396, + "parentEntityType": "Event", + "profile": { + "baseAddress": "0x1234567890abcdef1234567890abcdef12345678", + "displayUsernamePublic": true, + "name": "trader", + "proxyWallet": "0x9876543210fedcba9876543210fedcba98765432", + "pseudonym": "Bright-Analysis" + }, + "reactionCount": 0, + "replyAddress": "0x0bda5d16f76cd1d3485bcc7a44bc6fa7db004cdd", + "reportCount": 0, + "userAddress": "0x1234567890abcdef1234567890abcdef12345678" + } +} +``` + +### Comment Payload Fields + +| Field | Type | Description | +| ------------------ | ------ | ------------------------------------------------------------------------- | +| `body` | string | The text content of the comment | +| `createdAt` | string | ISO 8601 timestamp when the comment was created | +| `id` | string | Unique identifier for this comment | +| `parentCommentID` | string | ID of the parent comment if this is a reply (null for top-level comments) | +| `parentEntityID` | number | ID of the parent entity (event, market, etc.) | +| `parentEntityType` | string | Type of parent entity (`Event`, `Market`) | +| `profile` | object | Profile information of the comment author | +| `reactionCount` | number | Current number of reactions on this comment | +| `replyAddress` | string | Polygon address for replies (may differ from userAddress) | +| `reportCount` | number | Current number of reports on this comment | +| `userAddress` | string | Polygon address of the comment author | + +### Profile Object Fields + +| Field | Type | Description | +| ----------------------- | ------- | ------------------------------------------ | +| `baseAddress` | string | User profile address | +| `displayUsernamePublic` | boolean | Whether the username is displayed publicly | +| `name` | string | User's display name | +| `proxyWallet` | string | Proxy wallet address used for transactions | +| `pseudonym` | string | Generated pseudonym for the user | + +### Comment Hierarchy + +Comments support nested threading: + +* **Top-level comments**: `parentCommentID` is null or empty +* **Reply comments**: `parentCommentID` contains the ID of the parent comment +* All comments are associated with a `parentEntityID` and `parentEntityType` (`Event` or `Market`) + +## Troubleshooting + + + Send `PING` messages every 5 seconds to keep the connection alive. Connection errors will trigger automatic reconnection attempts. + + + + Verify your subscription message is valid JSON with the correct `action`, `topic`, and `type` fields. Invalid subscription messages may result in connection closure. + + + + If subscribing to user-specific streams, ensure your `gamma_auth` object includes a valid wallet `address`. Authentication failures will prevent subscription to protected topics. + diff --git a/PolymarketDocumentation-main/docs/developers/RTDS/RTDS-overview.md b/PolymarketDocumentation-main/docs/developers/RTDS/RTDS-overview.md new file mode 100644 index 00000000..0e274231 --- /dev/null +++ b/PolymarketDocumentation-main/docs/developers/RTDS/RTDS-overview.md @@ -0,0 +1,554 @@ +> ## Documentation Index +> Fetch the complete documentation index at: https://docs.polymarket.com/llms.txt +> Use this file to discover all available pages before exploring further. + +# Real-Time Data Socket + +> Stream comments, crypto prices, and equity prices via WebSocket + +The Polymarket Real-Time Data Socket (RTDS) is a WebSocket-based streaming service that provides real-time updates for **comments**, **crypto prices**, and **equity prices**. + + + Official RTDS TypeScript client (`real-time-data-client`). + + +## Endpoint + +``` +wss://ws-live-data.polymarket.com +``` + +Some user-specific streams may require `gamma_auth` with your wallet address. + +## Subscribing + +Send a JSON message to subscribe to data streams: + +```json theme={null} +{ + "action": "subscribe", + "subscriptions": [ + { + "topic": "topic_name", + "type": "message_type", + "filters": "optional_filter_string", + "gamma_auth": { + "address": "wallet_address" + } + } + ] +} +``` + +To unsubscribe, send the same structure with `"action": "unsubscribe"`. + +Subscriptions can be added, removed, and modified without disconnecting. Send `PING` messages every 5 seconds to maintain the connection. + +Only the subscription types documented below are supported. + +## Message Structure + +All messages follow this structure: + +```json theme={null} +{ + "topic": "string", + "type": "string", + "timestamp": "number", + "payload": "object" +} +``` + +| Field | Type | Description | +| ----------- | ------ | --------------------------------------------------------------------------- | +| `topic` | string | The subscription topic (e.g., `crypto_prices`, `equity_prices`, `comments`) | +| `type` | string | The message type/event (e.g., `update`, `reaction_created`) | +| `timestamp` | number | Unix timestamp in milliseconds when the message was sent | +| `payload` | object | Event-specific data object | + +## Crypto Prices + +Real-time cryptocurrency price data from two sources: **Binance** and **Chainlink**. No authentication required. + +### Binance Source + +Subscribe to all symbols: + +```json theme={null} +{ + "action": "subscribe", + "subscriptions": [ + { + "topic": "crypto_prices", + "type": "update" + } + ] +} +``` + +Subscribe to specific symbols with a comma-separated filter: + +```json theme={null} +{ + "action": "subscribe", + "subscriptions": [ + { + "topic": "crypto_prices", + "type": "update", + "filters": "solusdt,btcusdt,ethusdt" + } + ] +} +``` + +Symbols use lowercase concatenated format (e.g., `solusdt`, `btcusdt`). + +**Solana price update:** + +```json theme={null} +{ + "topic": "crypto_prices", + "type": "update", + "timestamp": 1753314064237, + "payload": { + "symbol": "solusdt", + "timestamp": 1753314064213, + "value": 189.55 + } +} +``` + +**Bitcoin price update:** + +```json theme={null} +{ + "topic": "crypto_prices", + "type": "update", + "timestamp": 1753314088421, + "payload": { + "symbol": "btcusdt", + "timestamp": 1753314088395, + "value": 67234.50 + } +} +``` + +### Chainlink Source + + + **Trading 15m Crypto Markets?** Get a sponsored Chainlink API key with onboarding support from Chainlink. Fill out [this form](https://pm-ds-request.streams.chain.link/). + + +Subscribe to all symbols: + +```json theme={null} +{ + "action": "subscribe", + "subscriptions": [ + { + "topic": "crypto_prices_chainlink", + "type": "*", + "filters": "" + } + ] +} +``` + +Subscribe to a specific symbol with a JSON filter: + +```json theme={null} +{ + "action": "subscribe", + "subscriptions": [ + { + "topic": "crypto_prices_chainlink", + "type": "*", + "filters": "{\"symbol\":\"eth/usd\"}" + } + ] +} +``` + +Symbols use slash-separated format (e.g., `eth/usd`, `btc/usd`). + +**Ethereum price update:** + +```json theme={null} +{ + "topic": "crypto_prices_chainlink", + "type": "update", + "timestamp": 1753314064237, + "payload": { + "symbol": "eth/usd", + "timestamp": 1753314064213, + "value": 3456.78 + } +} +``` + +**Bitcoin price update:** + +```json theme={null} +{ + "topic": "crypto_prices_chainlink", + "type": "update", + "timestamp": 1753314088421, + "payload": { + "symbol": "btc/usd", + "timestamp": 1753314088395, + "value": 67234.50 + } +} +``` + +### Price Payload Fields + +| Field | Type | Description | +| ----------- | ------ | -------------------------------------------------------------------------------------------------------------------------------------------------- | +| `symbol` | string | Trading pair symbol. **Binance**: lowercase concatenated (e.g., `solusdt`, `btcusdt`). **Chainlink**: slash-separated (e.g., `eth/usd`, `btc/usd`) | +| `timestamp` | number | When the price was recorded, in Unix milliseconds | +| `value` | number | Current price value in the quote currency | + +### Supported Symbols + +**Binance Source** — lowercase concatenated format: + +* `btcusdt` — Bitcoin to USDT +* `ethusdt` — Ethereum to USDT +* `solusdt` — Solana to USDT +* `xrpusdt` — XRP to USDT + +**Chainlink Source** — slash-separated format: + +* `btc/usd` — Bitcoin to USD +* `eth/usd` — Ethereum to USD +* `sol/usd` — Solana to USD +* `xrp/usd` — XRP to USD + +## Equity Prices + +Real-time price data for stocks, ETFs, forex pairs, precious metals, and commodities sourced from **Pyth Network**. No authentication required. + + + **Trading Equity Markets?** Get a Pyth Network data feed - first 30 days free, then \$99/month. [Subscribe here](https://buy.stripe.com/cNi8wPeiq76FgQrbsD4ZG09). + + +All asset classes stream through a single `equity_prices` topic. When you subscribe with a symbol filter, the server sends a historical snapshot (last 2 minutes of data), then continues streaming live updates. + +### Subscribe + +Subscribe to a specific symbol with a JSON filter: + +```json theme={null} +{ + "action": "subscribe", + "subscriptions": [ + { + "topic": "equity_prices", + "type": "update", + "filters": "{\"symbol\":\"AAPL\"}" + } + ] +} +``` + +Subscribe to multiple symbols across asset classes: + +```json theme={null} +{ + "action": "subscribe", + "subscriptions": [ + { "topic": "equity_prices", "type": "update", "filters": "{\"symbol\":\"AAPL\"}" }, + { "topic": "equity_prices", "type": "update", "filters": "{\"symbol\":\"EURUSD\"}" }, + { "topic": "equity_prices", "type": "update", "filters": "{\"symbol\":\"XAUUSD\"}" }, + { "topic": "equity_prices", "type": "update", "filters": "{\"symbol\":\"WTI\"}" } + ] +} +``` + +Use `type: "*"` to receive all message types (live updates and snapshots): + +```json theme={null} +{ + "action": "subscribe", + "subscriptions": [ + { + "topic": "equity_prices", + "type": "*", + "filters": "{\"symbol\":\"GOOGL\"}" + } + ] +} +``` + +Filter values are case-insensitive on subscribe, but the `symbol` field in payloads is always returned lowercase. + + + **Need the price-to-beat value?** Pass the market slug to the price-to-beat endpoint: + + `GET https://polymarket.com/api/equity/price-to-beat/{slug}` + + Example: `https://polymarket.com/api/equity/price-to-beat/wti-up-or-down-on-april-7-2026` + + +### Live Price Update + +**Apple stock update:** + +```json theme={null} +{ + "topic": "equity_prices", + "type": "update", + "timestamp": 1711382400000, + "payload": { + "symbol": "aapl", + "value": 198.45, + "full_accuracy_value": "198.4523", + "timestamp": 1711382400000, + "received_at": 1711382400005 + } +} +``` + +**Gold price update (market closed):** + +```json theme={null} +{ + "topic": "equity_prices", + "type": "update", + "timestamp": 1711400000000, + "payload": { + "symbol": "xauusd", + "value": 2175.30, + "full_accuracy_value": "2175.3012", + "timestamp": 1711399000000, + "received_at": 1711400000002, + "is_carried_forward": true + } +} +``` + +### Historical Snapshot + +On subscribe, the server delivers a backfill of the last 2 minutes of price data. Use the `type` field to distinguish: `"subscribe"` for the initial snapshot vs `"update"` for live ticks. + +```json theme={null} +{ + "topic": "equity_prices", + "type": "subscribe", + "timestamp": 1711382400000, + "payload": { + "symbol": "aapl", + "data": [ + { "timestamp": 1711382280000, "value": 198.30 }, + { "timestamp": 1711382281000, "value": 198.32 }, + { "timestamp": 1711382340000, "value": 198.41 } + ] + } +} +``` + +### Equity Price Payload Fields + +| Field | Type | Description | +| --------------------- | ------- | --------------------------------------------------------------------------------------------------------- | +| `symbol` | string | Lowercase symbol identifier (e.g., `aapl`, `eurusd`, `xauusd`) | +| `value` | number | Spot price as a float | +| `full_accuracy_value` | string | Full-precision price as a string | +| `timestamp` | number | Price measurement timestamp in Unix milliseconds | +| `received_at` | number | When the system received the price, in Unix milliseconds. Only present when non-zero. | +| `is_carried_forward` | boolean | `true` when the market session is closed and the value is the last known price. Only present when `true`. | + +### Supported Symbols + +**Stocks:** + +| Symbol | Name | +| ------- | -------------- | +| `AAPL` | Apple | +| `TSLA` | Tesla | +| `MSFT` | Microsoft | +| `GOOGL` | Alphabet | +| `AMZN` | Amazon | +| `META` | Meta Platforms | +| `NVDA` | NVIDIA | +| `NFLX` | Netflix | +| `PLTR` | Palantir | +| `OPEN` | Opendoor | +| `RKLB` | Rocket Lab | +| `ABNB` | Airbnb | +| `COIN` | Coinbase | +| `HOOD` | Robinhood | + +**ETFs:** + +| Symbol | Name | +| ------ | ------------------------------------ | +| `QQQ` | Invesco QQQ ETF | +| `SPY` | S\&P 500 ETF | +| `EWY` | iShares MSCI South Korea ETF | +| `VXX` | Barclays iPath Series B S\&P 500 VIX | + +**Forex:** + +| Symbol | Pair | +| -------- | ---------------------------- | +| `EURUSD` | Euro / US Dollar | +| `GBPUSD` | British Pound / US Dollar | +| `USDCAD` | US Dollar / Canadian Dollar | +| `USDJPY` | US Dollar / Japanese Yen | +| `USDKRW` | US Dollar / South Korean Won | + +**Precious Metals:** + +| Symbol | Name | +| -------- | ------ | +| `XAUUSD` | Gold | +| `XAGUSD` | Silver | + +**Commodities** (rolling front-month futures): + +| Symbol | Name | +| ------ | --------------- | +| `WTI` | Crude Oil (WTI) | +| `CC` | Cocoa | +| `NGD` | Natural Gas | + +### Market Hours + +When a market session is closed, the stream continues with the last known price and `is_carried_forward: true`. This lets you distinguish stale prices from live ticks. Update frequency is sub-second (up to 5 per second per feed) during market hours. + +## Comments + +Real-time comment events on the Polymarket platform, including new comments, replies, reactions, and removals. May require Gamma authentication for user-specific data. + +### Subscribe + +```json theme={null} +{ + "action": "subscribe", + "subscriptions": [ + { + "topic": "comments", + "type": "comment_created" + } + ] +} +``` + +### Message Types + +| Type | Description | +| ------------------ | ------------------------------------- | +| `comment_created` | A user creates a new comment or reply | +| `comment_removed` | A comment is removed or deleted | +| `reaction_created` | A user adds a reaction to a comment | +| `reaction_removed` | A reaction is removed from a comment | + +### comment\_created + +Emitted when a user posts a new comment or replies to an existing one. + +```json theme={null} +{ + "topic": "comments", + "type": "comment_created", + "timestamp": 1753454975808, + "payload": { + "body": "That's a good point about the definition.", + "createdAt": "2025-07-25T14:49:35.801298Z", + "id": "1763355", + "parentCommentID": "1763325", + "parentEntityID": 18396, + "parentEntityType": "Event", + "profile": { + "baseAddress": "0xce533188d53a16ed580fd5121dedf166d3482677", + "displayUsernamePublic": true, + "name": "salted.caramel", + "proxyWallet": "0x4ca749dcfa93c87e5ee23e2d21ff4422c7a4c1ee", + "pseudonym": "Adored-Disparity" + }, + "reactionCount": 0, + "replyAddress": "0x0bda5d16f76cd1d3485bcc7a44bc6fa7db004cdd", + "reportCount": 0, + "userAddress": "0xce533188d53a16ed580fd5121dedf166d3482677" + } +} +``` + +A reply to the above comment — note `parentCommentID` references the parent: + +```json theme={null} +{ + "topic": "comments", + "type": "comment_created", + "timestamp": 1753454985123, + "payload": { + "body": "I agree, the resolution criteria should be clearer.", + "createdAt": "2025-07-25T14:49:45.120000Z", + "id": "1763356", + "parentCommentID": "1763355", + "parentEntityID": 18396, + "parentEntityType": "Event", + "profile": { + "baseAddress": "0x1234567890abcdef1234567890abcdef12345678", + "displayUsernamePublic": true, + "name": "trader", + "proxyWallet": "0x9876543210fedcba9876543210fedcba98765432", + "pseudonym": "Bright-Analysis" + }, + "reactionCount": 0, + "replyAddress": "0x0bda5d16f76cd1d3485bcc7a44bc6fa7db004cdd", + "reportCount": 0, + "userAddress": "0x1234567890abcdef1234567890abcdef12345678" + } +} +``` + +### Comment Payload Fields + +| Field | Type | Description | +| ------------------ | ------ | ------------------------------------------------------------------------- | +| `body` | string | The text content of the comment | +| `createdAt` | string | ISO 8601 timestamp when the comment was created | +| `id` | string | Unique identifier for this comment | +| `parentCommentID` | string | ID of the parent comment if this is a reply (null for top-level comments) | +| `parentEntityID` | number | ID of the parent entity (event, market, etc.) | +| `parentEntityType` | string | Type of parent entity (`Event`, `Market`) | +| `profile` | object | Profile information of the comment author | +| `reactionCount` | number | Current number of reactions on this comment | +| `replyAddress` | string | Polygon address for replies (may differ from userAddress) | +| `reportCount` | number | Current number of reports on this comment | +| `userAddress` | string | Polygon address of the comment author | + +### Profile Object Fields + +| Field | Type | Description | +| ----------------------- | ------- | ------------------------------------------ | +| `baseAddress` | string | User profile address | +| `displayUsernamePublic` | boolean | Whether the username is displayed publicly | +| `name` | string | User's display name | +| `proxyWallet` | string | Proxy wallet address used for transactions | +| `pseudonym` | string | Generated pseudonym for the user | + +### Comment Hierarchy + +Comments support nested threading: + +* **Top-level comments**: `parentCommentID` is null or empty +* **Reply comments**: `parentCommentID` contains the ID of the parent comment +* All comments are associated with a `parentEntityID` and `parentEntityType` (`Event` or `Market`) + +## Troubleshooting + + + Send `PING` messages every 5 seconds to keep the connection alive. Connection errors will trigger automatic reconnection attempts. + + + + Verify your subscription message is valid JSON with the correct `action`, `topic`, and `type` fields. Invalid subscription messages may result in connection closure. + + + + If subscribing to user-specific streams, ensure your `gamma_auth` object includes a valid wallet `address`. Authentication failures will prevent subscription to protected topics. + diff --git a/PolymarketDocumentation-main/docs/developers/builders/blockchain-data-resources.md b/PolymarketDocumentation-main/docs/developers/builders/blockchain-data-resources.md new file mode 100644 index 00000000..533a410c --- /dev/null +++ b/PolymarketDocumentation-main/docs/developers/builders/blockchain-data-resources.md @@ -0,0 +1,70 @@ +> ## Documentation Index +> Fetch the complete documentation index at: https://docs.polymarket.com/llms.txt +> Use this file to discover all available pages before exploring further. + +# Data Resources + +> Access Polymarket on-chain activity for data & analytics + +Polymarket data that lands on the blockchain, such as trades, balances, positions, and redeems, is available through various on-chain analytics platforms and blockchain data providers. Polymarket also provides its own APIs and WebSockets. See the [API Endpoints reference](/quickstart/reference/endpoints) for more information. + +The purpose of this page is to serve as a public good for Polymarket builders, researches, and analysts alike. + +*** + +## Data + +### Goldsky + +[Goldsky](https://docs.goldsky.com/chains/polymarket) provides real-time streaming pipelines for Polymarket on-chain activity (i.e. trades, balances, positions, etc...) into your own database/data warehouse. + +Goldsky also partnered with [ClickHouse](https://clickhouse.com) to create [CryptoHouse](https://crypto.clickhouse.com), where you can query Polymarket on-chain data using SQL. + +### Dune + +[Dune](https://dune.com) is a blockchain analytics platform that has Polymarket on-chain activity (i.e. trades, balances, positions, etc...). Query Polymarket data using SQL, create custom dashboards, and more. + +Here are a few simple queries to get started: + +| Query | Description | Link | +| ------------- | --------------------------------------------- | --------------------------------------------------- | +| Volume | Notional Volume and Maker & Taker USDC Volume | [View Dune Query](https://dune.com/queries/6545441) | +| TVL | USDC locked in Polymarket smart contracts | [View Dune Query](https://dune.com/queries/6588784) | +| Open Interest | Estimated market open interest, and over time | [View Dune Query](https://dune.com/queries/6555478) | + +### Allium + +[Allium](https://docs.allium.so/historical-data/predictions) is a blockchain analytics platform that has Polymarket on-chain activity (i.e. trades, balances, positions, etc...). Query Polymarket data using SQL, create custom dashboards, and more. + +\-- + +## Dashboards + +Third-party blockchain analytics platforms that aggregate and visualize Polymarket data: + + + + + + + + + + + + + + + + + +### Community Dashboards + +Community-created Dune dashboards of Polymarket on-chain analytics: + +| Dashboard | Created By | Link | +| ------------------------------------------------- | ----------------------------------------------- | ---------------------------------------------------------------------------- | +| Polymarket Overview | [@datadashboards](https://x.com/datadashboards) | [View Dashboard](https://dune.com/datadashboards/polymarket-overview) | +| Polymarket Volume, OI, Markets, Addresses and TVL | [@hildobby](https://x.com/hildobby) | [View Dashboard](https://dune.com/hildobby/polymarket) | +| Polymarket Historical Accuracy | [@alexmccullaaa](https://x.com/alexmccullaaa) | [View Dashboard](https://dune.com/alexmccullough/how-accurate-is-polymarket) | +| Polymarket Builders Dashboard | [@defioasis](https://x.com/defioasis) | [View Dashboard](https://dune.com/gateresearch/pmbuilders) | diff --git a/PolymarketDocumentation-main/docs/developers/builders/builder-intro.md b/PolymarketDocumentation-main/docs/developers/builders/builder-intro.md new file mode 100644 index 00000000..9234e8d8 --- /dev/null +++ b/PolymarketDocumentation-main/docs/developers/builders/builder-intro.md @@ -0,0 +1,229 @@ +> ## Documentation Index +> Fetch the complete documentation index at: https://docs.polymarket.com/llms.txt +> Use this file to discover all available pages before exploring further. + +# Builder Program + +> Build applications that route orders through Polymarket + +A **builder** is a person, group, or organization that routes orders from users to Polymarket. If you've created a platform that allows users to trade on Polymarket through your system, this program is for you. + +## Program Benefits + + + + All onchain operations are gas-free through our relayer + + + + Get credit for orders and compete for grants on the Builder Leaderboard + + + +### What You Get + +| Benefit | Description | +| ------------------- | ------------------------------------------------------------------------------- | +| **Relayer Access** | Gas-free wallet deployment, approvals, order execution and CTF operations | +| **Volume Tracking** | All orders attributed to your builder profile | +| **Leaderboard** | Public visibility on [builders.polymarket.com](https://builders.polymarket.com) | +| **Support** | Telegram channel and engineering support (Verified+) | + + + EOA wallets do not have relayer access. Users trading directly from an EOA pay + their own gas fees. + + +## How It Works + + + + User places an order through your application. + + + + Your app adds your `builderCode` to the order struct. + + + + Order is submitted to Polymarket's CLOB — the builder code is serialized + onchain as part of the signed order. + + + + Polymarket matches the order and covers gas fees for onchain operations. + + + + Volume is credited to your builder account for every matched trade where + your code is attached. + + + +## Getting Started + + + + Go to + [polymarket.com/settings?tab=builder](https://polymarket.com/settings?tab=builder) + and copy your builder code. + + + + Pass `builderCode` on every order you submit — see [Order + Attribution](/trading/orders/attribution). + + + + Use the Relayer Client for gas-free wallet deployment and onchain + operations. + + + + Monitor your volume on the [Builder + Leaderboard](https://builders.polymarket.com). + + + + + Bridging user funds in or out via the Bridge API? Also pass your code via the + optional `X-Builder-Code` header on [`/deposit`](/trading/bridge/deposit) and + [`/withdraw`](/trading/bridge/withdraw) so bridge traffic is attributed to your + integration. + + +## SDKs and Libraries + + + + Place orders with builder attribution + + + + Place orders with builder attribution + + + + Gasless onchain transactions + + + + Gasless onchain transactions + + + + Place orders with builder attribution + + + +## Examples + +These open-source demo applications show how to integrate Polymarket's CLOB Client and Builder Relayer Client for gasless trading with builder order attribution. + + + + Multiple wallet providers + + + + Deposit wallet support for new API users + + + + Orders, positions, CTF ops + + + +### Deposit Wallet Integrations + +New API users should use deposit wallets. Use the Builder Relayer Client to +deploy deposit wallets and execute signed wallet batches, then place CLOB +orders with `POLY_1271`. + +See the [Deposit Wallet Guide](/trading/deposit-wallets) for TypeScript, +Python, Rust, and direct API integration details. + +### Existing Safe Wallet Examples + +Existing Safe integrations can continue using Gnosis Safe wallets: + + + + MetaMask, Phantom, Rabby, and other browser wallets + + + + Privy embedded wallets + + + + Magic Link email/social authentication + + + + Turnkey embedded wallets + + + +### Existing Proxy Wallet Examples + +For existing Magic Link users from Polymarket.com: + + + + Auto-deploying proxy wallets for Polymarket.com Magic users + + + +### What Each Demo Covers + + + +
    +
  • User sign-in via wallet provider
  • +
  • User API credential derivation (L2 auth)
  • +
  • Builder config with remote signing
  • +
  • Signature types for Deposit Wallet, Safe, and Proxy wallets
  • +
+
+ + +
    +
  • Deposit wallet deployment via Relayer
  • +
  • Batch token approvals (pUSD + outcome tokens)
  • +
  • CTF operations (split, merge, redeem)
  • +
  • Transaction monitoring
  • +
+
+ + +
    +
  • CLOB client initialization
  • +
  • Order placement with builder attribution
  • +
  • Position and order management
  • +
  • Market discovery via Gamma API
  • +
+
+
+ +*** + +## Next Steps + + + + Create and manage your Builder API credentials. + + + + Learn about rate limits and how to upgrade. + + + + Configure your client to credit trades to your account. + + + + Set up gasless transactions for your users. + + diff --git a/PolymarketDocumentation-main/docs/developers/builders/builder-profile.md b/PolymarketDocumentation-main/docs/developers/builders/builder-profile.md new file mode 100644 index 00000000..9234e8d8 --- /dev/null +++ b/PolymarketDocumentation-main/docs/developers/builders/builder-profile.md @@ -0,0 +1,229 @@ +> ## Documentation Index +> Fetch the complete documentation index at: https://docs.polymarket.com/llms.txt +> Use this file to discover all available pages before exploring further. + +# Builder Program + +> Build applications that route orders through Polymarket + +A **builder** is a person, group, or organization that routes orders from users to Polymarket. If you've created a platform that allows users to trade on Polymarket through your system, this program is for you. + +## Program Benefits + + + + All onchain operations are gas-free through our relayer + + + + Get credit for orders and compete for grants on the Builder Leaderboard + + + +### What You Get + +| Benefit | Description | +| ------------------- | ------------------------------------------------------------------------------- | +| **Relayer Access** | Gas-free wallet deployment, approvals, order execution and CTF operations | +| **Volume Tracking** | All orders attributed to your builder profile | +| **Leaderboard** | Public visibility on [builders.polymarket.com](https://builders.polymarket.com) | +| **Support** | Telegram channel and engineering support (Verified+) | + + + EOA wallets do not have relayer access. Users trading directly from an EOA pay + their own gas fees. + + +## How It Works + + + + User places an order through your application. + + + + Your app adds your `builderCode` to the order struct. + + + + Order is submitted to Polymarket's CLOB — the builder code is serialized + onchain as part of the signed order. + + + + Polymarket matches the order and covers gas fees for onchain operations. + + + + Volume is credited to your builder account for every matched trade where + your code is attached. + + + +## Getting Started + + + + Go to + [polymarket.com/settings?tab=builder](https://polymarket.com/settings?tab=builder) + and copy your builder code. + + + + Pass `builderCode` on every order you submit — see [Order + Attribution](/trading/orders/attribution). + + + + Use the Relayer Client for gas-free wallet deployment and onchain + operations. + + + + Monitor your volume on the [Builder + Leaderboard](https://builders.polymarket.com). + + + + + Bridging user funds in or out via the Bridge API? Also pass your code via the + optional `X-Builder-Code` header on [`/deposit`](/trading/bridge/deposit) and + [`/withdraw`](/trading/bridge/withdraw) so bridge traffic is attributed to your + integration. + + +## SDKs and Libraries + + + + Place orders with builder attribution + + + + Place orders with builder attribution + + + + Gasless onchain transactions + + + + Gasless onchain transactions + + + + Place orders with builder attribution + + + +## Examples + +These open-source demo applications show how to integrate Polymarket's CLOB Client and Builder Relayer Client for gasless trading with builder order attribution. + + + + Multiple wallet providers + + + + Deposit wallet support for new API users + + + + Orders, positions, CTF ops + + + +### Deposit Wallet Integrations + +New API users should use deposit wallets. Use the Builder Relayer Client to +deploy deposit wallets and execute signed wallet batches, then place CLOB +orders with `POLY_1271`. + +See the [Deposit Wallet Guide](/trading/deposit-wallets) for TypeScript, +Python, Rust, and direct API integration details. + +### Existing Safe Wallet Examples + +Existing Safe integrations can continue using Gnosis Safe wallets: + + + + MetaMask, Phantom, Rabby, and other browser wallets + + + + Privy embedded wallets + + + + Magic Link email/social authentication + + + + Turnkey embedded wallets + + + +### Existing Proxy Wallet Examples + +For existing Magic Link users from Polymarket.com: + + + + Auto-deploying proxy wallets for Polymarket.com Magic users + + + +### What Each Demo Covers + + + +
    +
  • User sign-in via wallet provider
  • +
  • User API credential derivation (L2 auth)
  • +
  • Builder config with remote signing
  • +
  • Signature types for Deposit Wallet, Safe, and Proxy wallets
  • +
+
+ + +
    +
  • Deposit wallet deployment via Relayer
  • +
  • Batch token approvals (pUSD + outcome tokens)
  • +
  • CTF operations (split, merge, redeem)
  • +
  • Transaction monitoring
  • +
+
+ + +
    +
  • CLOB client initialization
  • +
  • Order placement with builder attribution
  • +
  • Position and order management
  • +
  • Market discovery via Gamma API
  • +
+
+
+ +*** + +## Next Steps + + + + Create and manage your Builder API credentials. + + + + Learn about rate limits and how to upgrade. + + + + Configure your client to credit trades to your account. + + + + Set up gasless transactions for your users. + + diff --git a/PolymarketDocumentation-main/docs/developers/builders/builder-tiers.md b/PolymarketDocumentation-main/docs/developers/builders/builder-tiers.md new file mode 100644 index 00000000..64a7086c --- /dev/null +++ b/PolymarketDocumentation-main/docs/developers/builders/builder-tiers.md @@ -0,0 +1,170 @@ +> ## Documentation Index +> Fetch the complete documentation index at: https://docs.polymarket.com/llms.txt +> Use this file to discover all available pages before exploring further. + +# Tiers + +> Rate limits, rewards, and how to upgrade + +The Builder Program uses a tiered system to manage rate limits while rewarding high-performing integrations. Higher tiers unlock increased limits, weekly rewards, and priority support. + +## Feature Definitions + +| Feature | Description | +| --------------------------- | ------------------------------------------------------------------------------------------ | +| **Daily Relayer Txn Limit** | Maximum Relayer transactions per day for deposit wallet, Safe, and Proxy wallet operations | +| **API Rate Limits** | Rate limits for non-relayer endpoints (CLOB, Gamma, etc.) | +| **Gasless Trading** | Gas fees subsidized for supported smart-wallet operations | +| **Order Attribution** | Orders tracked and attributed to your Builder profile | +| **Builder Fees** | Builders who route orders can charge fees and monetize on flow | +| **Leaderboard Visibility** | Visibility on the [Builder Leaderboard](https://builders.polymarket.com/) | +| **Telegram Channel** | Private Builders channel for announcements and support | +| **Engineering Support** | Direct access to engineering team | +| **Marketing Support** | Promotion via official Polymarket social accounts | +| **Priority Access** | Early access to new features and products | + +*** + +## Tier Comparison + +| Feature | Unverified | Verified | Partner | +| --------------------------- | :--------: | :--------: | :-------: | +| **Daily Relayer Txn Limit** | 100/day | 10,000/day | Unlimited | +| **API Rate Limits** | Standard | Standard | Highest | +| **Gasless Trading\*** | Yes | Yes | Yes | +| **Order Attribution** | Yes | Yes | Yes | +| **Builder Fees** | Yes | Yes | Yes | +| **Leaderboard Visibility** | — | Yes | Yes | +| **Telegram Channel** | — | Yes | Yes | +| **Engineering Support** | — | Standard | Elevated | +| **Marketing Support** | — | Standard | Elevated | +| **Priority Access** | — | — | Yes | + +*** + +## Unverified + + + The default tier for all new builders. Start immediately with no approval + required. + + +**How to get started:** + +1. Go to [polymarket.com/settings?tab=builder](https://polymarket.com/settings?tab=builder) +2. Create a builder profile +3. Click **"+ Create New"** to generate API keys +4. Attach your [builder code](/trading/orders/attribution) to CLOB orders for attribution; use a Relayer API key for gasless wallet operations + +**What's included:** + +* Gasless trading through deposit wallets for new API users and existing Safe/Proxy wallets +* Gas subsidized on all Relayer transactions up to the daily limit +* Access to all client libraries and documentation + +*** + +## Verified + + + For builders who need higher throughput. Requires manual approval. + + +**How to upgrade:** + +Contact us at [builder@polymarket.com](mailto:builder@polymarket.com) with: + +* Your Builder API Key +* Use case description +* Expected volume +* Other relevant information (links, docs, decks, etc.) + +**Unlocks over Unverified:** + +* 100x daily Relayer transaction limit +* Monetize with Builder fees +* Leaderboard visibility at [builders.polymarket.com](https://builders.polymarket.com) +* Private Telegram channel for announcements and support +* Weekly USDC rewards based on volume (subject to approval) +* Grants (subject to approval) + +*** + +## Partner + + + Enterprise tier for high-volume integrations and strategic partners. + + +**Unlocks over Verified:** + +* Unlimited Relayer transactions +* Highest API rate limits +* Elevated engineering support +* Elevated and coordinated marketing support +* Priority access to new features and products + +*** + +## How to Upgrade + + + + Start with the Unverified tier and build your integration. + + + + Route orders through Polymarket and demonstrate consistent usage. + + + + Email [builder@polymarket.com](mailto:builder@polymarket.com) with your + builder key and use case. + + + + The Polymarket team reviews applications and responds within a few business + days. + + + +## Contact + +Ready to upgrade or have questions? + + + Email us with your Builder API Key and use case details. + + +## FAQ + + + + Verification is displayed in your [Builder Profile](https://polymarket.com/settings?tab=builder) settings. + + + + Relayer requests beyond your daily limit will be rate-limited and return an + error. Consider upgrading to Verified or Partner tier if you're hitting + limits. + + + + If you're not routing orders for other users (wallets), you can get unlimited + daily Relay transactions by obtaining a [Relayer API key](https://polymarket.com/settings?tab=api-keys). + + + +*** + +## Next Steps + + + + Create your Builder API credentials. + + + + Configure your client to credit trades to your account. + + diff --git a/PolymarketDocumentation-main/docs/developers/builders/examples.md b/PolymarketDocumentation-main/docs/developers/builders/examples.md new file mode 100644 index 00000000..9234e8d8 --- /dev/null +++ b/PolymarketDocumentation-main/docs/developers/builders/examples.md @@ -0,0 +1,229 @@ +> ## Documentation Index +> Fetch the complete documentation index at: https://docs.polymarket.com/llms.txt +> Use this file to discover all available pages before exploring further. + +# Builder Program + +> Build applications that route orders through Polymarket + +A **builder** is a person, group, or organization that routes orders from users to Polymarket. If you've created a platform that allows users to trade on Polymarket through your system, this program is for you. + +## Program Benefits + + + + All onchain operations are gas-free through our relayer + + + + Get credit for orders and compete for grants on the Builder Leaderboard + + + +### What You Get + +| Benefit | Description | +| ------------------- | ------------------------------------------------------------------------------- | +| **Relayer Access** | Gas-free wallet deployment, approvals, order execution and CTF operations | +| **Volume Tracking** | All orders attributed to your builder profile | +| **Leaderboard** | Public visibility on [builders.polymarket.com](https://builders.polymarket.com) | +| **Support** | Telegram channel and engineering support (Verified+) | + + + EOA wallets do not have relayer access. Users trading directly from an EOA pay + their own gas fees. + + +## How It Works + + + + User places an order through your application. + + + + Your app adds your `builderCode` to the order struct. + + + + Order is submitted to Polymarket's CLOB — the builder code is serialized + onchain as part of the signed order. + + + + Polymarket matches the order and covers gas fees for onchain operations. + + + + Volume is credited to your builder account for every matched trade where + your code is attached. + + + +## Getting Started + + + + Go to + [polymarket.com/settings?tab=builder](https://polymarket.com/settings?tab=builder) + and copy your builder code. + + + + Pass `builderCode` on every order you submit — see [Order + Attribution](/trading/orders/attribution). + + + + Use the Relayer Client for gas-free wallet deployment and onchain + operations. + + + + Monitor your volume on the [Builder + Leaderboard](https://builders.polymarket.com). + + + + + Bridging user funds in or out via the Bridge API? Also pass your code via the + optional `X-Builder-Code` header on [`/deposit`](/trading/bridge/deposit) and + [`/withdraw`](/trading/bridge/withdraw) so bridge traffic is attributed to your + integration. + + +## SDKs and Libraries + + + + Place orders with builder attribution + + + + Place orders with builder attribution + + + + Gasless onchain transactions + + + + Gasless onchain transactions + + + + Place orders with builder attribution + + + +## Examples + +These open-source demo applications show how to integrate Polymarket's CLOB Client and Builder Relayer Client for gasless trading with builder order attribution. + + + + Multiple wallet providers + + + + Deposit wallet support for new API users + + + + Orders, positions, CTF ops + + + +### Deposit Wallet Integrations + +New API users should use deposit wallets. Use the Builder Relayer Client to +deploy deposit wallets and execute signed wallet batches, then place CLOB +orders with `POLY_1271`. + +See the [Deposit Wallet Guide](/trading/deposit-wallets) for TypeScript, +Python, Rust, and direct API integration details. + +### Existing Safe Wallet Examples + +Existing Safe integrations can continue using Gnosis Safe wallets: + + + + MetaMask, Phantom, Rabby, and other browser wallets + + + + Privy embedded wallets + + + + Magic Link email/social authentication + + + + Turnkey embedded wallets + + + +### Existing Proxy Wallet Examples + +For existing Magic Link users from Polymarket.com: + + + + Auto-deploying proxy wallets for Polymarket.com Magic users + + + +### What Each Demo Covers + + + +
    +
  • User sign-in via wallet provider
  • +
  • User API credential derivation (L2 auth)
  • +
  • Builder config with remote signing
  • +
  • Signature types for Deposit Wallet, Safe, and Proxy wallets
  • +
+
+ + +
    +
  • Deposit wallet deployment via Relayer
  • +
  • Batch token approvals (pUSD + outcome tokens)
  • +
  • CTF operations (split, merge, redeem)
  • +
  • Transaction monitoring
  • +
+
+ + +
    +
  • CLOB client initialization
  • +
  • Order placement with builder attribution
  • +
  • Position and order management
  • +
  • Market discovery via Gamma API
  • +
+
+
+ +*** + +## Next Steps + + + + Create and manage your Builder API credentials. + + + + Learn about rate limits and how to upgrade. + + + + Configure your client to credit trades to your account. + + + + Set up gasless transactions for your users. + + diff --git a/PolymarketDocumentation-main/docs/developers/builders/order-attribution.md b/PolymarketDocumentation-main/docs/developers/builders/order-attribution.md new file mode 100644 index 00000000..cf91199b --- /dev/null +++ b/PolymarketDocumentation-main/docs/developers/builders/order-attribution.md @@ -0,0 +1,150 @@ +> ## Documentation Index +> Fetch the complete documentation index at: https://docs.polymarket.com/llms.txt +> Use this file to discover all available pages before exploring further. + +# Order Attribution + +> Attribute orders to your builder code for volume credit and fee rewards + +Order attribution credits trades to your builder account by attaching your **builder code** to every order. This enables: + +* Volume tracking on the [Builder Leaderboard](https://builders.polymarket.com/) +* Fee rewards through the [Builder Program](/builders/overview) +* Performance monitoring via the Data API + +*** + +## Builder Code + +Your **builder code** is a `bytes32` identifier tied to your builder profile. Find it at [polymarket.com/settings?tab=builder](https://polymarket.com/settings?tab=builder). + +That's the only credential you need for attribution — no HMAC signing, no separate API key, no special headers. + + + Builder codes are public identifiers — they appear onchain in the `builder` + field of every order you attribute. Only you control which orders include your + code, so keep it scoped to apps you own. + + +*** + +## Attaching the Builder Code + +Pass `builderCode` in the order struct on every order you submit. The SDK serializes it into the onchain order's `builder` field, and the protocol attributes every matched trade to your profile. + + + ```typescript TypeScript theme={null} + import { ClobClient, Side, OrderType } from "@polymarket/clob-client-v2"; + + const client = new ClobClient({ + host: "https://clob.polymarket.com", + chain: 137, + signer, + creds: apiCreds, + signatureType: 3, + funderAddress: depositWalletAddress, + }); + + const response = await client.createAndPostOrder( + { + tokenID: "0x...", + price: 0.55, + size: 100, + side: Side.BUY, + builderCode: "0xabc123...", // your builder code from polymarket.com/settings?tab=builder + }, + { tickSize: "0.01", negRisk: false }, + OrderType.GTC, + ); + ``` + + ```python Python theme={null} + from py_clob_client_v2 import ClobClient + from py_clob_client_v2 import OrderArgs, OrderType, PartialCreateOrderOptions + from py_clob_client_v2.order_builder.constants import BUY + + client = ClobClient( + host="https://clob.polymarket.com", + chain_id=137, + key=private_key, + creds=api_creds, + signature_type=3, + funder=deposit_wallet_address, + ) + + response = client.create_and_post_order( + OrderArgs( + token_id="0x...", + price=0.55, + size=100, + side=BUY, + builder_code="0xabc123...", # your builder code from polymarket.com/settings?tab=builder + ), + options=PartialCreateOrderOptions(tick_size="0.01", neg_risk=False), + order_type=OrderType.GTC, + ) + ``` + + +Every order placed with `builderCode` attached is credited to your builder profile — no additional configuration needed. + +*** + +## Verifying Attribution + +Query trades attributed to your builder code: + + + ```typescript TypeScript theme={null} + const trades = await client.getBuilderTrades(); + + // Filtered by market + const marketTrades = await client.getBuilderTrades({ + market: "0xbd31dc8a...", + }); + ``` + + ```python Python theme={null} + trades = client.get_builder_trades() + + market_trades = client.get_builder_trades( + market="0xbd31dc8a..." + ) + ``` + + +Each `BuilderTrade` includes: `id`, `market`, `assetId`, `side`, `size`, `price`, `status`, `outcome`, `owner`, `maker`, `builder`, `transactionHash`, `matchTime`, `fee`, and `feeUsdc`. + +*** + +## Troubleshooting + + + +
    +
  • Confirm your `builderCode` is correctly attached to every order
  • +
  • Check that orders are being matched, not just placed
  • +
  • Allow up to 24 hours for volume to appear on the leaderboard
  • +
+
+ + + Verify the code matches what's shown on [your Builder + Profile](https://polymarket.com/settings?tab=builder). Builder codes are + `bytes32` hex values starting with `0x`. + +
+ +*** + +## Next Steps + + + + Learn about the Builder Program tiers and rewards + + + + Build, sign, and submit orders + + diff --git a/PolymarketDocumentation-main/docs/developers/builders/relayer-client.md b/PolymarketDocumentation-main/docs/developers/builders/relayer-client.md new file mode 100644 index 00000000..f9767156 --- /dev/null +++ b/PolymarketDocumentation-main/docs/developers/builders/relayer-client.md @@ -0,0 +1,432 @@ +> ## Documentation Index +> Fetch the complete documentation index at: https://docs.polymarket.com/llms.txt +> Use this file to discover all available pages before exploring further. + +# Gasless Transactions + +> Execute onchain operations without paying gas fees + +Polymarket's **Relayer Client** enables gasless transactions for your users. Instead of requiring users to hold POL for gas, Polymarket's infrastructure pays all transaction fees. This creates a seamless experience where users only need pUSD to trade. + +## How It Works + +The relayer acts as a transaction sponsor: + +1. Your app creates a transaction +2. The user signs it with their private key +3. Your app sends it to Polymarket's relayer +4. The relayer submits it onchain and pays the gas fee +5. The transaction executes from the user's wallet + +## What Is Covered + +Polymarket pays gas for all operations routed through the relayer: + +| Operation | Description | +| --------------------- | ------------------------------------------------- | +| **Wallet deployment** | Deploy deposit wallets for new API users | +| **Token approvals** | Approve contracts to spend pUSD or outcome tokens | +| **CTF operations** | Split, merge, and redeem positions | +| **Transfers** | Move tokens between addresses | + +## Authentication + +The relayer uses **Relayer API Keys**. You can create one from [Settings > API Keys](https://polymarket.com/settings?tab=api-keys) on the Polymarket website. + + + **Already have a builder signing key?** Your existing HMAC-based builder API + key keeps working with the Relayer — no need to rotate or reissue. Order + attribution is now associated with the native `builderCode` field in CLOB V2. + See [Migrating to CLOB V2](/v2-migration#builder-program) for context. + + +Include these headers with your requests: + +| Header | Description | +| ------------------------- | ----------------------------- | +| `RELAYER_API_KEY` | Your Relayer API key | +| `RELAYER_API_KEY_ADDRESS` | The address that owns the key | + + + If you want to use the Relayer API Key directly without the SDK, see the + [Relayer API Reference](/api-reference/relayer). + + +## Prerequisites + +Before using the relayer, you need: + +| Requirement | Source | +| ---------------------------- | ------------------------------------------------------------------- | +| Relayer API Key | [Settings > API Keys](https://polymarket.com/settings?tab=api-keys) | +| User's private key or signer | Your wallet integration | +| pUSD balance | For trading (not for gas) | + +## Installation + + + ```bash npm theme={null} + npm install @polymarket/builder-relayer-client + ``` + + ```bash pip theme={null} + pip install py-builder-relayer-client + ``` + + +## Client Setup + +Initialize the relayer client with your Relayer API Key: + + + ```typescript TypeScript theme={null} + import { createWalletClient, http, Hex } from "viem"; + import { privateKeyToAccount } from "viem/accounts"; + import { polygon } from "viem/chains"; + import { RelayClient } from "@polymarket/builder-relayer-client"; + + const account = privateKeyToAccount(process.env.PRIVATE_KEY as Hex); + const wallet = createWalletClient({ + account, + chain: polygon, + transport: http(process.env.RPC_URL), + }); + + const client = new RelayClient({ + host: "https://relayer-v2.polymarket.com/", + chain: 137, + signer: wallet, + relayerApiKey: process.env.RELAYER_API_KEY!, + relayerApiKeyAddress: process.env.RELAYER_API_KEY_ADDRESS!, + }); + ``` + + ```python Python theme={null} + import os + from py_builder_relayer_client.client import RelayClient + + client = RelayClient( + host="https://relayer-v2.polymarket.com", + chain=137, + signer=os.getenv("PRIVATE_KEY"), + relayer_api_key=os.environ["RELAYER_API_KEY"], + relayer_api_key_address=os.environ["RELAYER_API_KEY_ADDRESS"], + ) + ``` + + + + Never expose your Relayer API Key in client-side code. Use environment + variables or a secrets manager. + + +## Wallet Types + +Use deposit wallets for new API users. Existing Safe and Proxy users can keep +using their current wallet type and signature flow. + +| Type | Deployment | Best For | +| ------------------ | ---------------------------------------- | ----------------------------------- | +| **Deposit Wallet** | Call `deployDepositWallet()` | New API users | +| **Safe** | Call `deploy()` before first transaction | Existing Safe integrations | +| **Proxy** | Auto-deploys on first transaction | Existing Polymarket.com proxy users | + + + For the new deposit wallet flow, including `WALLET-CREATE`, signed `WALLET` + batches, and `POLY_1271` CLOB orders, see the [Deposit Wallet + Guide](/trading/deposit-wallets). + + + + ```typescript Safe Wallet (TypeScript) theme={null} + import { RelayClient, RelayerTxType } from "@polymarket/builder-relayer-client"; + + const client = new RelayClient({ + host: "https://relayer-v2.polymarket.com/", + chain: 137, + signer: wallet, + relayerApiKey: process.env.RELAYER_API_KEY!, + relayerApiKeyAddress: process.env.RELAYER_API_KEY_ADDRESS!, + txType: RelayerTxType.SAFE, + }); + + // Deploy before first transaction + const response = await client.deploy(); + const result = await response.wait(); + console.log("Safe Address:", result?.proxyAddress); + ``` + + ```python Safe Wallet (Python) theme={null} + from py_builder_relayer_client.client import RelayClient + + # client initialized with relayer credentials (see Client Setup above) + + # Deploy before first transaction + response = client.deploy() + result = response.wait() + print("Safe Address:", result.get("proxyAddress")) + ``` + + ```typescript Proxy Wallet (TypeScript) theme={null} + import { RelayClient, RelayerTxType } from "@polymarket/builder-relayer-client"; + + const client = new RelayClient({ + host: "https://relayer-v2.polymarket.com/", + chain: 137, + signer: wallet, + relayerApiKey: process.env.RELAYER_API_KEY!, + relayerApiKeyAddress: process.env.RELAYER_API_KEY_ADDRESS!, + txType: RelayerTxType.PROXY, + }); + + // No deploy needed - auto-deploys on first transaction + ``` + + ```python Proxy Wallet (Python) theme={null} + from py_builder_relayer_client.client import RelayClient + + # client initialized with relayer credentials (see Client Setup above) + # No deploy needed - auto-deploys on first transaction + ``` + + +## Executing Transactions + +Use the `execute` method to send transactions through the relayer: + +```typescript theme={null} +interface Transaction { + to: string; // Target contract address + data: string; // Encoded function call + value: string; // POL to send (usually "0") +} + +const response = await client.execute(transactions, "Description"); +const result = await response.wait(); +``` + +### Token Approval + +Approve contracts to spend tokens: + + + ```typescript TypeScript theme={null} + import { encodeFunctionData, maxUint256 } from "viem"; + + const pUSD = "0xC011a7E12a19f7B1f670d46F03B03f3342E82DFB"; + const CTF = "0x4D97DCd97eC945f40cF65F87097ACe5EA0476045"; + + const approveTx = { + to: pUSD, + data: encodeFunctionData({ + abi: [ + { + name: "approve", + type: "function", + inputs: [ + { name: "spender", type: "address" }, + { name: "amount", type: "uint256" }, + ], + outputs: [{ type: "bool" }], + }, + ], + functionName: "approve", + args: [CTF, maxUint256], + }), + value: "0", + }; + + const response = await client.execute([approveTx], "Approve pUSD for CTF"); + await response.wait(); + ``` + + ```python Python theme={null} + from web3 import Web3 + + pUSD = "0xC011a7E12a19f7B1f670d46F03B03f3342E82DFB" + CTF = "0x4D97DCd97eC945f40cF65F87097ACe5EA0476045" + MAX_UINT256 = 2**256 - 1 + + approve_tx = { + "to": pUSD, + "data": Web3().eth.contract( + address=pUSD, + abi=[{ + "name": "approve", + "type": "function", + "inputs": [ + {"name": "spender", "type": "address"}, + {"name": "amount", "type": "uint256"} + ], + "outputs": [{"type": "bool"}] + }] + ).encode_abi(abi_element_identifier="approve", args=[CTF, MAX_UINT256]), + "value": "0" + } + + response = client.execute([approve_tx], "Approve pUSD for CTF") + response.wait() + ``` + + +### Redeem Positions + +Exchange winning tokens for pUSD after market resolution: + + + ```typescript TypeScript theme={null} + import { encodeFunctionData } from "viem"; + + const redeemTx = { + to: CTF_ADDRESS, + data: encodeFunctionData({ + abi: [ + { + name: "redeemPositions", + type: "function", + inputs: [ + { name: "collateralToken", type: "address" }, + { name: "parentCollectionId", type: "bytes32" }, + { name: "conditionId", type: "bytes32" }, + { name: "indexSets", type: "uint256[]" }, + ], + outputs: [], + }, + ], + functionName: "redeemPositions", + args: [collateralToken, parentCollectionId, conditionId, indexSets], + }), + value: "0", + }; + + const response = await client.execute([redeemTx], "Redeem positions"); + await response.wait(); + ``` + + ```python Python theme={null} + CTF = "0x4D97DCd97eC945f40cF65F87097ACe5EA0476045" + + redeem_tx = { + "to": CTF, + "data": Web3().eth.contract( + address=CTF, + abi=[{ + "name": "redeemPositions", + "type": "function", + "inputs": [ + {"name": "collateralToken", "type": "address"}, + {"name": "parentCollectionId", "type": "bytes32"}, + {"name": "conditionId", "type": "bytes32"}, + {"name": "indexSets", "type": "uint256[]"} + ], + "outputs": [] + }] + ).encode_abi( + abi_element_identifier="redeemPositions", + args=[collateral_token, parent_collection_id, condition_id, index_sets] + ), + "value": "0" + } + + response = client.execute([redeem_tx], "Redeem positions") + response.wait() + ``` + + +### Batch Transactions + +Execute multiple operations atomically in a single call: + + + ```typescript TypeScript theme={null} + const approveTx = { + to: pUSD, + data: encodeFunctionData({ + abi: erc20Abi, + functionName: "approve", + args: [CTF, maxUint256], + }), + value: "0", + }; + + const transferTx = { + to: pUSD, + data: encodeFunctionData({ + abi: erc20Abi, + functionName: "transfer", + args: [recipientAddress, parseUnits("50", 6)], + }), + value: "0", + }; + + // Both execute atomically + const response = await client.execute( + [approveTx, transferTx], + "Approve and transfer", + ); + await response.wait(); + ``` + + ```python Python theme={null} + approve_tx = { + "to": pUSD, + "data": contract.encode_abi( + abi_element_identifier="approve", + args=[CTF, MAX_UINT256] + ), + "value": "0" + } + + transfer_tx = { + "to": pUSD, + "data": contract.encode_abi( + abi_element_identifier="transfer", + args=[recipient_address, 50 * 10**6] + ), + "value": "0" + } + + # Both execute atomically + response = client.execute([approve_tx, transfer_tx], "Approve and transfer") + response.wait() + ``` + + + + Batching reduces latency and ensures all transactions succeed or fail + together. + + +## Transaction States + +Track transaction progress through these states: + +| State | Terminal | Description | +| ----------------- | -------- | ------------------------------- | +| `STATE_NEW` | No | Transaction received by relayer | +| `STATE_EXECUTED` | No | Submitted onchain | +| `STATE_MINED` | No | Included in a block | +| `STATE_CONFIRMED` | Yes | Finalized successfully | +| `STATE_FAILED` | Yes | Failed permanently | +| `STATE_INVALID` | Yes | Rejected as invalid | + +## Contract Addresses + +See [Contracts](/resources/contracts) for all Polymarket smart contract addresses on Polygon. + +## Resources + +* [Builder Relayer Client (TypeScript)](https://github.com/Polymarket/builder-relayer-client) +* [Builder Relayer Client (Python)](https://github.com/Polymarket/py-builder-relayer-client) + +## Next Steps + + + + Learn about capital-efficient trading for multi-outcome events. + + + + Understand token operations like split, merge, and redeem. + + diff --git a/PolymarketDocumentation-main/docs/developers/gamma-markets-api/fetch-markets-guide.md b/PolymarketDocumentation-main/docs/developers/gamma-markets-api/fetch-markets-guide.md new file mode 100644 index 00000000..92c50f3c --- /dev/null +++ b/PolymarketDocumentation-main/docs/developers/gamma-markets-api/fetch-markets-guide.md @@ -0,0 +1,156 @@ +> ## Documentation Index +> Fetch the complete documentation index at: https://docs.polymarket.com/llms.txt +> Use this file to discover all available pages before exploring further. + +# Fetching Markets + +> Three strategies for discovering and querying markets + + + Both the events and markets endpoints are paginated. See + [pagination](#pagination) for details. + + +There are three main strategies for retrieving market data, each optimized for different use cases: + +1. **By Slug** — Best for fetching specific individual markets or events +2. **By Tags** — Ideal for filtering markets by category or sport +3. **Via Events Endpoint** — Most efficient for retrieving all active markets + +*** + +## Fetch by Slug + +**Use case:** When you need to retrieve a specific market or event that you already know about. + +Individual markets and events are best fetched using their unique slug identifier. The slug can be found directly in the Polymarket frontend URL. + +### How to Extract the Slug + +From any Polymarket URL, the slug is the path segment after `/event/`: + +``` +https://polymarket.com/event/fed-decision-in-october + ↑ + Slug: fed-decision-in-october +``` + +### Examples + +```bash theme={null} +# Fetch an event by slug (query parameter) +curl "https://gamma-api.polymarket.com/events?slug=fed-decision-in-october" + +# Or use the path endpoint +curl "https://gamma-api.polymarket.com/events/slug/fed-decision-in-october" +``` + +```bash theme={null} +# Fetch a market by slug (query parameter) +curl "https://gamma-api.polymarket.com/markets?slug=fed-decision-in-october" + +# Or use the path endpoint +curl "https://gamma-api.polymarket.com/markets/slug/fed-decision-in-october" +``` + +*** + +## Fetch by Tags + +**Use case:** When you want to filter markets by category, sport, or topic. + +Tags provide a way to categorize and filter markets. You can discover available tags and then use them to filter your requests. + +### Discover Available Tags + +**General tags:** `GET /tags` (Gamma API) + +**Sports tags and metadata:** `GET /sports` (Gamma API) + +The `/sports` endpoint returns metadata for sports including tag IDs, images, resolution sources, and series information. + +### Filter by Tag + +Once you have tag IDs, use the `tag_id` parameter in both events and markets endpoints: + +```bash theme={null} +# Fetch events for a specific tag +curl "https://gamma-api.polymarket.com/events?tag_id=100381&limit=10&active=true&closed=false" +``` + +### Additional Tag Filtering + +You can also: + +* Use `related_tags=true` to include related tag markets +* Exclude specific tags with `exclude_tag_id` + +```bash theme={null} +# Include related tags +curl "https://gamma-api.polymarket.com/events?tag_id=100381&related_tags=true&active=true&closed=false" +``` + +*** + +## Fetch All Active Markets + +**Use case:** When you need to retrieve all available active markets, typically for broader analysis or market discovery. + +The most efficient approach is to use the events endpoint with `active=true&closed=false`, as events contain their associated markets. + +```bash theme={null} +curl "https://gamma-api.polymarket.com/events?active=true&closed=false&limit=100" +``` + +### Key Parameters + +| Parameter | Description | +| ----------- | ---------------------------------------------------------------------------------------------------------------- | +| `order` | Field to order by (`volume_24hr`, `volume`, `liquidity`, `start_date`, `end_date`, `competitive`, `closed_time`) | +| `ascending` | Sort direction (`true` for ascending, `false` for descending). Default: `false` | +| `active` | Filter by active status (`true` for live tradable events) | +| `closed` | Filter by closed status. Default: `false` | +| `limit` | Results per page | +| `offset` | Number of results to skip for pagination | + +```bash theme={null} +# Get the highest volume active events +curl "https://gamma-api.polymarket.com/events?active=true&closed=false&order=volume_24hr&ascending=false&limit=100" +``` + +*** + +## Pagination + +All list endpoints return paginated responses with `limit` and `offset` parameters: + +```bash theme={null} +# Page 1: First 50 results +curl "https://gamma-api.polymarket.com/events?active=true&closed=false&limit=50&offset=0" + +# Page 2: Next 50 results +curl "https://gamma-api.polymarket.com/events?active=true&closed=false&limit=50&offset=50" + +# Page 3: Next 50 results +curl "https://gamma-api.polymarket.com/events?active=true&closed=false&limit=50&offset=100" +``` + +*** + +## Best Practices + +1. **For individual markets:** Use the slug method for direct lookups +2. **For category browsing:** Use tag filtering to reduce API calls +3. **For complete market discovery:** Use the events endpoint with pagination +4. **Always include `active=true`** when fetching live markets. The `closed` parameter now defaults to `false`, so closed markets are excluded automatically — pass `closed=true` only if you need historical data +5. **Use the events endpoint** and work backwards — events contain their associated markets, reducing the number of API calls needed + +*** + +## Next Steps + + + + Full endpoint documentation with parameters and response schemas. + + diff --git a/PolymarketDocumentation-main/docs/developers/gamma-markets-api/gamma-structure.md b/PolymarketDocumentation-main/docs/developers/gamma-markets-api/gamma-structure.md new file mode 100644 index 00000000..424fc25a --- /dev/null +++ b/PolymarketDocumentation-main/docs/developers/gamma-markets-api/gamma-structure.md @@ -0,0 +1,108 @@ +> ## Documentation Index +> Fetch the complete documentation index at: https://docs.polymarket.com/llms.txt +> Use this file to discover all available pages before exploring further. + +# Markets & Events + +> Understanding the fundamental building blocks of Polymarket + +Every prediction on Polymarket is structured around two core concepts: **markets** and **events**. Understanding how they relate is essential for building on the platform. + + + + + + + +## Markets + +A **market** is the fundamental tradable unit on Polymarket. Each market represents a single binary question with Yes/No outcomes. + + + + + + + +Every market has: + +| Identifier | Description | +| ---------------- | ------------------------------------------------------------------------ | +| **Condition ID** | Unique identifier for the market's condition in the CTF contracts | +| **Question ID** | Hash of the market question used for resolution | +| **Token IDs** | ERC1155 token IDs used for trading on the CLOB — one for Yes, one for No | + + + Markets can only be traded via the CLOB if `enableOrderBook` is `true`. Some + markets may exist onchain but not be available for order book trading. + + +### Market Example + +A simple market might be: + +> **"Will Bitcoin reach \$150,000 by December 2026?"** + +This creates two outcome tokens: + +* **Yes token** - Redeemable for `$1` if Bitcoin reaches `$150k` +* **No token** - Redeemable for `$1` if Bitcoin doesn't reach `$150k` + +## Events + +An **event** is a container that groups one or more related markets together. Events provide organizational structure and enable multi-outcome predictions. + +### Single-Market Events + +When an event contains just one market, it creates a simple market pair. The event and market are essentially equivalent. + +``` +Event: Will Bitcoin reach $100,000 by December 2024? +└── Market: Will Bitcoin reach $100,000 by December 2024? (Yes/No) +``` + +### Multi-Market Events + +When an event contains two or more markets, it creates a grouped market pair. This enables mutually exclusive multi-outcome predictions. + +``` +Event: Who will win the 2024 Presidential Election? +├── Market: Donald Trump? (Yes/No) +├── Market: Joe Biden? (Yes/No) +├── Market: Kamala Harris? (Yes/No) +└── Market: Other? (Yes/No) +``` + +## Identifying Markets + +Every market and event has a unique **slug** that appears in the Polymarket URL: + +``` +https://polymarket.com/event/fed-decision-in-october + └── slug: fed-decision-in-october +``` + +You can use slugs to fetch specific markets or events from the API: + +```bash theme={null} +# Fetch event by slug +curl "https://gamma-api.polymarket.com/events?slug=fed-decision-in-october" +``` + +## Sports Markets + +Specifically for sports markets, outstanding limit orders are **automatically cancelled** once the game begins, clearing the order book at the official start time. However, game start times can shift — if a game starts earlier than scheduled, orders may not be cleared in time. Always monitor your orders closely around game start times. + +*** + +## Next Steps + + + + Learn how prices are determined and how the order book works. + + + + Start querying markets and events from the API. + + diff --git a/PolymarketDocumentation-main/docs/developers/gamma-markets-api/overview.md b/PolymarketDocumentation-main/docs/developers/gamma-markets-api/overview.md new file mode 100644 index 00000000..d2c61fe0 --- /dev/null +++ b/PolymarketDocumentation-main/docs/developers/gamma-markets-api/overview.md @@ -0,0 +1,111 @@ +> ## Documentation Index +> Fetch the complete documentation index at: https://docs.polymarket.com/llms.txt +> Use this file to discover all available pages before exploring further. + +# Overview + +> Fetch market data with no authentication required + +All market data is available through public REST endpoints. No API key, no authentication, no wallet required. + +```bash theme={null} +curl "https://gamma-api.polymarket.com/events?limit=5" +``` + +*** + +## Data Model + +Polymarket structures data using two organizational models. The most fundamental element is always markets—events simply provide additional organization. + + + + A top-level object representing a question (e.g., "Who will win the 2024 + Presidential Election?"). Contains one or more markets. + + + + A specific tradable binary outcome within an event. Maps to a pair of CLOB + token IDs, a market address, a question ID, and a condition ID. + + + +### Single-Market Events vs Multi-Market Events + +| Type | Example | +| ------------------- | ---------------------------------------------------------------------------------------------- | +| Single-market event | "Will Bitcoin reach \$100k?" → 1 market (Yes/No) | +| Multi-market event | "Where will Barron Trump attend College?" → Markets for Georgetown, NYU, UPenn, Harvard, Other | + +### Outcomes and Prices + +Each market has `outcomes` and `outcomePrices` arrays that map 1:1. Prices represent implied probabilities: + +```json theme={null} +{ + "outcomes": "[\"Yes\", \"No\"]", + "outcomePrices": "[\"0.20\", \"0.80\"]" +} +// Index 0: "Yes" → 0.20 (20% probability) +// Index 1: "No" → 0.80 (80% probability) +``` + +Markets can be traded via the CLOB if `enableOrderBook` is `true`. + +*** + +## Available Data + +Endpoints are split across three APIs. See the [API Reference](/api-reference/introduction) for full endpoint documentation with parameters and response schemas. + +### Gamma API - Events Markets and Discovery + +| Endpoint | Description | +| -------------------- | ------------------------------------------- | +| `GET /events` | List events with filtering and pagination | +| `GET /events/{id}` | Get a single event by ID | +| `GET /markets` | List markets with filtering and pagination | +| `GET /markets/{id}` | Get a single market by ID | +| `GET /public-search` | Search across events, markets, and profiles | +| `GET /tags` | Ranked tags/categories | +| `GET /series` | Series (grouped events) | +| `GET /sports` | Sports metadata | +| `GET /teams` | Teams | + +### CLOB API - Prices and Orderbooks + +| Endpoint | Description | +| --------------------- | --------------------------------- | +| `GET /price` | Price for a single token | +| `GET /prices` | Prices for multiple tokens | +| `GET /book` | Order book for a token | +| `POST /books` | Order books for multiple tokens | +| `GET /prices-history` | Historical price data for a token | +| `GET /midpoint` | Midpoint price for a token | +| `GET /spread` | Spread for a token | + +### Data API - Positions Trades and Analytics + +| Endpoint | Description | +| -------------------------------------- | ---------------------------- | +| `GET /positions?user={address}` | Current positions for a user | +| `GET /closed-positions?user={address}` | Closed positions for a user | +| `GET /activity?user={address}` | Onchain activity for a user | +| `GET /value?user={address}` | Total position value | +| `GET /oi` | Open interest for a market | +| `GET /holders` | Top holders of a market | +| `GET /trades` | Trade history | + +*** + +## Next Steps + + + + Three strategies for discovering and querying markets. + + + + Full endpoint documentation with parameters and response schemas. + + diff --git a/PolymarketDocumentation-main/docs/developers/market-makers/data-feeds.md b/PolymarketDocumentation-main/docs/developers/market-makers/data-feeds.md new file mode 100644 index 00000000..92c50f3c --- /dev/null +++ b/PolymarketDocumentation-main/docs/developers/market-makers/data-feeds.md @@ -0,0 +1,156 @@ +> ## Documentation Index +> Fetch the complete documentation index at: https://docs.polymarket.com/llms.txt +> Use this file to discover all available pages before exploring further. + +# Fetching Markets + +> Three strategies for discovering and querying markets + + + Both the events and markets endpoints are paginated. See + [pagination](#pagination) for details. + + +There are three main strategies for retrieving market data, each optimized for different use cases: + +1. **By Slug** — Best for fetching specific individual markets or events +2. **By Tags** — Ideal for filtering markets by category or sport +3. **Via Events Endpoint** — Most efficient for retrieving all active markets + +*** + +## Fetch by Slug + +**Use case:** When you need to retrieve a specific market or event that you already know about. + +Individual markets and events are best fetched using their unique slug identifier. The slug can be found directly in the Polymarket frontend URL. + +### How to Extract the Slug + +From any Polymarket URL, the slug is the path segment after `/event/`: + +``` +https://polymarket.com/event/fed-decision-in-october + ↑ + Slug: fed-decision-in-october +``` + +### Examples + +```bash theme={null} +# Fetch an event by slug (query parameter) +curl "https://gamma-api.polymarket.com/events?slug=fed-decision-in-october" + +# Or use the path endpoint +curl "https://gamma-api.polymarket.com/events/slug/fed-decision-in-october" +``` + +```bash theme={null} +# Fetch a market by slug (query parameter) +curl "https://gamma-api.polymarket.com/markets?slug=fed-decision-in-october" + +# Or use the path endpoint +curl "https://gamma-api.polymarket.com/markets/slug/fed-decision-in-october" +``` + +*** + +## Fetch by Tags + +**Use case:** When you want to filter markets by category, sport, or topic. + +Tags provide a way to categorize and filter markets. You can discover available tags and then use them to filter your requests. + +### Discover Available Tags + +**General tags:** `GET /tags` (Gamma API) + +**Sports tags and metadata:** `GET /sports` (Gamma API) + +The `/sports` endpoint returns metadata for sports including tag IDs, images, resolution sources, and series information. + +### Filter by Tag + +Once you have tag IDs, use the `tag_id` parameter in both events and markets endpoints: + +```bash theme={null} +# Fetch events for a specific tag +curl "https://gamma-api.polymarket.com/events?tag_id=100381&limit=10&active=true&closed=false" +``` + +### Additional Tag Filtering + +You can also: + +* Use `related_tags=true` to include related tag markets +* Exclude specific tags with `exclude_tag_id` + +```bash theme={null} +# Include related tags +curl "https://gamma-api.polymarket.com/events?tag_id=100381&related_tags=true&active=true&closed=false" +``` + +*** + +## Fetch All Active Markets + +**Use case:** When you need to retrieve all available active markets, typically for broader analysis or market discovery. + +The most efficient approach is to use the events endpoint with `active=true&closed=false`, as events contain their associated markets. + +```bash theme={null} +curl "https://gamma-api.polymarket.com/events?active=true&closed=false&limit=100" +``` + +### Key Parameters + +| Parameter | Description | +| ----------- | ---------------------------------------------------------------------------------------------------------------- | +| `order` | Field to order by (`volume_24hr`, `volume`, `liquidity`, `start_date`, `end_date`, `competitive`, `closed_time`) | +| `ascending` | Sort direction (`true` for ascending, `false` for descending). Default: `false` | +| `active` | Filter by active status (`true` for live tradable events) | +| `closed` | Filter by closed status. Default: `false` | +| `limit` | Results per page | +| `offset` | Number of results to skip for pagination | + +```bash theme={null} +# Get the highest volume active events +curl "https://gamma-api.polymarket.com/events?active=true&closed=false&order=volume_24hr&ascending=false&limit=100" +``` + +*** + +## Pagination + +All list endpoints return paginated responses with `limit` and `offset` parameters: + +```bash theme={null} +# Page 1: First 50 results +curl "https://gamma-api.polymarket.com/events?active=true&closed=false&limit=50&offset=0" + +# Page 2: Next 50 results +curl "https://gamma-api.polymarket.com/events?active=true&closed=false&limit=50&offset=50" + +# Page 3: Next 50 results +curl "https://gamma-api.polymarket.com/events?active=true&closed=false&limit=50&offset=100" +``` + +*** + +## Best Practices + +1. **For individual markets:** Use the slug method for direct lookups +2. **For category browsing:** Use tag filtering to reduce API calls +3. **For complete market discovery:** Use the events endpoint with pagination +4. **Always include `active=true`** when fetching live markets. The `closed` parameter now defaults to `false`, so closed markets are excluded automatically — pass `closed=true` only if you need historical data +5. **Use the events endpoint** and work backwards — events contain their associated markets, reducing the number of API calls needed + +*** + +## Next Steps + + + + Full endpoint documentation with parameters and response schemas. + + diff --git a/PolymarketDocumentation-main/docs/developers/market-makers/introduction.md b/PolymarketDocumentation-main/docs/developers/market-makers/introduction.md new file mode 100644 index 00000000..77bd86ea --- /dev/null +++ b/PolymarketDocumentation-main/docs/developers/market-makers/introduction.md @@ -0,0 +1,83 @@ +> ## Documentation Index +> Fetch the complete documentation index at: https://docs.polymarket.com/llms.txt +> Use this file to discover all available pages before exploring further. + +# Overview + +> Market making on Polymarket + +A Market Maker (MM) on Polymarket is a trader who provides liquidity to prediction markets by continuously posting bid and ask orders. By laying the spread, market makers enable other users to trade efficiently while earning the spread as compensation for the risk they take. + +Market makers are essential to Polymarket's ecosystem — they provide liquidity across markets, tighten spreads for better user experience, enable price discovery through continuous quoting, and absorb trading flow from retail and institutional users. + + + **Not a Market Maker?** If you're building an application that routes orders + for your users, see the [Builder Program](/builders/overview) instead. + + +*** + +## Getting Started + + + + Deploy wallets, fund with pUSD, and set token approvals. See the [Getting + Started](/market-makers/getting-started) guide. + + + + WebSocket for real-time orderbook updates, Gamma API for market metadata. + See [Market Data](/market-data/overview). + + + + Post orders via the CLOB REST API. See [Trading ](/market-makers/trading). + + + +*** + +## Quick Reference + +| Action | Tool | Documentation | +| -------------------- | -------------- | ------------------------------------------------- | +| Deposit pUSD | Bridge API | [Bridge](/trading/bridge/deposit) | +| Approve tokens | Relayer Client | [Getting Started](/market-makers/getting-started) | +| Post limit orders | CLOB REST API | [Create Orders](/trading/orders/create) | +| Monitor orderbook | WebSocket | [WebSocket](/market-data/websocket/overview) | +| Split pUSD to tokens | CTF / Relayer | [Inventory](/market-makers/inventory) | +| Merge tokens to pUSD | CTF / Relayer | [Inventory](/market-makers/inventory) | + +*** + +## What Is in This Section + + + + Deposits, token approvals, wallet deployment, API keys + + + + Quoting best practices, strategies, and risk controls + + + + Split, merge, and redeem outcome tokens + + + + Earn rewards for providing liquidity + + + +## Risks + + + Be careful with spread management — if your bid price is higher than your ask + price (a "negative spread" or "crossed market"), you will lose money on every + fill. Always validate your quote prices before submission. + + +## Support + +For market maker onboarding and support, contact [support@polymarket.com](mailto:support@polymarket.com). diff --git a/PolymarketDocumentation-main/docs/developers/market-makers/setup.md b/PolymarketDocumentation-main/docs/developers/market-makers/setup.md new file mode 100644 index 00000000..7d38c648 --- /dev/null +++ b/PolymarketDocumentation-main/docs/developers/market-makers/setup.md @@ -0,0 +1,241 @@ +> ## Documentation Index +> Fetch the complete documentation index at: https://docs.polymarket.com/llms.txt +> Use this file to discover all available pages before exploring further. + +# Getting Started + +> One-time setup for market making on Polymarket + +Before you can start market making, you need to complete these one-time setup steps — deposit pUSD to Polygon, deploy a wallet, approve tokens for trading, and generate API credentials. + + + + Market makers need pUSD on Polygon to fund their trading operations. + + | Method | Best For | Documentation | + | ----------------------- | ------------------------------------ | ---------------------------------------------------- | + | Bridge API | Automated deposits from other chains | [Bridge Deposit](/trading/bridge/deposit) | + | Direct Polygon transfer | Already have pUSD on Polygon | N/A | + | Cross-chain bridge | Large deposits from Ethereum | [Supported Assets](/trading/bridge/supported-assets) | + + ### Using the Bridge API + + ```typescript theme={null} + // Get bridge addresses for your Polymarket wallet + const deposit = await fetch("https://bridge.polymarket.com/deposit", { + method: "POST", + headers: { "Content-Type": "application/json" }, + body: JSON.stringify({ + address: "YOUR_POLYMARKET_WALLET_ADDRESS", + }), + }); + + // Returns bridge addresses for EVM, SVM, and BTC networks + const addresses = await deposit.json(); + // Send USDC to the appropriate address for your source chain + ``` + + + + ### EOA + + Standard Ethereum wallet. You pay for all onchain transactions (approvals, splits, merges, trade execution). + + ### Deposit Wallet + + Deposit wallets are the recommended wallet path for new API users. They are + deployed through Polymarket's relayer and use `POLY_1271` order signatures. + + See the [Deposit Wallet Guide](/trading/deposit-wallets) for the + wallet creation, approval, balance sync, and order-signing flow. + + ### Existing Safe Wallets + + Existing Gnosis Safe users can continue using their current wallet. Safe wallets + are deployed via Polymarket's relayer and support: + + * **Gasless transactions** — Polymarket pays gas fees for onchain operations + * **Contract wallet** — Enables advanced features like batched transactions + + For existing Safe integrations, deploy a Safe wallet using the Relayer Client: + + + ```typescript TypeScript theme={null} + import { RelayClient, RelayerTxType } from "@polymarket/builder-relayer-client"; + + const client = new RelayClient({ + host: "https://relayer-v2.polymarket.com/", + chain: 137, + signer, + relayerApiKey: process.env.RELAYER_API_KEY!, + relayerApiKeyAddress: process.env.RELAYER_API_KEY_ADDRESS!, + txType: RelayerTxType.SAFE, + }); + + // Deploy the Safe wallet + const response = await client.deploy(); + const result = await response.wait(); + console.log("Safe Address:", result?.proxyAddress); + ``` + + ```python Python theme={null} + from py_builder_relayer_client.client import RelayClient + + # client initialized with Relayer API Key credentials (see Gasless Transactions) + + # Deploy the Safe wallet + response = client.deploy() + result = response.wait() + print("Safe Address:", result.get("proxyAddress")) + ``` + + + + See [Gasless Transactions](/trading/gasless) for full Relayer Client setup + including local and remote signing configurations. + + + + + Before trading, you must approve the exchange contracts to spend your tokens. + + ### Required Approvals + + | Token | Spender | Purpose | + | -------------------- | --------------------- | ------------------------------ | + | pUSD | CTF Contract | Split pUSD into outcome tokens | + | CTF (outcome tokens) | CTF Exchange | Trade outcome tokens | + | CTF (outcome tokens) | Neg Risk CTF Exchange | Trade neg-risk market tokens | + + ### Contract Addresses + + ```typescript theme={null} + const ADDRESSES = { + pUSD: "0xC011a7E12a19f7B1f670d46F03B03f3342E82DFB", + CTF: "0x4D97DCd97eC945f40cF65F87097ACe5EA0476045", + CTF_EXCHANGE: "0xE111180000d2663C0091e4f400237545B87B996B", + NEG_RISK_CTF_EXCHANGE: "0xe2222d279d744050d28e00520010520000310F59", + NEG_RISK_ADAPTER: "0xd91E80cF2E7be2e162c6513ceD06f1dD0dA35296", + }; + ``` + + ### Approve via Relayer Client + + + ```typescript TypeScript theme={null} + import { ethers } from "ethers"; + import { Interface } from "ethers/lib/utils"; + + const erc20Interface = new Interface([ + "function approve(address spender, uint256 amount) returns (bool)", + ]); + + // Approve pUSD for CTF contract + const approveTx = { + to: ADDRESSES.pUSD, + data: erc20Interface.encodeFunctionData("approve", [ + ADDRESSES.CTF, + ethers.constants.MaxUint256, + ]), + value: "0", + }; + + const response = await client.execute([approveTx], "Approve pUSD for CTF"); + await response.wait(); + ``` + + ```python Python theme={null} + from web3 import Web3 + + pUSD = "0xC011a7E12a19f7B1f670d46F03B03f3342E82DFB" + CTF = "0x4D97DCd97eC945f40cF65F87097ACe5EA0476045" + MAX_UINT256 = 2**256 - 1 + + approve_tx = { + "to": pUSD, + "data": Web3().eth.contract( + address=pUSD, + abi=[{ + "name": "approve", + "type": "function", + "inputs": [ + {"name": "spender", "type": "address"}, + {"name": "amount", "type": "uint256"} + ], + "outputs": [{"type": "bool"}] + }] + ).encode_abi(abi_element_identifier="approve", args=[CTF, MAX_UINT256]), + "value": "0" + } + + response = client.execute([approve_tx], "Approve pUSD for CTF") + response.wait() + ``` + + + + + To place orders and access authenticated endpoints, you need L2 API credentials derived from your wallet. + + + ```typescript TypeScript theme={null} + import { ClobClient } from "@polymarket/clob-client-v2"; + + const client = new ClobClient({ + host: "https://clob.polymarket.com", + chain: 137, + signer, + }); + + // Derive API credentials from your wallet + const credentials = await client.createOrDeriveApiKey(); + console.log("API Key:", credentials.key); + console.log("Secret:", credentials.secret); + console.log("Passphrase:", credentials.passphrase); + ``` + + ```python Python theme={null} + from py_clob_client_v2 import ClobClient + import os + + private_key = os.getenv("PRIVATE_KEY") + + temp_client = ClobClient("https://clob.polymarket.com", key=private_key, chain_id=137) + credentials = temp_client.create_or_derive_api_key() + ``` + + ```rust Rust theme={null} + use std::str::FromStr; + use polymarket_client_sdk_v2::POLYGON; + use polymarket_client_sdk_v2::auth::{LocalSigner, Signer}; + use polymarket_client_sdk_v2::clob::{Client, Config}; + + let private_key = std::env::var("POLYMARKET_PRIVATE_KEY")?; + let signer = LocalSigner::from_str(&private_key)? + .with_chain_id(Some(POLYGON)); + + // The Rust SDK derives credentials and initializes in one step + let client = Client::new("https://clob.polymarket.com", Config::default())? + .authentication_builder(&signer) + .authenticate() + .await?; + ``` + + + See [Authentication](/trading/overview#authentication) for full details on signature types and REST API headers. + + + +*** + +## Next Steps + + + + Post limit orders and manage quotes + + + + Connect to real-time market data + + diff --git a/PolymarketDocumentation-main/docs/developers/misc-endpoints/bridge-overview.md b/PolymarketDocumentation-main/docs/developers/misc-endpoints/bridge-overview.md new file mode 100644 index 00000000..40164593 --- /dev/null +++ b/PolymarketDocumentation-main/docs/developers/misc-endpoints/bridge-overview.md @@ -0,0 +1,115 @@ +> ## Documentation Index +> Fetch the complete documentation index at: https://docs.polymarket.com/llms.txt +> Use this file to discover all available pages before exploring further. + +# Deposit + +> Bridge assets from any supported chain to fund your Polymarket account + +Polymarket uses **pUSD** (Polymarket USD) on Polygon as collateral for all trading. The Bridge API lets you deposit assets from Ethereum, Solana, Bitcoin, and other chains—they're automatically converted to pUSD on Polygon. + +## How It Works + +1. Request bridge addresses for your Polymarket wallet +2. Send assets to the appropriate address for your source chain +3. Assets are bridged and swapped to pUSD automatically +4. pUSD is credited to your wallet for trading + +## Create Bridge Addresses + +Generate unique bridge addresses linked to your Polymarket wallet. See the [Bridge API Reference](/api-reference/introduction) for full request and response schemas. + + + **Builders: attach your code.** If you route user funds through this endpoint, + pass your builder code via the optional `X-Builder-Code` header (bytes32 hex; + `0x` + 64 hex chars). It lets our bridge provider attribute traffic to your + app, so stuck or delayed transfers can be traced and prioritized. The header is + optional. Requests without it still succeed but return a `missing_builder_code` + warning, and a malformed code returns `400`. Get your code at [Settings → + Builder](https://polymarket.com/settings?tab=builder). + + +```bash theme={null} +curl -X POST https://bridge.polymarket.com/deposit \ + -H "Content-Type: application/json" \ + -H "X-Builder-Code: " \ + -d '{"address": "0x56687bf447db6ffa42ffe2204a05edaa20f55839"}' +``` + +### Address Types + +| Address | Use For | +| ------- | -------------------------------------------------------- | +| `evm` | Ethereum, Arbitrum, Base, Optimism, and other EVM chains | +| `svm` | Solana | +| `btc` | Bitcoin | +| `tvm` | Tron | + + + Each address is unique to your wallet. Only send assets from supported chains + to the correct address type. + + +## Deposit Flow + + + + Call `POST /deposit` with your Polymarket wallet address to get bridge + addresses. + + + + Verify your token is supported and meets the minimum deposit amount via + `/supported-assets`. + + + + Transfer tokens to the appropriate bridge address from your source chain. + + + + Monitor your deposit progress using `/status/{address}`. + + + +## USDC vs pUSD + +You can deposit either USDC (native) or USDC.e (bridged) as the source asset to your Polymarket wallet. Either way, the incoming USDC or USDC.e is wrapped into pUSD via the Collateral Onramp, and pUSD is what you hold and trade with on Polymarket. + +## Large Deposits + +For deposits over \$50,000 originating from a chain other than Polygon, we recommend using a third-party bridge to minimize slippage: + +* [DeBridge](https://app.debridge.finance/) +* [Across](https://app.across.to/bridge) +* [Portal](https://portalbridge.com/) + +Bridge directly to your Polymarket USDC (Polygon) bridge address. Polymarket is not affiliated with or responsible for any third-party bridge. + +## Minimum Deposits + +Each asset has a minimum deposit amount. Deposits below the minimum will not be processed. Check `/supported-assets` for current minimums. + +## Deposit Recovery + +If you deposited the wrong token, use this tool to recover your funds: + +[recovery.polymarket.com](https://recovery.polymarket.com/) + + + Sending unsupported tokens may cause **irrecoverable loss**. Always verify + your token is listed in [Supported Assets](/trading/bridge/supported-assets) + before depositing. + + +## Next Steps + + + + See all supported chains and tokens with minimum amounts. + + + + Track your deposit progress through completion. + + diff --git a/PolymarketDocumentation-main/docs/developers/neg-risk/overview.md b/PolymarketDocumentation-main/docs/developers/neg-risk/overview.md new file mode 100644 index 00000000..579d57c1 --- /dev/null +++ b/PolymarketDocumentation-main/docs/developers/neg-risk/overview.md @@ -0,0 +1,145 @@ +> ## Documentation Index +> Fetch the complete documentation index at: https://docs.polymarket.com/llms.txt +> Use this file to discover all available pages before exploring further. + +# Negative Risk Markets + +> Capital-efficient trading for multi-outcome events + +**Negative risk** is a mechanism for multi-outcome events where only one outcome can win. It enables capital-efficient trading by allowing positions across all outcomes within an event to be related through a **conversion** operation. + +## How It Works + +In a standard multi-outcome event, each market is independent. If you want to bet against one outcome, you must buy that outcome's No tokens—but those No tokens have no relationship to the other outcomes. + +Negative risk changes this. In a neg risk event: + +* A **No share** in any market can be converted into **1 Yes share in every other market** +* This conversion happens through the Neg Risk Adapter contract + +### Example + +Consider an event: "Who will win the 2024 Presidential Election?" with three outcomes: + +| Outcome | Your Position | +| ------- | ------------- | +| Trump | — | +| Harris | — | +| Other | 1 No | + +With negative risk, that 1 No on "Other" can be converted into: + +| Outcome | After Conversion | +| ------- | ---------------- | +| Trump | 1 Yes | +| Harris | 1 Yes | +| Other | — | + +This is capital-efficient because betting against one outcome is economically equivalent to betting *for* all other outcomes. + +## Identifying Neg Risk Markets + +The Gamma API includes a `negRisk` boolean on events and markets: + +```json theme={null} +{ + "id": "123", + "title": "Who will win the 2024 Presidential Election?", + "negRisk": true, + "markets": [...] +} +``` + +When placing orders on neg risk markets, you must specify this in your order options: + +```typescript theme={null} +const response = await client.createAndPostOrder( + { + tokenID: "TOKEN_ID", + price: 0.5, + size: 100, + side: Side.BUY, + }, + { + tickSize: "0.01", + negRisk: true, // Required for neg risk markets + }, +); +``` + +## Contract Addresses + +Neg risk markets use different contracts than standard markets: + +See [Contracts](/resources/contracts) for the Neg Risk Adapter and Neg Risk CTF Exchange addresses. + +## Augmented Negative Risk + +Standard negative risk requires the complete set of outcomes to be known at market creation. But sometimes new outcomes emerge after trading begins (e.g., a new candidate enters a race). + +**Augmented negative risk** solves this with: + +| Outcome Type | Description | +| ------------------------ | ------------------------------------------------------------- | +| **Named outcomes** | Known outcomes (e.g., "Trump", "Harris") | +| **Placeholder outcomes** | Reserved slots that can be clarified later (e.g., "Person A") | +| **Explicit Other** | Catches any outcome not explicitly named | + +### How Placeholders Work + +1. Event launches with named outcomes + placeholders + "Other" +2. When a new outcome emerges, a placeholder is clarified via the bulletin board +3. The "Other" definition narrows as placeholders are assigned + +### Trading Rules for Augmented Neg Risk + + + Only trade on **named outcomes**. Placeholder outcomes should be ignored until + they are named or until resolution occurs. The Polymarket UI does not display + unnamed outcomes. + + +* If the correct outcome at resolution is not named, the market resolves to "Other" +* The "Other" outcome's definition changes as placeholders are clarified—avoid trading it directly + +### Identifying Augmented Neg Risk + +An event is augmented neg risk when both flags are true: + +```json theme={null} +{ + "enableNegRisk": true, + "negRiskAugmented": true +} +``` + + + The Gamma API includes a boolean field `negRisk` on events and markets, which indicates whether the event uses negative risk. For augmented neg risk events, an additional `enableNegRisk` field is also `true`. When placing orders, the SDK option is always `negRisk: true` / `neg_risk: True` regardless of whether the market is standard or augmented neg risk. + + +## Technical Details + +### Conversion Mechanics + +The conversion operation is atomic and happens through the Neg Risk Adapter: + +1. You hold 1 No token for Outcome A +2. Call the convert function on the adapter +3. You receive 1 Yes token for every other outcome in the event + +## Resources + +* [Neg Risk Adapter Source Code](https://github.com/Polymarket/neg-risk-ctf-adapter) +* [Gamma API Documentation](/market-data/overview) + +## Next Steps + + + + Understand how multi-market events are structured. + + + + Learn about token operations like split, merge, and redeem. + + diff --git a/PolymarketDocumentation-main/docs/developers/proxy-wallet.md b/PolymarketDocumentation-main/docs/developers/proxy-wallet.md new file mode 100644 index 00000000..d099fd75 --- /dev/null +++ b/PolymarketDocumentation-main/docs/developers/proxy-wallet.md @@ -0,0 +1,437 @@ +> ## Documentation Index +> Fetch the complete documentation index at: https://docs.polymarket.com/llms.txt +> Use this file to discover all available pages before exploring further. + +# Authentication + +> How to authenticate requests to the CLOB API + +The CLOB API uses two levels of authentication: **L1 (Private Key)** and **L2 (API Key)**. Either can be accomplished using the CLOB client or REST API. + +## Public vs Authenticated + + + + The **Gamma API**, **Data API**, and CLOB read endpoints (orderbook, prices, spreads) require no authentication. + + + + CLOB trading endpoints (placing orders, cancellations, heartbeat) require all 5 `POLY_*` L2 HTTP headers. + + + +*** + +## Two-Level Authentication Model + +The CLOB uses two levels of authentication: L1 (Private Key) and L2 (API Key). Either can be accomplished using the CLOB client or REST API + +### L1 Authentication + +L1 authentication uses the wallet's private key to sign an EIP-712 message used in the request header. It proves ownership and control over the private key. The private key stays in control of the user and all trading activity remains non-custodial. + +**Used for:** + +* Creating API credentials +* Deriving existing API credentials +* Signing and creating user's orders locally + +### L2 Authentication + +L2 uses API credentials (apiKey, secret, passphrase) generated from L1 authentication. These are used solely to authenticate requests made to the CLOB API. Requests are signed using HMAC-SHA256. + +**Used for:** + +* Cancel or get user's open orders +* Check user's balances and allowances +* Post user's signed orders + + + Even with L2 authentication headers, methods that create user orders still + require the user to sign the order payload. + + +*** + +## Getting API Credentials + +Before making authenticated requests, you need to obtain API credentials using L1 authentication. + +### Using the SDK + + + + ```typescript theme={null} + import { ClobClient } from "@polymarket/clob-client-v2"; + import { createWalletClient, http } from "viem"; + import { privateKeyToAccount } from "viem/accounts"; + + const account = privateKeyToAccount(process.env.PRIVATE_KEY as `0x${string}`); + const signer = createWalletClient({ account, transport: http() }); + + const client = new ClobClient({ + host: "https://clob.polymarket.com", + chain: 137, // Polygon mainnet + signer, + }); + + // Creates new credentials or derives existing ones + const credentials = await client.createOrDeriveApiKey(); + + console.log(credentials); + // { + // key: "550e8400-e29b-41d4-a716-446655440000", + // secret: "base64EncodedSecretString", + // passphrase: "randomPassphraseString" + // } + ``` + + + + ```python theme={null} + from py_clob_client_v2 import ClobClient + import os + + client = ClobClient( + host="https://clob.polymarket.com", + chain_id=137, # Polygon mainnet + key=os.getenv("PRIVATE_KEY") + ) + + # Creates new credentials or derives existing ones + credentials = client.create_or_derive_api_key() + + print(credentials) + # { + # "apiKey": "550e8400-e29b-41d4-a716-446655440000", + # "secret": "base64EncodedSecretString", + # "passphrase": "randomPassphraseString" + # } + ``` + + + + ```rust theme={null} + use std::str::FromStr; + use polymarket_client_sdk_v2::POLYGON; + use polymarket_client_sdk_v2::auth::{LocalSigner, Signer}; + use polymarket_client_sdk_v2::clob::{Client, Config}; + + let private_key = std::env::var("POLYMARKET_PRIVATE_KEY")?; + let signer = LocalSigner::from_str(&private_key)? + .with_chain_id(Some(POLYGON)); + + // Creates new credentials or derives existing ones, + // then initializes the authenticated client — all in one step + let client = Client::new("https://clob.polymarket.com", Config::default())? + .authentication_builder(&signer) + .authenticate() + .await?; + + let credentials = client.credentials(); + println!("API Key: {}", credentials.key()); + ``` + + + + + **Never commit private keys to version control.** Always use environment + variables or secure key management systems. + + +### Using the REST API + +While we highly recommend using our provided clients to handle signing and authentication, the following is for developers who choose NOT to use our [Python](https://github.com/Polymarket/py-clob-client-v2) or [TypeScript](https://github.com/Polymarket/clob-client-v2) clients. + +**Create API Credentials** + +```bash theme={null} +POST https://clob.polymarket.com/auth/api-key +``` + +**Derive API Credentials** + +```bash theme={null} +GET https://clob.polymarket.com/auth/derive-api-key +``` + +Required L1 headers: + +| Header | Description | +| ---------------- | ---------------------- | +| `POLY_ADDRESS` | Polygon signer address | +| `POLY_SIGNATURE` | CLOB EIP-712 signature | +| `POLY_TIMESTAMP` | Current UNIX timestamp | +| `POLY_NONCE` | Nonce (default: 0) | + +The `POLY_SIGNATURE` is generated by signing the following EIP-712 struct: + + + + ```typescript TypeScript theme={null} + const domain = { + name: "ClobAuthDomain", + version: "1", + chainId: chainId, // Polygon Chain ID 137 + }; + + const types = { + ClobAuth: [ + { name: "address", type: "address" }, + { name: "timestamp", type: "string" }, + { name: "nonce", type: "uint256" }, + { name: "message", type: "string" }, + ], + }; + + const value = { + address: signingAddress, // The Signing address + timestamp: ts, // The CLOB API server timestamp + nonce: nonce, // The nonce used + message: "This message attests that I control the given wallet", + }; + + const sig = await signer._signTypedData(domain, types, value); + ``` + + ```python Python theme={null} + domain = { + "name": "ClobAuthDomain", + "version": "1", + "chainId": chainId, # Polygon Chain ID 137 + } + + types = { + "ClobAuth": [ + {"name": "address", "type": "address"}, + {"name": "timestamp", "type": "string"}, + {"name": "nonce", "type": "uint256"}, + {"name": "message", "type": "string"}, + ] + } + + value = { + "address": signingAddress, # The signing address + "timestamp": ts, # The CLOB API server timestamp + "nonce": nonce, # The nonce used + "message": "This message attests that I control the given wallet", + } + + sig = signer.sign_typed_data(domain, types, value) + ``` + + + +Reference implementations: + +* [TypeScript](https://github.com/Polymarket/clob-client-v2/blob/main/src/signing/eip712.ts) +* [Python](https://github.com/Polymarket/py-clob-client-v2/blob/main/py_clob_client_v2/signing/eip712.py) + +Response: + +```json theme={null} +{ + "apiKey": "550e8400-e29b-41d4-a716-446655440000", + "secret": "base64EncodedSecretString", + "passphrase": "randomPassphraseString" +} +``` + +**You'll need all three values for L2 authentication.** + +*** + +## L2 Authentication Headers + +All trading endpoints require these 5 headers: + +| Header | Description | +| ----------------- | ----------------------------- | +| `POLY_ADDRESS` | Polygon signer address | +| `POLY_SIGNATURE` | HMAC signature for request | +| `POLY_TIMESTAMP` | Current UNIX timestamp | +| `POLY_API_KEY` | User's API `apiKey` value | +| `POLY_PASSPHRASE` | User's API `passphrase` value | + +The `POLY_SIGNATURE` for L2 is an HMAC-SHA256 signature created using the user's API credentials `secret` value. Reference implementations can be found in the [TypeScript](https://github.com/Polymarket/clob-client-v2/blob/main/src/signing/hmac.ts) and [Python](https://github.com/Polymarket/py-clob-client-v2/blob/main/py_clob_client_v2/signing/hmac.py) clients. + +### CLOB Client + + + + ```typescript theme={null} + import { ClobClient, Side } from "@polymarket/clob-client-v2"; + import { createWalletClient, http } from "viem"; + import { privateKeyToAccount } from "viem/accounts"; + + const account = privateKeyToAccount(process.env.PRIVATE_KEY as `0x${string}`); + const signer = createWalletClient({ account, transport: http() }); + const depositWalletAddress = process.env.DEPOSIT_WALLET_ADDRESS!; + + const client = new ClobClient({ + host: "https://clob.polymarket.com", + chain: 137, + signer, + creds: apiCreds, // Generated from L1 auth, API credentials enable L2 methods + signatureType: 3, // POLY_1271, explained below + funderAddress: depositWalletAddress, // deposit wallet funder + }); + + // Now you can trade! + const order = await client.createAndPostOrder( + { tokenID: "123456", price: 0.65, size: 100, side: Side.BUY }, + { tickSize: "0.01", negRisk: false } + ); + ``` + + + + ```python theme={null} + from py_clob_client_v2 import ClobClient, OrderArgs, PartialCreateOrderOptions + from py_clob_client_v2.order_builder.constants import BUY + import os + + client = ClobClient( + host="https://clob.polymarket.com", + chain_id=137, + key=os.getenv("PRIVATE_KEY"), + creds=api_creds, # Generated from L1 auth, API credentials enable L2 methods + signature_type=3, # POLY_1271, explained below + funder=os.getenv("DEPOSIT_WALLET_ADDRESS") + ) + + # Now you can trade! + order = client.create_and_post_order( + OrderArgs(token_id="123456", price=0.65, size=100, side=BUY), + options=PartialCreateOrderOptions(tick_size="0.01", neg_risk=False), + ) + ``` + + + + ```rust theme={null} + use polymarket_client_sdk_v2::clob::types::{Side, SignatureType}; + use polymarket_client_sdk_v2::types::dec; + + let deposit_wallet = std::env::var("DEPOSIT_WALLET_ADDRESS")?.parse()?; + + let client = Client::new("https://clob.polymarket.com", Config::default())? + .authentication_builder(&signer) + .funder(deposit_wallet) + .signature_type(SignatureType::Poly1271) + .authenticate() + .await?; + + // Now you can trade! + let order = client.limit_order() + .token_id("123456".parse()?) + .price(dec!(0.65)) + .size(dec!(100)) + .side(Side::Buy) + .build().await?; + let signed = client.sign(&signer, order).await?; + let response = client.post_order(signed).await?; + ``` + + + + + Even with L2 authentication headers, methods that create user orders still + require the user to sign the order payload. + + +*** + +## Signature Types and Funder + +When initializing the L2 client, you must specify your wallet **signatureType** and the **funder** address which holds the funds: + +| Signature Type | Value | Description | +| -------------- | ----- | -------------------------------------------------------------------------------------------------------------------------- | +| EOA | `0` | Standard Ethereum wallet (MetaMask). Funder is the EOA address and will need POL to pay gas on transactions. | +| POLY\_PROXY | `1` | Existing Polymarket proxy wallet flow, commonly used by users who logged in via Magic Link email/Google. | +| GNOSIS\_SAFE | `2` | Existing Gnosis Safe wallet flow. Existing Safe users can continue using this type. | +| POLY\_1271 | `3` | Deposit wallet flow for new API users. The funder is the deposit wallet address and orders are validated through ERC-1271. | + + + New API users should use deposit wallets with `POLY_1271`. Existing Safe and + Proxy users are unaffected and can keep using their current funder address and + signature type. See the [Deposit Wallet Guide](/trading/deposit-wallets) for + setup details. + + +*** + +## Security Best Practices + + + + Store private keys in environment variables or secure key management systems. Never commit them to version control. + + ```bash theme={null} + # .env (never commit this file) + PRIVATE_KEY=0x... + ``` + + + + Never expose your API secret in client-side code. All authenticated requests should originate from your backend. + + + +*** + +## Troubleshooting + + + + Your wallet's private key is incorrect or improperly formatted. + + **Solutions:** + + * Verify your private key is a valid hex string (starts with "0x") + * Ensure you're using the correct key for the intended address + * Check that the key has proper permissions + + + + The nonce you provided has already been used to create an API key. + + **Solutions:** + + * Use `deriveApiKey()` with the same nonce to retrieve existing credentials + * Or use a different nonce with `createApiKey()` + + + + Your funder address is incorrect or doesn't match your wallet. + + **Solution:** Check your Polymarket profile address at [polymarket.com/settings](https://polymarket.com/settings). + + If it does not exist or user has never logged into Polymarket.com, deploy it first before creating L2 authentication. + + + + Unfortunately, there's no way to recover lost API credentials without the nonce. You'll need to create new credentials: + + ```typescript theme={null} + // Create fresh credentials with a new nonce + const newCreds = await client.createApiKey(); + // Save the nonce this time! + ``` + + + +*** + +## Next Steps + + + + Learn how to create and submit orders. + + + + Check trading availability by region. + + diff --git a/PolymarketDocumentation-main/docs/developers/resolution/UMA.md b/PolymarketDocumentation-main/docs/developers/resolution/UMA.md new file mode 100644 index 00000000..e7c8d916 --- /dev/null +++ b/PolymarketDocumentation-main/docs/developers/resolution/UMA.md @@ -0,0 +1,151 @@ +> ## Documentation Index +> Fetch the complete documentation index at: https://docs.polymarket.com/llms.txt +> Use this file to discover all available pages before exploring further. + +# Resolution + +> How markets are resolved and winning positions redeemed + +When the outcome of an event becomes known, the market is **resolved**. Resolution determines which outcome won, allowing holders of winning tokens to redeem them for \$1 each. Losing tokens become worthless. + +Polymarket uses the **UMA Optimistic Oracle** for decentralized, permissionless resolution. Anyone can propose an outcome, and anyone can dispute it if they believe it's incorrect. + + + + + + + +## Resolution Rules + +Every market has pre-defined resolution rules that specify: + +* **Resolution source** — Where the outcome will be determined from (e.g., official announcements, specific websites) +* **End date** — When the market is eligible for resolution +* **Edge cases** — How ambiguous situations should be handled + + + Always read the resolution rules before trading. The market title describes + the question, but the **rules** define how it resolves. + + + + + Anyone can propose a resolution by: + + 1. Selecting the winning outcome + 2. Posting a bond (typically \$750 pUSD) + 3. Submitting the proposal to the UMA Oracle + + If the proposal is correct and undisputed, the proposer receives their bond back plus a reward. + + + If you propose incorrectly or too early, you lose your entire bond. Only + propose if you're confident in the outcome and understand the process. + + + + + After a proposal, there's a **2-hour challenge period** where anyone can dispute the outcome. + + * **If no dispute**: The proposal is accepted and the market resolves + * **If disputed**: A new proposal round begins. If the second proposal is also disputed, the resolution escalates to UMA's DVM (Data Verification Mechanism) for a token holder vote. + + There are three possible resolution flows: + + 1. **No dispute** — Propose then Resolve (fastest, \~2 hours) + 2. **One dispute** — Propose, Challenge, second Propose, Resolve (second proposal accepted) + 3. **Two disputes** — Propose, Challenge, second Propose, second Challenge, Resolve via DVM vote + + + + To dispute a proposal: + + 1. Post a counter-bond (same amount as proposer, typically \$750) + 2. The dispute triggers a new proposal round, or if already in the second round, a debate period + + During the **24-48 hour debate period**, evidence can be submitted in UMA's Discord channels (`#evidence-rationale` and `#voting-discussion`). + + + + After the debate period, UMA token holders vote on the correct outcome. The voting process takes approximately 48 hours. + + | Outcome | Result | Bond Distribution | + | ----------------- | -------------------------------------- | -------------------------------------------------------------------------------------------------------- | + | **Proposer wins** | Original proposal accepted | Proposer gets bond back + half of disputer's bond | + | **Disputer wins** | Proposal rejected, new proposal needed | Disputer gets bond back + half of proposer's bond | + | **Too Early** | Event hasn't concluded yet | Disputer gets bond back + half of proposer's bond | + | **Unknown/50-50** | Neither outcome applicable (rare) | Market resolves 50/50 — each token redeems for \$0.50; disputer gets bond back + half of proposer's bond | + + + +## After Resolution + +Once a market resolves: + +* **Trading stops** — You can no longer buy or sell tokens for this market +* **Winning tokens** become redeemable for \$1.00 each +* **Losing tokens** become worthless (\$0.00) + +### Redeeming Tokens + +After resolution, redeem through the CTF collateral adapter to exchange winning tokens for pUSD. The adapter burns your ERC1155 outcome tokens through the CTF contract, receives the released USDC.e collateral, wraps it into pUSD, and returns pUSD to your wallet. + +``` +100 winning tokens → $100 pUSD +``` + +## Clarifications + +In rare cases, unforeseen circumstances require clarification of the rules after trading begins. Polymarket may issue an **"Additional context"** update that proposers and voters should consider during resolution. + +Clarifications: + +* Cannot change the fundamental intent of the question +* Are published onchain via the bulletin board contract +* Should be considered by UMA voters when resolving disputes + + + If you believe a clarification is needed, request it in the [Polymarket + Discord](https://discord.com/invite/polymarket) `#market-review` channel. + + +## Resolution Timeline + +| Phase | Duration | +| --------------------------- | ----------- | +| Challenge period | 2 hours | +| Debate period (if disputed) | 24-48 hours | +| UMA voting (if disputed) | \~48 hours | + +**Undisputed resolution**: \~2 hours after proposal + +**Disputed resolution**: 4-6 days total + +## Contract Addresses + +| Contract | Address | Network | +| ---------------------- | -------------------------------------------- | --------------- | +| **UmaCtfAdapter v3.0** | `0x157Ce2d672854c848c9b79C49a8Cc6cc89176a49` | Polygon Mainnet | +| **UmaCtfAdapter v2.0** | `0x6A9D222616C90FcA5754cd1333cFD9b7fb6a4F74` | Polygon Mainnet | +| **UmaCtfAdapter v1.0** | `0xCB1822859cEF82Cd2Eb4E6276C7916e692995130` | Polygon Mainnet | + +## Resources + +* [UMA Oracle Portal](https://oracle.uma.xyz/) — View and interact with proposals +* [UMA Documentation](https://docs.uma.xyz/) — Learn more about the Optimistic Oracle +* [Polymarket Discord](https://discord.com/invite/polymarket) — Discuss resolutions and request clarifications +* [UmaCtfAdapter Source Code](https://github.com/Polymarket/uma-ctf-adapter) — Smart contract source +* [UmaCtfAdapter Audit](https://github.com/Polymarket/uma-ctf-adapter/blob/main/audit/Polymarket_UMA_Optimistic_Oracle_Adapter_Audit.pdf) — Security audit report + +## Next Steps + + + + Learn how to redeem winning tokens after resolution. + + + + Understand how markets are structured. + + diff --git a/PolymarketDocumentation-main/docs/developers/sports-websocket/message-format.md b/PolymarketDocumentation-main/docs/developers/sports-websocket/message-format.md new file mode 100644 index 00000000..2afd0dee --- /dev/null +++ b/PolymarketDocumentation-main/docs/developers/sports-websocket/message-format.md @@ -0,0 +1,222 @@ +> ## Documentation Index +> Fetch the complete documentation index at: https://docs.polymarket.com/llms.txt +> Use this file to discover all available pages before exploring further. + +# Sports WebSocket + +> Live sports scores and game state + +The Sports WebSocket provides real-time sports results updates, including scores, periods, and game status. No authentication required. + + + This feed is provided for informational purposes only. It may be delayed, + contain errors, or omit recent events. Polymarket does not provide trading or + investment advice, and this content should not be used as the basis for any + trading decision. + + +## Endpoint + +``` +wss://sports-api.polymarket.com/ws +``` + +No subscription message required — connect and start receiving data for all active sports events. + +## Heartbeat + +The server sends `ping` every 5 seconds. Respond with `pong` within 10 seconds or the connection will close. + +```javascript theme={null} +ws.onmessage = (event) => { + if (event.data === "ping") { + ws.send("pong"); + return; + } + + // Handle JSON messages... +}; +``` + +## Message Type + +Each message is a JSON object with game state fields. + +### sport\_result + +Emitted when: + +* A match goes live +* The score changes +* The period changes (e.g., halftime, overtime) +* A match ends +* Possession changes (NFL and CFB only) + +**NFL (in progress):** + +```json theme={null} +{ + "gameId": 19439, + "leagueAbbreviation": "nfl", + "slug": "nfl-lac-buf-2025-01-26", + "homeTeam": "LAC", + "awayTeam": "BUF", + "status": "InProgress", + "score": "3-16", + "period": "Q4", + "elapsed": "5:18", + "live": true, + "ended": false, + "turn": "lac" +} +``` + +**Esports — CS2 (finished):** + +```json theme={null} +{ + "gameId": 1317359, + "leagueAbbreviation": "cs2", + "slug": "cs2-arcred-the-glecs-2025-07-20", + "homeTeam": "ARCRED", + "awayTeam": "The glecs", + "status": "finished", + "score": "000-000|2-0|Bo3", + "period": "2/3", + "live": false, + "ended": true, + "finished_timestamp": "2025-07-20T18:30:00.000Z" +} +``` + +The `finished_timestamp` field is an ISO 8601 timestamp only present when `ended: true`. + +The `slug` field follows the format `{league}-{team1}-{team2}-{date}` (e.g., `nfl-buf-kc-2025-01-26`). + +## Period Values + +| Period | Description | +| ---------------------- | --------------------------------------- | +| `1H` | First half | +| `2H` | Second half | +| `1Q`, `2Q`, `3Q`, `4Q` | Quarters (NFL, NBA) | +| `HT` | Halftime | +| `FT` | Full time (match ended in regulation) | +| `FT OT` | Full time with overtime | +| `FT NR` | Full time, no result (draw or canceled) | +| `End 1`, `End 2`, ... | End of inning (MLB) | +| `1/3`, `2/3`, `3/3` | Map number in Bo3 series (Esports) | +| `1/5`, `2/5`, ... | Map number in Bo5 series (Esports) | + +## Game Status Values + +Game status values vary by sport: + +### NFL + +| Status | Description | +| -------------- | ---------------------------- | +| `Scheduled` | Game not yet started | +| `InProgress` | Game currently playing | +| `Final` | Game completed in regulation | +| `F/OT` | Final after overtime | +| `Suspended` | Game suspended | +| `Postponed` | Game postponed | +| `Delayed` | Game delayed | +| `Canceled` | Game canceled | +| `Forfeit` | Game forfeited | +| `NotNecessary` | Scheduled, but not needed | + +### NHL + +| Status | Description | +| -------------- | ---------------------------- | +| `Scheduled` | Game not yet started | +| `InProgress` | Game currently playing | +| `Final` | Game completed in regulation | +| `F/OT` | Final after overtime | +| `F/SO` | Final after shootout | +| `Suspended` | Game suspended | +| `Postponed` | Game postponed | +| `Delayed` | Game delayed | +| `Canceled` | Game canceled | +| `Forfeit` | Game forfeited | +| `NotNecessary` | Scheduled, but not needed | + +### MLB + +| Status | Description | +| -------------- | ------------------------- | +| `Scheduled` | Game not yet started | +| `InProgress` | Game currently playing | +| `Final` | Game completed | +| `Suspended` | Game suspended | +| `Delayed` | Game delayed | +| `Postponed` | Game postponed | +| `Canceled` | Game canceled | +| `Forfeit` | Game forfeited | +| `NotNecessary` | Scheduled, but not needed | + +### NBA and CBB + +| Status | Description | +| -------------- | ------------------------- | +| `Scheduled` | Game not yet started | +| `InProgress` | Game currently playing | +| `Final` | Game completed | +| `F/OT` | Final after overtime | +| `Suspended` | Game suspended | +| `Postponed` | Game postponed | +| `Delayed` | Game delayed | +| `Canceled` | Game canceled | +| `Forfeit` | Game forfeited | +| `NotNecessary` | Scheduled, but not needed | + +### CFB + +| Status | Description | +| ------------ | ---------------------- | +| `Scheduled` | Game not yet started | +| `InProgress` | Game currently playing | +| `Final` | Game completed | +| `F/OT` | Final after overtime | +| `Suspended` | Game suspended | +| `Postponed` | Game postponed | +| `Delayed` | Game delayed | +| `Canceled` | Game canceled | +| `Forfeit` | Game forfeited | + +### Soccer + +| Status | Description | +| ----------------- | ------------------------------------ | +| `Scheduled` | Game not yet started | +| `InProgress` | Game currently playing | +| `Break` | Halftime or other break | +| `Suspended` | Game suspended | +| `PenaltyShootout` | Penalty shootout in progress | +| `Final` | Game completed | +| `Awarded` | Result awarded due to ruling/forfeit | +| `Postponed` | Game postponed | +| `Canceled` | Game canceled | + +### Esports + +| Status | Description | +| ------------- | ----------------------- | +| `not_started` | Match not yet started | +| `running` | Match currently playing | +| `finished` | Match completed | +| `postponed` | Match postponed | +| `canceled` | Match canceled | + +### Tennis + +| Status | Description | +| ------------ | ----------------------- | +| `scheduled` | Match not yet started | +| `inprogress` | Match currently playing | +| `suspended` | Match suspended | +| `finished` | Match completed | +| `postponed` | Match postponed | +| `cancelled` | Match canceled | diff --git a/PolymarketDocumentation-main/docs/developers/sports-websocket/overview.md b/PolymarketDocumentation-main/docs/developers/sports-websocket/overview.md new file mode 100644 index 00000000..2afd0dee --- /dev/null +++ b/PolymarketDocumentation-main/docs/developers/sports-websocket/overview.md @@ -0,0 +1,222 @@ +> ## Documentation Index +> Fetch the complete documentation index at: https://docs.polymarket.com/llms.txt +> Use this file to discover all available pages before exploring further. + +# Sports WebSocket + +> Live sports scores and game state + +The Sports WebSocket provides real-time sports results updates, including scores, periods, and game status. No authentication required. + + + This feed is provided for informational purposes only. It may be delayed, + contain errors, or omit recent events. Polymarket does not provide trading or + investment advice, and this content should not be used as the basis for any + trading decision. + + +## Endpoint + +``` +wss://sports-api.polymarket.com/ws +``` + +No subscription message required — connect and start receiving data for all active sports events. + +## Heartbeat + +The server sends `ping` every 5 seconds. Respond with `pong` within 10 seconds or the connection will close. + +```javascript theme={null} +ws.onmessage = (event) => { + if (event.data === "ping") { + ws.send("pong"); + return; + } + + // Handle JSON messages... +}; +``` + +## Message Type + +Each message is a JSON object with game state fields. + +### sport\_result + +Emitted when: + +* A match goes live +* The score changes +* The period changes (e.g., halftime, overtime) +* A match ends +* Possession changes (NFL and CFB only) + +**NFL (in progress):** + +```json theme={null} +{ + "gameId": 19439, + "leagueAbbreviation": "nfl", + "slug": "nfl-lac-buf-2025-01-26", + "homeTeam": "LAC", + "awayTeam": "BUF", + "status": "InProgress", + "score": "3-16", + "period": "Q4", + "elapsed": "5:18", + "live": true, + "ended": false, + "turn": "lac" +} +``` + +**Esports — CS2 (finished):** + +```json theme={null} +{ + "gameId": 1317359, + "leagueAbbreviation": "cs2", + "slug": "cs2-arcred-the-glecs-2025-07-20", + "homeTeam": "ARCRED", + "awayTeam": "The glecs", + "status": "finished", + "score": "000-000|2-0|Bo3", + "period": "2/3", + "live": false, + "ended": true, + "finished_timestamp": "2025-07-20T18:30:00.000Z" +} +``` + +The `finished_timestamp` field is an ISO 8601 timestamp only present when `ended: true`. + +The `slug` field follows the format `{league}-{team1}-{team2}-{date}` (e.g., `nfl-buf-kc-2025-01-26`). + +## Period Values + +| Period | Description | +| ---------------------- | --------------------------------------- | +| `1H` | First half | +| `2H` | Second half | +| `1Q`, `2Q`, `3Q`, `4Q` | Quarters (NFL, NBA) | +| `HT` | Halftime | +| `FT` | Full time (match ended in regulation) | +| `FT OT` | Full time with overtime | +| `FT NR` | Full time, no result (draw or canceled) | +| `End 1`, `End 2`, ... | End of inning (MLB) | +| `1/3`, `2/3`, `3/3` | Map number in Bo3 series (Esports) | +| `1/5`, `2/5`, ... | Map number in Bo5 series (Esports) | + +## Game Status Values + +Game status values vary by sport: + +### NFL + +| Status | Description | +| -------------- | ---------------------------- | +| `Scheduled` | Game not yet started | +| `InProgress` | Game currently playing | +| `Final` | Game completed in regulation | +| `F/OT` | Final after overtime | +| `Suspended` | Game suspended | +| `Postponed` | Game postponed | +| `Delayed` | Game delayed | +| `Canceled` | Game canceled | +| `Forfeit` | Game forfeited | +| `NotNecessary` | Scheduled, but not needed | + +### NHL + +| Status | Description | +| -------------- | ---------------------------- | +| `Scheduled` | Game not yet started | +| `InProgress` | Game currently playing | +| `Final` | Game completed in regulation | +| `F/OT` | Final after overtime | +| `F/SO` | Final after shootout | +| `Suspended` | Game suspended | +| `Postponed` | Game postponed | +| `Delayed` | Game delayed | +| `Canceled` | Game canceled | +| `Forfeit` | Game forfeited | +| `NotNecessary` | Scheduled, but not needed | + +### MLB + +| Status | Description | +| -------------- | ------------------------- | +| `Scheduled` | Game not yet started | +| `InProgress` | Game currently playing | +| `Final` | Game completed | +| `Suspended` | Game suspended | +| `Delayed` | Game delayed | +| `Postponed` | Game postponed | +| `Canceled` | Game canceled | +| `Forfeit` | Game forfeited | +| `NotNecessary` | Scheduled, but not needed | + +### NBA and CBB + +| Status | Description | +| -------------- | ------------------------- | +| `Scheduled` | Game not yet started | +| `InProgress` | Game currently playing | +| `Final` | Game completed | +| `F/OT` | Final after overtime | +| `Suspended` | Game suspended | +| `Postponed` | Game postponed | +| `Delayed` | Game delayed | +| `Canceled` | Game canceled | +| `Forfeit` | Game forfeited | +| `NotNecessary` | Scheduled, but not needed | + +### CFB + +| Status | Description | +| ------------ | ---------------------- | +| `Scheduled` | Game not yet started | +| `InProgress` | Game currently playing | +| `Final` | Game completed | +| `F/OT` | Final after overtime | +| `Suspended` | Game suspended | +| `Postponed` | Game postponed | +| `Delayed` | Game delayed | +| `Canceled` | Game canceled | +| `Forfeit` | Game forfeited | + +### Soccer + +| Status | Description | +| ----------------- | ------------------------------------ | +| `Scheduled` | Game not yet started | +| `InProgress` | Game currently playing | +| `Break` | Halftime or other break | +| `Suspended` | Game suspended | +| `PenaltyShootout` | Penalty shootout in progress | +| `Final` | Game completed | +| `Awarded` | Result awarded due to ruling/forfeit | +| `Postponed` | Game postponed | +| `Canceled` | Game canceled | + +### Esports + +| Status | Description | +| ------------- | ----------------------- | +| `not_started` | Match not yet started | +| `running` | Match currently playing | +| `finished` | Match completed | +| `postponed` | Match postponed | +| `canceled` | Match canceled | + +### Tennis + +| Status | Description | +| ------------ | ----------------------- | +| `scheduled` | Match not yet started | +| `inprogress` | Match currently playing | +| `suspended` | Match suspended | +| `finished` | Match completed | +| `postponed` | Match postponed | +| `cancelled` | Match canceled | diff --git a/PolymarketDocumentation-main/docs/developers/sports-websocket/quickstart.md b/PolymarketDocumentation-main/docs/developers/sports-websocket/quickstart.md new file mode 100644 index 00000000..2afd0dee --- /dev/null +++ b/PolymarketDocumentation-main/docs/developers/sports-websocket/quickstart.md @@ -0,0 +1,222 @@ +> ## Documentation Index +> Fetch the complete documentation index at: https://docs.polymarket.com/llms.txt +> Use this file to discover all available pages before exploring further. + +# Sports WebSocket + +> Live sports scores and game state + +The Sports WebSocket provides real-time sports results updates, including scores, periods, and game status. No authentication required. + + + This feed is provided for informational purposes only. It may be delayed, + contain errors, or omit recent events. Polymarket does not provide trading or + investment advice, and this content should not be used as the basis for any + trading decision. + + +## Endpoint + +``` +wss://sports-api.polymarket.com/ws +``` + +No subscription message required — connect and start receiving data for all active sports events. + +## Heartbeat + +The server sends `ping` every 5 seconds. Respond with `pong` within 10 seconds or the connection will close. + +```javascript theme={null} +ws.onmessage = (event) => { + if (event.data === "ping") { + ws.send("pong"); + return; + } + + // Handle JSON messages... +}; +``` + +## Message Type + +Each message is a JSON object with game state fields. + +### sport\_result + +Emitted when: + +* A match goes live +* The score changes +* The period changes (e.g., halftime, overtime) +* A match ends +* Possession changes (NFL and CFB only) + +**NFL (in progress):** + +```json theme={null} +{ + "gameId": 19439, + "leagueAbbreviation": "nfl", + "slug": "nfl-lac-buf-2025-01-26", + "homeTeam": "LAC", + "awayTeam": "BUF", + "status": "InProgress", + "score": "3-16", + "period": "Q4", + "elapsed": "5:18", + "live": true, + "ended": false, + "turn": "lac" +} +``` + +**Esports — CS2 (finished):** + +```json theme={null} +{ + "gameId": 1317359, + "leagueAbbreviation": "cs2", + "slug": "cs2-arcred-the-glecs-2025-07-20", + "homeTeam": "ARCRED", + "awayTeam": "The glecs", + "status": "finished", + "score": "000-000|2-0|Bo3", + "period": "2/3", + "live": false, + "ended": true, + "finished_timestamp": "2025-07-20T18:30:00.000Z" +} +``` + +The `finished_timestamp` field is an ISO 8601 timestamp only present when `ended: true`. + +The `slug` field follows the format `{league}-{team1}-{team2}-{date}` (e.g., `nfl-buf-kc-2025-01-26`). + +## Period Values + +| Period | Description | +| ---------------------- | --------------------------------------- | +| `1H` | First half | +| `2H` | Second half | +| `1Q`, `2Q`, `3Q`, `4Q` | Quarters (NFL, NBA) | +| `HT` | Halftime | +| `FT` | Full time (match ended in regulation) | +| `FT OT` | Full time with overtime | +| `FT NR` | Full time, no result (draw or canceled) | +| `End 1`, `End 2`, ... | End of inning (MLB) | +| `1/3`, `2/3`, `3/3` | Map number in Bo3 series (Esports) | +| `1/5`, `2/5`, ... | Map number in Bo5 series (Esports) | + +## Game Status Values + +Game status values vary by sport: + +### NFL + +| Status | Description | +| -------------- | ---------------------------- | +| `Scheduled` | Game not yet started | +| `InProgress` | Game currently playing | +| `Final` | Game completed in regulation | +| `F/OT` | Final after overtime | +| `Suspended` | Game suspended | +| `Postponed` | Game postponed | +| `Delayed` | Game delayed | +| `Canceled` | Game canceled | +| `Forfeit` | Game forfeited | +| `NotNecessary` | Scheduled, but not needed | + +### NHL + +| Status | Description | +| -------------- | ---------------------------- | +| `Scheduled` | Game not yet started | +| `InProgress` | Game currently playing | +| `Final` | Game completed in regulation | +| `F/OT` | Final after overtime | +| `F/SO` | Final after shootout | +| `Suspended` | Game suspended | +| `Postponed` | Game postponed | +| `Delayed` | Game delayed | +| `Canceled` | Game canceled | +| `Forfeit` | Game forfeited | +| `NotNecessary` | Scheduled, but not needed | + +### MLB + +| Status | Description | +| -------------- | ------------------------- | +| `Scheduled` | Game not yet started | +| `InProgress` | Game currently playing | +| `Final` | Game completed | +| `Suspended` | Game suspended | +| `Delayed` | Game delayed | +| `Postponed` | Game postponed | +| `Canceled` | Game canceled | +| `Forfeit` | Game forfeited | +| `NotNecessary` | Scheduled, but not needed | + +### NBA and CBB + +| Status | Description | +| -------------- | ------------------------- | +| `Scheduled` | Game not yet started | +| `InProgress` | Game currently playing | +| `Final` | Game completed | +| `F/OT` | Final after overtime | +| `Suspended` | Game suspended | +| `Postponed` | Game postponed | +| `Delayed` | Game delayed | +| `Canceled` | Game canceled | +| `Forfeit` | Game forfeited | +| `NotNecessary` | Scheduled, but not needed | + +### CFB + +| Status | Description | +| ------------ | ---------------------- | +| `Scheduled` | Game not yet started | +| `InProgress` | Game currently playing | +| `Final` | Game completed | +| `F/OT` | Final after overtime | +| `Suspended` | Game suspended | +| `Postponed` | Game postponed | +| `Delayed` | Game delayed | +| `Canceled` | Game canceled | +| `Forfeit` | Game forfeited | + +### Soccer + +| Status | Description | +| ----------------- | ------------------------------------ | +| `Scheduled` | Game not yet started | +| `InProgress` | Game currently playing | +| `Break` | Halftime or other break | +| `Suspended` | Game suspended | +| `PenaltyShootout` | Penalty shootout in progress | +| `Final` | Game completed | +| `Awarded` | Result awarded due to ruling/forfeit | +| `Postponed` | Game postponed | +| `Canceled` | Game canceled | + +### Esports + +| Status | Description | +| ------------- | ----------------------- | +| `not_started` | Match not yet started | +| `running` | Match currently playing | +| `finished` | Match completed | +| `postponed` | Match postponed | +| `canceled` | Match canceled | + +### Tennis + +| Status | Description | +| ------------ | ----------------------- | +| `scheduled` | Match not yet started | +| `inprogress` | Match currently playing | +| `suspended` | Match suspended | +| `finished` | Match completed | +| `postponed` | Match postponed | +| `cancelled` | Match canceled | diff --git a/PolymarketDocumentation-main/docs/index.md b/PolymarketDocumentation-main/docs/index.md new file mode 100644 index 00000000..c4440b03 --- /dev/null +++ b/PolymarketDocumentation-main/docs/index.md @@ -0,0 +1,150 @@ +> ## Documentation Index +> Fetch the complete documentation index at: https://docs.polymarket.com/llms.txt +> Use this file to discover all available pages before exploring further. + +# Overview + +> Build on the world's largest prediction market. Trade, integrate, and access real-time market data with the Polymarket API. + +export const IconCard = ({ icon, title, description, href, color }) => { + return ( + +
+ +
+

+ {title} +

+

+ {description} +

+
+ ); +}; + + + 🇺🇸 + Looking for Polymarket US documentation? + Visit US Docs → + + + + + + +
+
+

+ Polymarket Documentation +

+ +
+ Build on the world's largest prediction market. APIs, SDKs, and tools for prediction market developers. +
+ +
+
+

+ Developer Quickstart +

+ +

+ Make your first API request in minutes. Learn the basics of the Polymarket platform, fetch market data, place orders, and redeem winning positions. +

+ + +
+ + + ```typescript TypeScript theme={null} + import { ClobClient, Side } from "@polymarket/clob-client-v2"; + + const client = new ClobClient({ host, chain: chainId, signer, creds }); + + const order = await client.createAndPostOrder( + { tokenID, price: 0.50, size: 10, side: Side.BUY }, + { tickSize: "0.01", negRisk: false } + ); + ``` + + ```python Python theme={null} + from py_clob_client_v2 import ClobClient, OrderArgs, PartialCreateOrderOptions + from py_clob_client_v2.order_builder.constants import BUY + + client = ClobClient(host, key=key, chain_id=chain, creds=creds) + order = client.create_and_post_order( + OrderArgs(token_id=token_id, price=0.50, size=10, side=BUY), + options=PartialCreateOrderOptions(tick_size="0.01", neg_risk=False) + ) + ``` + + ```rust Rust theme={null} + use polymarket_client_sdk_v2::clob::{Client, Config}; + use polymarket_client_sdk_v2::clob::types::Side; + use polymarket_client_sdk_v2::types::dec; + + let client = Client::new(host, Config::default())?.authentication_builder(&signer).authenticate().await?; + let order = client.limit_order().token_id(token_id).price(dec!(0.50)).size(dec!(10)).side(Side::Buy).build().await?; + let signed = client.sign(&signer, order).await?; + let response = client.post_order(signed).await?; + ``` + +
+
+ +
+

+ Get Familiar with Polymarket +

+ +

+ Learn the fundamentals, explore our APIs, and start building on the world's largest prediction market. +

+ +
+ + + Set up your environment and make your first API call in minutes. + + + + Understand markets, events, tokens, and how trading works. + + + + Explore REST endpoints, WebSocket streams, and authentication. + + + + Official Python, TypeScript, and Rust libraries for faster development. + + +
+ +
+ + Banner + +
+
+ +
+
+ + + + + +
+
+
diff --git a/PolymarketDocumentation-main/docs/market-data/fetching-markets.md b/PolymarketDocumentation-main/docs/market-data/fetching-markets.md new file mode 100644 index 00000000..92c50f3c --- /dev/null +++ b/PolymarketDocumentation-main/docs/market-data/fetching-markets.md @@ -0,0 +1,156 @@ +> ## Documentation Index +> Fetch the complete documentation index at: https://docs.polymarket.com/llms.txt +> Use this file to discover all available pages before exploring further. + +# Fetching Markets + +> Three strategies for discovering and querying markets + + + Both the events and markets endpoints are paginated. See + [pagination](#pagination) for details. + + +There are three main strategies for retrieving market data, each optimized for different use cases: + +1. **By Slug** — Best for fetching specific individual markets or events +2. **By Tags** — Ideal for filtering markets by category or sport +3. **Via Events Endpoint** — Most efficient for retrieving all active markets + +*** + +## Fetch by Slug + +**Use case:** When you need to retrieve a specific market or event that you already know about. + +Individual markets and events are best fetched using their unique slug identifier. The slug can be found directly in the Polymarket frontend URL. + +### How to Extract the Slug + +From any Polymarket URL, the slug is the path segment after `/event/`: + +``` +https://polymarket.com/event/fed-decision-in-october + ↑ + Slug: fed-decision-in-october +``` + +### Examples + +```bash theme={null} +# Fetch an event by slug (query parameter) +curl "https://gamma-api.polymarket.com/events?slug=fed-decision-in-october" + +# Or use the path endpoint +curl "https://gamma-api.polymarket.com/events/slug/fed-decision-in-october" +``` + +```bash theme={null} +# Fetch a market by slug (query parameter) +curl "https://gamma-api.polymarket.com/markets?slug=fed-decision-in-october" + +# Or use the path endpoint +curl "https://gamma-api.polymarket.com/markets/slug/fed-decision-in-october" +``` + +*** + +## Fetch by Tags + +**Use case:** When you want to filter markets by category, sport, or topic. + +Tags provide a way to categorize and filter markets. You can discover available tags and then use them to filter your requests. + +### Discover Available Tags + +**General tags:** `GET /tags` (Gamma API) + +**Sports tags and metadata:** `GET /sports` (Gamma API) + +The `/sports` endpoint returns metadata for sports including tag IDs, images, resolution sources, and series information. + +### Filter by Tag + +Once you have tag IDs, use the `tag_id` parameter in both events and markets endpoints: + +```bash theme={null} +# Fetch events for a specific tag +curl "https://gamma-api.polymarket.com/events?tag_id=100381&limit=10&active=true&closed=false" +``` + +### Additional Tag Filtering + +You can also: + +* Use `related_tags=true` to include related tag markets +* Exclude specific tags with `exclude_tag_id` + +```bash theme={null} +# Include related tags +curl "https://gamma-api.polymarket.com/events?tag_id=100381&related_tags=true&active=true&closed=false" +``` + +*** + +## Fetch All Active Markets + +**Use case:** When you need to retrieve all available active markets, typically for broader analysis or market discovery. + +The most efficient approach is to use the events endpoint with `active=true&closed=false`, as events contain their associated markets. + +```bash theme={null} +curl "https://gamma-api.polymarket.com/events?active=true&closed=false&limit=100" +``` + +### Key Parameters + +| Parameter | Description | +| ----------- | ---------------------------------------------------------------------------------------------------------------- | +| `order` | Field to order by (`volume_24hr`, `volume`, `liquidity`, `start_date`, `end_date`, `competitive`, `closed_time`) | +| `ascending` | Sort direction (`true` for ascending, `false` for descending). Default: `false` | +| `active` | Filter by active status (`true` for live tradable events) | +| `closed` | Filter by closed status. Default: `false` | +| `limit` | Results per page | +| `offset` | Number of results to skip for pagination | + +```bash theme={null} +# Get the highest volume active events +curl "https://gamma-api.polymarket.com/events?active=true&closed=false&order=volume_24hr&ascending=false&limit=100" +``` + +*** + +## Pagination + +All list endpoints return paginated responses with `limit` and `offset` parameters: + +```bash theme={null} +# Page 1: First 50 results +curl "https://gamma-api.polymarket.com/events?active=true&closed=false&limit=50&offset=0" + +# Page 2: Next 50 results +curl "https://gamma-api.polymarket.com/events?active=true&closed=false&limit=50&offset=50" + +# Page 3: Next 50 results +curl "https://gamma-api.polymarket.com/events?active=true&closed=false&limit=50&offset=100" +``` + +*** + +## Best Practices + +1. **For individual markets:** Use the slug method for direct lookups +2. **For category browsing:** Use tag filtering to reduce API calls +3. **For complete market discovery:** Use the events endpoint with pagination +4. **Always include `active=true`** when fetching live markets. The `closed` parameter now defaults to `false`, so closed markets are excluded automatically — pass `closed=true` only if you need historical data +5. **Use the events endpoint** and work backwards — events contain their associated markets, reducing the number of API calls needed + +*** + +## Next Steps + + + + Full endpoint documentation with parameters and response schemas. + + diff --git a/PolymarketDocumentation-main/docs/market-data/overview.md b/PolymarketDocumentation-main/docs/market-data/overview.md new file mode 100644 index 00000000..d2c61fe0 --- /dev/null +++ b/PolymarketDocumentation-main/docs/market-data/overview.md @@ -0,0 +1,111 @@ +> ## Documentation Index +> Fetch the complete documentation index at: https://docs.polymarket.com/llms.txt +> Use this file to discover all available pages before exploring further. + +# Overview + +> Fetch market data with no authentication required + +All market data is available through public REST endpoints. No API key, no authentication, no wallet required. + +```bash theme={null} +curl "https://gamma-api.polymarket.com/events?limit=5" +``` + +*** + +## Data Model + +Polymarket structures data using two organizational models. The most fundamental element is always markets—events simply provide additional organization. + + + + A top-level object representing a question (e.g., "Who will win the 2024 + Presidential Election?"). Contains one or more markets. + + + + A specific tradable binary outcome within an event. Maps to a pair of CLOB + token IDs, a market address, a question ID, and a condition ID. + + + +### Single-Market Events vs Multi-Market Events + +| Type | Example | +| ------------------- | ---------------------------------------------------------------------------------------------- | +| Single-market event | "Will Bitcoin reach \$100k?" → 1 market (Yes/No) | +| Multi-market event | "Where will Barron Trump attend College?" → Markets for Georgetown, NYU, UPenn, Harvard, Other | + +### Outcomes and Prices + +Each market has `outcomes` and `outcomePrices` arrays that map 1:1. Prices represent implied probabilities: + +```json theme={null} +{ + "outcomes": "[\"Yes\", \"No\"]", + "outcomePrices": "[\"0.20\", \"0.80\"]" +} +// Index 0: "Yes" → 0.20 (20% probability) +// Index 1: "No" → 0.80 (80% probability) +``` + +Markets can be traded via the CLOB if `enableOrderBook` is `true`. + +*** + +## Available Data + +Endpoints are split across three APIs. See the [API Reference](/api-reference/introduction) for full endpoint documentation with parameters and response schemas. + +### Gamma API - Events Markets and Discovery + +| Endpoint | Description | +| -------------------- | ------------------------------------------- | +| `GET /events` | List events with filtering and pagination | +| `GET /events/{id}` | Get a single event by ID | +| `GET /markets` | List markets with filtering and pagination | +| `GET /markets/{id}` | Get a single market by ID | +| `GET /public-search` | Search across events, markets, and profiles | +| `GET /tags` | Ranked tags/categories | +| `GET /series` | Series (grouped events) | +| `GET /sports` | Sports metadata | +| `GET /teams` | Teams | + +### CLOB API - Prices and Orderbooks + +| Endpoint | Description | +| --------------------- | --------------------------------- | +| `GET /price` | Price for a single token | +| `GET /prices` | Prices for multiple tokens | +| `GET /book` | Order book for a token | +| `POST /books` | Order books for multiple tokens | +| `GET /prices-history` | Historical price data for a token | +| `GET /midpoint` | Midpoint price for a token | +| `GET /spread` | Spread for a token | + +### Data API - Positions Trades and Analytics + +| Endpoint | Description | +| -------------------------------------- | ---------------------------- | +| `GET /positions?user={address}` | Current positions for a user | +| `GET /closed-positions?user={address}` | Closed positions for a user | +| `GET /activity?user={address}` | Onchain activity for a user | +| `GET /value?user={address}` | Total position value | +| `GET /oi` | Open interest for a market | +| `GET /holders` | Top holders of a market | +| `GET /trades` | Trade history | + +*** + +## Next Steps + + + + Three strategies for discovering and querying markets. + + + + Full endpoint documentation with parameters and response schemas. + + diff --git a/PolymarketDocumentation-main/docs/market-data/websocket/market-channel.md b/PolymarketDocumentation-main/docs/market-data/websocket/market-channel.md new file mode 100644 index 00000000..bd7708f3 --- /dev/null +++ b/PolymarketDocumentation-main/docs/market-data/websocket/market-channel.md @@ -0,0 +1,235 @@ +> ## Documentation Index +> Fetch the complete documentation index at: https://docs.polymarket.com/llms.txt +> Use this file to discover all available pages before exploring further. + +# Market Channel + +> Real-time orderbook, price, and trade data + +Public channel for market data updates (level 2 price data). Subscribe with asset IDs to receive orderbook snapshots, price changes, trade executions, and market events. + +## Endpoint + +``` +wss://ws-subscriptions-clob.polymarket.com/ws/market +``` + +## Subscription + +```json theme={null} +{ + "assets_ids": ["", ""], + "type": "market", + "custom_feature_enabled": true +} +``` + +Set `custom_feature_enabled: true` to receive `best_bid_ask`, `new_market`, and `market_resolved` events. + +## Message Types + +Each message includes an `event_type` field identifying the type. + +### book + +Emitted when first subscribed to a market and when there is a trade that affects the book. + +```json theme={null} +{ + "event_type": "book", + "asset_id": "65818619657568813474341868652308942079804919287380422192892211131408793125422", + "market": "0xbd31dc8a20211944f6b70f31557f1001557b59905b7738480ca09bd4532f84af", + "bids": [ + { "price": ".48", "size": "30" }, + { "price": ".49", "size": "20" }, + { "price": ".50", "size": "15" } + ], + "asks": [ + { "price": ".52", "size": "25" }, + { "price": ".53", "size": "60" }, + { "price": ".54", "size": "10" } + ], + "timestamp": "123456789000", + "hash": "0x0...." +} +``` + +### price\_change + +Emitted when a new order is placed or an order is cancelled. + +```json theme={null} +{ + "market": "0x5f65177b394277fd294cd75650044e32ba009a95022d88a0c1d565897d72f8f1", + "price_changes": [ + { + "asset_id": "71321045679252212594626385532706912750332728571942532289631379312455583992563", + "price": "0.5", + "size": "200", + "side": "BUY", + "hash": "56621a121a47ed9333273e21c83b660cff37ae50", + "best_bid": "0.5", + "best_ask": "1" + }, + { + "asset_id": "52114319501245915516055106046884209969926127482827954674443846427813813222426", + "price": "0.5", + "size": "200", + "side": "SELL", + "hash": "1895759e4df7a796bf4f1c5a5950b748306923e2", + "best_bid": "0", + "best_ask": "0.5" + } + ], + "timestamp": "1757908892351", + "event_type": "price_change" +} +``` + +A `size` of `"0"` means the price level has been removed from the book. + +### tick\_size\_change + +Emitted when the minimum tick size of a market changes. This happens when the book's price reaches the limits: price > 0.96 or price \< 0.04. + +```json theme={null} +{ + "event_type": "tick_size_change", + "asset_id": "65818619657568813474341868652308942079804919287380422192892211131408793125422", + "market": "0xbd31dc8a20211944f6b70f31557f1001557b59905b7738480ca09bd4532f84af", + "old_tick_size": "0.01", + "new_tick_size": "0.001", + "timestamp": "100000000" +} +``` + +### last\_trade\_price + +Emitted when a maker and taker order is matched, creating a trade event. + +```json theme={null} +{ + "asset_id": "114122071509644379678018727908709560226618148003371446110114509806601493071694", + "event_type": "last_trade_price", + "fee_rate_bps": "0", + "market": "0x6a67b9d828d53862160e470329ffea5246f338ecfffdf2cab45211ec578b0347", + "price": "0.456", + "side": "BUY", + "size": "219.217767", + "timestamp": "1750428146322" +} +``` + +### best\_bid\_ask + +Requires `custom_feature_enabled: true`. + +Emitted when the best bid or ask prices for a market change. + +```json theme={null} +{ + "event_type": "best_bid_ask", + "market": "0x0005c0d312de0be897668695bae9f32b624b4a1ae8b140c49f08447fcc74f442", + "asset_id": "85354956062430465315924116860125388538595433819574542752031640332592237464430", + "best_bid": "0.73", + "best_ask": "0.77", + "spread": "0.04", + "timestamp": "1766789469958" +} +``` + +### new\_market + +Requires `custom_feature_enabled: true`. + +Emitted when a new market is created. + +The payload also includes market metadata fields such as `tags`, +`condition_id`, `active`, `clob_token_ids`, `sports_market_type`, `line`, +`game_start_time`, `order_price_min_tick_size`, `group_item_title`, +`taker_base_fee`, `fees_enabled`, and `fee_schedule`. + +Where a `FeeSchedule` object is of the form: + +| Name | Type | Description | +| ------------ | ------- | --------------------------------- | +| exponent | string | fee curve exponent | +| rate | string | fee rate | +| taker\_only | boolean | whether fee applies to taker only | +| rebate\_rate | string | maker rebate rate | + +```json theme={null} +{ + "id": "1031769", + "question": "Will NVIDIA (NVDA) close above $240 end of January?", + "market": "0x311d0c4b6671ab54af4970c06fcf58662516f5168997bdda209ec3db5aa6b0c1", + "slug": "nvda-above-240-on-january-30-2026", + "description": "This market will resolve to \"Yes\" if the official closing price...", + "assets_ids": [ + "76043073756653678226373981964075571318267289248134717369284518995922789326425", + "31690934263385727664202099278545688007799199447969475608906331829650099442770" + ], + "outcomes": ["Yes", "No"], + "event_message": { + "id": "125819", + "ticker": "nvda-above-in-january-2026", + "slug": "nvda-above-in-january-2026", + "title": "Will NVIDIA (NVDA) close above ___ end of January?", + "description": "This market will resolve to \"Yes\" if the official closing price..." + }, + "timestamp": "1766790415550", + "event_type": "new_market", + "tags": ["stocks"], + "condition_id": "0x311d0c4b6671ab54af4970c06fcf58662516f5168997bdda209ec3db5aa6b0c1", + "active": true, + "clob_token_ids": [ + "76043073756653678226373981964075571318267289248134717369284518995922789326425", + "31690934263385727664202099278545688007799199447969475608906331829650099442770" + ], + "sports_market_type": "", + "line": "", + "game_start_time": "", + "order_price_min_tick_size": "0.01", + "group_item_title": "NVDA above $240", + "taker_base_fee": "0", + "fees_enabled": true, + "fee_schedule": { + "exponent": "2", + "rate": "0.02", + "taker_only": true, + "rebate_rate": "0" + } +} +``` + +### market\_resolved + +Requires `custom_feature_enabled: true`. + +Emitted when a market is resolved. + +```json theme={null} +{ + "id": "1031769", + "question": "Will NVIDIA (NVDA) close above $240 end of January?", + "market": "0x311d0c4b6671ab54af4970c06fcf58662516f5168997bdda209ec3db5aa6b0c1", + "slug": "nvda-above-240-on-january-30-2026", + "description": "This market will resolve to \"Yes\" if the official closing price...", + "assets_ids": [ + "76043073756653678226373981964075571318267289248134717369284518995922789326425", + "31690934263385727664202099278545688007799199447969475608906331829650099442770" + ], + "outcomes": ["Yes", "No"], + "winning_asset_id": "76043073756653678226373981964075571318267289248134717369284518995922789326425", + "winning_outcome": "Yes", + "event_message": { + "id": "125819", + "ticker": "nvda-above-in-january-2026", + "slug": "nvda-above-in-january-2026", + "title": "Will NVIDIA (NVDA) close above ___ end of January?", + "description": "This market will resolve to \"Yes\" if the official closing price..." + }, + "timestamp": "1766790415550", + "event_type": "market_resolved" +} +``` diff --git a/PolymarketDocumentation-main/docs/market-data/websocket/overview.md b/PolymarketDocumentation-main/docs/market-data/websocket/overview.md new file mode 100644 index 00000000..578a7d66 --- /dev/null +++ b/PolymarketDocumentation-main/docs/market-data/websocket/overview.md @@ -0,0 +1,181 @@ +> ## Documentation Index +> Fetch the complete documentation index at: https://docs.polymarket.com/llms.txt +> Use this file to discover all available pages before exploring further. + +# Overview + +> Real-time market data and trading updates via WebSocket + +Polymarket provides WebSocket channels for near real-time streaming of orderbook data, trades, and personal order activity. There are four available channels: `market`, `user`, `sports`, and `RTDS` (Real-Time Data Socket). + +## Channels + +| Channel | Endpoint | Auth | +| ----------------------------------- | ------------------------------------------------------ | -------- | +| Market | `wss://ws-subscriptions-clob.polymarket.com/ws/market` | No | +| User | `wss://ws-subscriptions-clob.polymarket.com/ws/user` | Yes | +| Sports | `wss://sports-api.polymarket.com/ws` | No | +| [RTDS](/market-data/websocket/rtds) | `wss://ws-live-data.polymarket.com` | Optional | + +### Market Channel + +| Type | Description | Custom Feature | +| ------------------ | ----------------------- | -------------- | +| `book` | Full orderbook snapshot | No | +| `price_change` | Price level updates | No | +| `tick_size_change` | Tick size changes | No | +| `last_trade_price` | Trade executions | No | +| `best_bid_ask` | Best prices update | Yes | +| `new_market` | New market created | Yes | +| `market_resolved` | Market resolution | Yes | + +Types marked "Custom Feature" require `custom_feature_enabled: true` in your subscription. + +### User Channel + +| Type | Description | +| ------- | --------------------------------------------- | +| `trade` | Trade lifecycle updates (MATCHED → CONFIRMED) | +| `order` | Order placements, updates, and cancellations | + +### Sports + +| Type | Description | +| -------------- | ------------------------------------- | +| `sport_result` | Live game scores, periods, and status | + +## Subscribing + +Send a subscription message after connecting to specify which data you want to receive. + +### Market Channel + +```json theme={null} +{ + "assets_ids": [ + "21742633143463906290569050155826241533067272736897614950488156847949938836455", + "48331043336612883890938759509493159234755048973500640148014422747788308965732" + ], + "type": "market", + "custom_feature_enabled": true +} +``` + +| Field | Type | Description | +| ------------------------ | --------- | ----------------------------------------------------------------- | +| `assets_ids` | string\[] | Token IDs to subscribe to | +| `type` | string | Channel identifier | +| `custom_feature_enabled` | boolean | Enable `best_bid_ask`, `new_market`, and `market_resolved` events | + +### User Channel + +```json theme={null} +{ + "auth": { + "apiKey": "your-api-key", + "secret": "your-api-secret", + "passphrase": "your-passphrase" + }, + "markets": ["0x1234...condition_id"], + "type": "user" +} +``` + + + The `auth` fields (`apiKey`, `secret`, `passphrase`) are **only required for + the user channel**. For the market channel, these fields are optional and can + be omitted. + + +| Field | Type | Description | +| --------- | --------- | -------------------------------------------------- | +| `auth` | object | API credentials (`apiKey`, `secret`, `passphrase`) | +| `markets` | string\[] | Condition IDs to receive events for | +| `type` | string | Channel identifier | + + + The user channel subscribes by **condition IDs** (market identifiers), not + asset IDs. Each market has one condition ID but two asset IDs (Yes and No + tokens). + + +### Sports Channel + +No subscription message required. Connect and start receiving data for all active sports events. + +## Dynamic Subscription + +Modify subscriptions without reconnecting. + +### Subscribe to more assets + +```json theme={null} +{ + "assets_ids": ["new_asset_id_1", "new_asset_id_2"], + "operation": "subscribe", + "custom_feature_enabled": true +} +``` + +### Unsubscribe from assets + +```json theme={null} +{ + "assets_ids": ["asset_id_to_remove"], + "operation": "unsubscribe" +} +``` + +For the user channel, use `markets` instead of `assets_ids`: + +```json theme={null} +{ + "markets": ["0x1234...condition_id"], + "operation": "subscribe" +} +``` + +## Heartbeats + +### Market and User Channels + +Send `PING` every 10 seconds. The server responds with `PONG`. + +``` +PING +``` + +### Sports Channel + +The server sends `ping` every 5 seconds. Respond with `pong` within 10 seconds. + +``` +pong +``` + + + If you don't respond to the server's ping within 10 seconds, the connection + will be closed. + + +## Troubleshooting + + + Send a valid subscription message immediately after connecting. The server may + close connections that don't subscribe within a timeout period. + + + + You're not sending heartbeats. Send `PING` every 10 seconds for market/user + channels, or respond to server `ping` with `pong` for the sports channel. + + + + 1. Verify your asset IDs or condition IDs are correct 2. Check that the + markets are active (not resolved) 3. Set `custom_feature_enabled: true` if + expecting `best_bid_ask`, `new_market`, or `market_resolved` events + + + + Verify your API credentials are correct and haven't expired. + diff --git a/PolymarketDocumentation-main/docs/market-data/websocket/rtds.md b/PolymarketDocumentation-main/docs/market-data/websocket/rtds.md new file mode 100644 index 00000000..0e274231 --- /dev/null +++ b/PolymarketDocumentation-main/docs/market-data/websocket/rtds.md @@ -0,0 +1,554 @@ +> ## Documentation Index +> Fetch the complete documentation index at: https://docs.polymarket.com/llms.txt +> Use this file to discover all available pages before exploring further. + +# Real-Time Data Socket + +> Stream comments, crypto prices, and equity prices via WebSocket + +The Polymarket Real-Time Data Socket (RTDS) is a WebSocket-based streaming service that provides real-time updates for **comments**, **crypto prices**, and **equity prices**. + + + Official RTDS TypeScript client (`real-time-data-client`). + + +## Endpoint + +``` +wss://ws-live-data.polymarket.com +``` + +Some user-specific streams may require `gamma_auth` with your wallet address. + +## Subscribing + +Send a JSON message to subscribe to data streams: + +```json theme={null} +{ + "action": "subscribe", + "subscriptions": [ + { + "topic": "topic_name", + "type": "message_type", + "filters": "optional_filter_string", + "gamma_auth": { + "address": "wallet_address" + } + } + ] +} +``` + +To unsubscribe, send the same structure with `"action": "unsubscribe"`. + +Subscriptions can be added, removed, and modified without disconnecting. Send `PING` messages every 5 seconds to maintain the connection. + +Only the subscription types documented below are supported. + +## Message Structure + +All messages follow this structure: + +```json theme={null} +{ + "topic": "string", + "type": "string", + "timestamp": "number", + "payload": "object" +} +``` + +| Field | Type | Description | +| ----------- | ------ | --------------------------------------------------------------------------- | +| `topic` | string | The subscription topic (e.g., `crypto_prices`, `equity_prices`, `comments`) | +| `type` | string | The message type/event (e.g., `update`, `reaction_created`) | +| `timestamp` | number | Unix timestamp in milliseconds when the message was sent | +| `payload` | object | Event-specific data object | + +## Crypto Prices + +Real-time cryptocurrency price data from two sources: **Binance** and **Chainlink**. No authentication required. + +### Binance Source + +Subscribe to all symbols: + +```json theme={null} +{ + "action": "subscribe", + "subscriptions": [ + { + "topic": "crypto_prices", + "type": "update" + } + ] +} +``` + +Subscribe to specific symbols with a comma-separated filter: + +```json theme={null} +{ + "action": "subscribe", + "subscriptions": [ + { + "topic": "crypto_prices", + "type": "update", + "filters": "solusdt,btcusdt,ethusdt" + } + ] +} +``` + +Symbols use lowercase concatenated format (e.g., `solusdt`, `btcusdt`). + +**Solana price update:** + +```json theme={null} +{ + "topic": "crypto_prices", + "type": "update", + "timestamp": 1753314064237, + "payload": { + "symbol": "solusdt", + "timestamp": 1753314064213, + "value": 189.55 + } +} +``` + +**Bitcoin price update:** + +```json theme={null} +{ + "topic": "crypto_prices", + "type": "update", + "timestamp": 1753314088421, + "payload": { + "symbol": "btcusdt", + "timestamp": 1753314088395, + "value": 67234.50 + } +} +``` + +### Chainlink Source + + + **Trading 15m Crypto Markets?** Get a sponsored Chainlink API key with onboarding support from Chainlink. Fill out [this form](https://pm-ds-request.streams.chain.link/). + + +Subscribe to all symbols: + +```json theme={null} +{ + "action": "subscribe", + "subscriptions": [ + { + "topic": "crypto_prices_chainlink", + "type": "*", + "filters": "" + } + ] +} +``` + +Subscribe to a specific symbol with a JSON filter: + +```json theme={null} +{ + "action": "subscribe", + "subscriptions": [ + { + "topic": "crypto_prices_chainlink", + "type": "*", + "filters": "{\"symbol\":\"eth/usd\"}" + } + ] +} +``` + +Symbols use slash-separated format (e.g., `eth/usd`, `btc/usd`). + +**Ethereum price update:** + +```json theme={null} +{ + "topic": "crypto_prices_chainlink", + "type": "update", + "timestamp": 1753314064237, + "payload": { + "symbol": "eth/usd", + "timestamp": 1753314064213, + "value": 3456.78 + } +} +``` + +**Bitcoin price update:** + +```json theme={null} +{ + "topic": "crypto_prices_chainlink", + "type": "update", + "timestamp": 1753314088421, + "payload": { + "symbol": "btc/usd", + "timestamp": 1753314088395, + "value": 67234.50 + } +} +``` + +### Price Payload Fields + +| Field | Type | Description | +| ----------- | ------ | -------------------------------------------------------------------------------------------------------------------------------------------------- | +| `symbol` | string | Trading pair symbol. **Binance**: lowercase concatenated (e.g., `solusdt`, `btcusdt`). **Chainlink**: slash-separated (e.g., `eth/usd`, `btc/usd`) | +| `timestamp` | number | When the price was recorded, in Unix milliseconds | +| `value` | number | Current price value in the quote currency | + +### Supported Symbols + +**Binance Source** — lowercase concatenated format: + +* `btcusdt` — Bitcoin to USDT +* `ethusdt` — Ethereum to USDT +* `solusdt` — Solana to USDT +* `xrpusdt` — XRP to USDT + +**Chainlink Source** — slash-separated format: + +* `btc/usd` — Bitcoin to USD +* `eth/usd` — Ethereum to USD +* `sol/usd` — Solana to USD +* `xrp/usd` — XRP to USD + +## Equity Prices + +Real-time price data for stocks, ETFs, forex pairs, precious metals, and commodities sourced from **Pyth Network**. No authentication required. + + + **Trading Equity Markets?** Get a Pyth Network data feed - first 30 days free, then \$99/month. [Subscribe here](https://buy.stripe.com/cNi8wPeiq76FgQrbsD4ZG09). + + +All asset classes stream through a single `equity_prices` topic. When you subscribe with a symbol filter, the server sends a historical snapshot (last 2 minutes of data), then continues streaming live updates. + +### Subscribe + +Subscribe to a specific symbol with a JSON filter: + +```json theme={null} +{ + "action": "subscribe", + "subscriptions": [ + { + "topic": "equity_prices", + "type": "update", + "filters": "{\"symbol\":\"AAPL\"}" + } + ] +} +``` + +Subscribe to multiple symbols across asset classes: + +```json theme={null} +{ + "action": "subscribe", + "subscriptions": [ + { "topic": "equity_prices", "type": "update", "filters": "{\"symbol\":\"AAPL\"}" }, + { "topic": "equity_prices", "type": "update", "filters": "{\"symbol\":\"EURUSD\"}" }, + { "topic": "equity_prices", "type": "update", "filters": "{\"symbol\":\"XAUUSD\"}" }, + { "topic": "equity_prices", "type": "update", "filters": "{\"symbol\":\"WTI\"}" } + ] +} +``` + +Use `type: "*"` to receive all message types (live updates and snapshots): + +```json theme={null} +{ + "action": "subscribe", + "subscriptions": [ + { + "topic": "equity_prices", + "type": "*", + "filters": "{\"symbol\":\"GOOGL\"}" + } + ] +} +``` + +Filter values are case-insensitive on subscribe, but the `symbol` field in payloads is always returned lowercase. + + + **Need the price-to-beat value?** Pass the market slug to the price-to-beat endpoint: + + `GET https://polymarket.com/api/equity/price-to-beat/{slug}` + + Example: `https://polymarket.com/api/equity/price-to-beat/wti-up-or-down-on-april-7-2026` + + +### Live Price Update + +**Apple stock update:** + +```json theme={null} +{ + "topic": "equity_prices", + "type": "update", + "timestamp": 1711382400000, + "payload": { + "symbol": "aapl", + "value": 198.45, + "full_accuracy_value": "198.4523", + "timestamp": 1711382400000, + "received_at": 1711382400005 + } +} +``` + +**Gold price update (market closed):** + +```json theme={null} +{ + "topic": "equity_prices", + "type": "update", + "timestamp": 1711400000000, + "payload": { + "symbol": "xauusd", + "value": 2175.30, + "full_accuracy_value": "2175.3012", + "timestamp": 1711399000000, + "received_at": 1711400000002, + "is_carried_forward": true + } +} +``` + +### Historical Snapshot + +On subscribe, the server delivers a backfill of the last 2 minutes of price data. Use the `type` field to distinguish: `"subscribe"` for the initial snapshot vs `"update"` for live ticks. + +```json theme={null} +{ + "topic": "equity_prices", + "type": "subscribe", + "timestamp": 1711382400000, + "payload": { + "symbol": "aapl", + "data": [ + { "timestamp": 1711382280000, "value": 198.30 }, + { "timestamp": 1711382281000, "value": 198.32 }, + { "timestamp": 1711382340000, "value": 198.41 } + ] + } +} +``` + +### Equity Price Payload Fields + +| Field | Type | Description | +| --------------------- | ------- | --------------------------------------------------------------------------------------------------------- | +| `symbol` | string | Lowercase symbol identifier (e.g., `aapl`, `eurusd`, `xauusd`) | +| `value` | number | Spot price as a float | +| `full_accuracy_value` | string | Full-precision price as a string | +| `timestamp` | number | Price measurement timestamp in Unix milliseconds | +| `received_at` | number | When the system received the price, in Unix milliseconds. Only present when non-zero. | +| `is_carried_forward` | boolean | `true` when the market session is closed and the value is the last known price. Only present when `true`. | + +### Supported Symbols + +**Stocks:** + +| Symbol | Name | +| ------- | -------------- | +| `AAPL` | Apple | +| `TSLA` | Tesla | +| `MSFT` | Microsoft | +| `GOOGL` | Alphabet | +| `AMZN` | Amazon | +| `META` | Meta Platforms | +| `NVDA` | NVIDIA | +| `NFLX` | Netflix | +| `PLTR` | Palantir | +| `OPEN` | Opendoor | +| `RKLB` | Rocket Lab | +| `ABNB` | Airbnb | +| `COIN` | Coinbase | +| `HOOD` | Robinhood | + +**ETFs:** + +| Symbol | Name | +| ------ | ------------------------------------ | +| `QQQ` | Invesco QQQ ETF | +| `SPY` | S\&P 500 ETF | +| `EWY` | iShares MSCI South Korea ETF | +| `VXX` | Barclays iPath Series B S\&P 500 VIX | + +**Forex:** + +| Symbol | Pair | +| -------- | ---------------------------- | +| `EURUSD` | Euro / US Dollar | +| `GBPUSD` | British Pound / US Dollar | +| `USDCAD` | US Dollar / Canadian Dollar | +| `USDJPY` | US Dollar / Japanese Yen | +| `USDKRW` | US Dollar / South Korean Won | + +**Precious Metals:** + +| Symbol | Name | +| -------- | ------ | +| `XAUUSD` | Gold | +| `XAGUSD` | Silver | + +**Commodities** (rolling front-month futures): + +| Symbol | Name | +| ------ | --------------- | +| `WTI` | Crude Oil (WTI) | +| `CC` | Cocoa | +| `NGD` | Natural Gas | + +### Market Hours + +When a market session is closed, the stream continues with the last known price and `is_carried_forward: true`. This lets you distinguish stale prices from live ticks. Update frequency is sub-second (up to 5 per second per feed) during market hours. + +## Comments + +Real-time comment events on the Polymarket platform, including new comments, replies, reactions, and removals. May require Gamma authentication for user-specific data. + +### Subscribe + +```json theme={null} +{ + "action": "subscribe", + "subscriptions": [ + { + "topic": "comments", + "type": "comment_created" + } + ] +} +``` + +### Message Types + +| Type | Description | +| ------------------ | ------------------------------------- | +| `comment_created` | A user creates a new comment or reply | +| `comment_removed` | A comment is removed or deleted | +| `reaction_created` | A user adds a reaction to a comment | +| `reaction_removed` | A reaction is removed from a comment | + +### comment\_created + +Emitted when a user posts a new comment or replies to an existing one. + +```json theme={null} +{ + "topic": "comments", + "type": "comment_created", + "timestamp": 1753454975808, + "payload": { + "body": "That's a good point about the definition.", + "createdAt": "2025-07-25T14:49:35.801298Z", + "id": "1763355", + "parentCommentID": "1763325", + "parentEntityID": 18396, + "parentEntityType": "Event", + "profile": { + "baseAddress": "0xce533188d53a16ed580fd5121dedf166d3482677", + "displayUsernamePublic": true, + "name": "salted.caramel", + "proxyWallet": "0x4ca749dcfa93c87e5ee23e2d21ff4422c7a4c1ee", + "pseudonym": "Adored-Disparity" + }, + "reactionCount": 0, + "replyAddress": "0x0bda5d16f76cd1d3485bcc7a44bc6fa7db004cdd", + "reportCount": 0, + "userAddress": "0xce533188d53a16ed580fd5121dedf166d3482677" + } +} +``` + +A reply to the above comment — note `parentCommentID` references the parent: + +```json theme={null} +{ + "topic": "comments", + "type": "comment_created", + "timestamp": 1753454985123, + "payload": { + "body": "I agree, the resolution criteria should be clearer.", + "createdAt": "2025-07-25T14:49:45.120000Z", + "id": "1763356", + "parentCommentID": "1763355", + "parentEntityID": 18396, + "parentEntityType": "Event", + "profile": { + "baseAddress": "0x1234567890abcdef1234567890abcdef12345678", + "displayUsernamePublic": true, + "name": "trader", + "proxyWallet": "0x9876543210fedcba9876543210fedcba98765432", + "pseudonym": "Bright-Analysis" + }, + "reactionCount": 0, + "replyAddress": "0x0bda5d16f76cd1d3485bcc7a44bc6fa7db004cdd", + "reportCount": 0, + "userAddress": "0x1234567890abcdef1234567890abcdef12345678" + } +} +``` + +### Comment Payload Fields + +| Field | Type | Description | +| ------------------ | ------ | ------------------------------------------------------------------------- | +| `body` | string | The text content of the comment | +| `createdAt` | string | ISO 8601 timestamp when the comment was created | +| `id` | string | Unique identifier for this comment | +| `parentCommentID` | string | ID of the parent comment if this is a reply (null for top-level comments) | +| `parentEntityID` | number | ID of the parent entity (event, market, etc.) | +| `parentEntityType` | string | Type of parent entity (`Event`, `Market`) | +| `profile` | object | Profile information of the comment author | +| `reactionCount` | number | Current number of reactions on this comment | +| `replyAddress` | string | Polygon address for replies (may differ from userAddress) | +| `reportCount` | number | Current number of reports on this comment | +| `userAddress` | string | Polygon address of the comment author | + +### Profile Object Fields + +| Field | Type | Description | +| ----------------------- | ------- | ------------------------------------------ | +| `baseAddress` | string | User profile address | +| `displayUsernamePublic` | boolean | Whether the username is displayed publicly | +| `name` | string | User's display name | +| `proxyWallet` | string | Proxy wallet address used for transactions | +| `pseudonym` | string | Generated pseudonym for the user | + +### Comment Hierarchy + +Comments support nested threading: + +* **Top-level comments**: `parentCommentID` is null or empty +* **Reply comments**: `parentCommentID` contains the ID of the parent comment +* All comments are associated with a `parentEntityID` and `parentEntityType` (`Event` or `Market`) + +## Troubleshooting + + + Send `PING` messages every 5 seconds to keep the connection alive. Connection errors will trigger automatic reconnection attempts. + + + + Verify your subscription message is valid JSON with the correct `action`, `topic`, and `type` fields. Invalid subscription messages may result in connection closure. + + + + If subscribing to user-specific streams, ensure your `gamma_auth` object includes a valid wallet `address`. Authentication failures will prevent subscription to protected topics. + diff --git a/PolymarketDocumentation-main/docs/market-data/websocket/sports.md b/PolymarketDocumentation-main/docs/market-data/websocket/sports.md new file mode 100644 index 00000000..2afd0dee --- /dev/null +++ b/PolymarketDocumentation-main/docs/market-data/websocket/sports.md @@ -0,0 +1,222 @@ +> ## Documentation Index +> Fetch the complete documentation index at: https://docs.polymarket.com/llms.txt +> Use this file to discover all available pages before exploring further. + +# Sports WebSocket + +> Live sports scores and game state + +The Sports WebSocket provides real-time sports results updates, including scores, periods, and game status. No authentication required. + + + This feed is provided for informational purposes only. It may be delayed, + contain errors, or omit recent events. Polymarket does not provide trading or + investment advice, and this content should not be used as the basis for any + trading decision. + + +## Endpoint + +``` +wss://sports-api.polymarket.com/ws +``` + +No subscription message required — connect and start receiving data for all active sports events. + +## Heartbeat + +The server sends `ping` every 5 seconds. Respond with `pong` within 10 seconds or the connection will close. + +```javascript theme={null} +ws.onmessage = (event) => { + if (event.data === "ping") { + ws.send("pong"); + return; + } + + // Handle JSON messages... +}; +``` + +## Message Type + +Each message is a JSON object with game state fields. + +### sport\_result + +Emitted when: + +* A match goes live +* The score changes +* The period changes (e.g., halftime, overtime) +* A match ends +* Possession changes (NFL and CFB only) + +**NFL (in progress):** + +```json theme={null} +{ + "gameId": 19439, + "leagueAbbreviation": "nfl", + "slug": "nfl-lac-buf-2025-01-26", + "homeTeam": "LAC", + "awayTeam": "BUF", + "status": "InProgress", + "score": "3-16", + "period": "Q4", + "elapsed": "5:18", + "live": true, + "ended": false, + "turn": "lac" +} +``` + +**Esports — CS2 (finished):** + +```json theme={null} +{ + "gameId": 1317359, + "leagueAbbreviation": "cs2", + "slug": "cs2-arcred-the-glecs-2025-07-20", + "homeTeam": "ARCRED", + "awayTeam": "The glecs", + "status": "finished", + "score": "000-000|2-0|Bo3", + "period": "2/3", + "live": false, + "ended": true, + "finished_timestamp": "2025-07-20T18:30:00.000Z" +} +``` + +The `finished_timestamp` field is an ISO 8601 timestamp only present when `ended: true`. + +The `slug` field follows the format `{league}-{team1}-{team2}-{date}` (e.g., `nfl-buf-kc-2025-01-26`). + +## Period Values + +| Period | Description | +| ---------------------- | --------------------------------------- | +| `1H` | First half | +| `2H` | Second half | +| `1Q`, `2Q`, `3Q`, `4Q` | Quarters (NFL, NBA) | +| `HT` | Halftime | +| `FT` | Full time (match ended in regulation) | +| `FT OT` | Full time with overtime | +| `FT NR` | Full time, no result (draw or canceled) | +| `End 1`, `End 2`, ... | End of inning (MLB) | +| `1/3`, `2/3`, `3/3` | Map number in Bo3 series (Esports) | +| `1/5`, `2/5`, ... | Map number in Bo5 series (Esports) | + +## Game Status Values + +Game status values vary by sport: + +### NFL + +| Status | Description | +| -------------- | ---------------------------- | +| `Scheduled` | Game not yet started | +| `InProgress` | Game currently playing | +| `Final` | Game completed in regulation | +| `F/OT` | Final after overtime | +| `Suspended` | Game suspended | +| `Postponed` | Game postponed | +| `Delayed` | Game delayed | +| `Canceled` | Game canceled | +| `Forfeit` | Game forfeited | +| `NotNecessary` | Scheduled, but not needed | + +### NHL + +| Status | Description | +| -------------- | ---------------------------- | +| `Scheduled` | Game not yet started | +| `InProgress` | Game currently playing | +| `Final` | Game completed in regulation | +| `F/OT` | Final after overtime | +| `F/SO` | Final after shootout | +| `Suspended` | Game suspended | +| `Postponed` | Game postponed | +| `Delayed` | Game delayed | +| `Canceled` | Game canceled | +| `Forfeit` | Game forfeited | +| `NotNecessary` | Scheduled, but not needed | + +### MLB + +| Status | Description | +| -------------- | ------------------------- | +| `Scheduled` | Game not yet started | +| `InProgress` | Game currently playing | +| `Final` | Game completed | +| `Suspended` | Game suspended | +| `Delayed` | Game delayed | +| `Postponed` | Game postponed | +| `Canceled` | Game canceled | +| `Forfeit` | Game forfeited | +| `NotNecessary` | Scheduled, but not needed | + +### NBA and CBB + +| Status | Description | +| -------------- | ------------------------- | +| `Scheduled` | Game not yet started | +| `InProgress` | Game currently playing | +| `Final` | Game completed | +| `F/OT` | Final after overtime | +| `Suspended` | Game suspended | +| `Postponed` | Game postponed | +| `Delayed` | Game delayed | +| `Canceled` | Game canceled | +| `Forfeit` | Game forfeited | +| `NotNecessary` | Scheduled, but not needed | + +### CFB + +| Status | Description | +| ------------ | ---------------------- | +| `Scheduled` | Game not yet started | +| `InProgress` | Game currently playing | +| `Final` | Game completed | +| `F/OT` | Final after overtime | +| `Suspended` | Game suspended | +| `Postponed` | Game postponed | +| `Delayed` | Game delayed | +| `Canceled` | Game canceled | +| `Forfeit` | Game forfeited | + +### Soccer + +| Status | Description | +| ----------------- | ------------------------------------ | +| `Scheduled` | Game not yet started | +| `InProgress` | Game currently playing | +| `Break` | Halftime or other break | +| `Suspended` | Game suspended | +| `PenaltyShootout` | Penalty shootout in progress | +| `Final` | Game completed | +| `Awarded` | Result awarded due to ruling/forfeit | +| `Postponed` | Game postponed | +| `Canceled` | Game canceled | + +### Esports + +| Status | Description | +| ------------- | ----------------------- | +| `not_started` | Match not yet started | +| `running` | Match currently playing | +| `finished` | Match completed | +| `postponed` | Match postponed | +| `canceled` | Match canceled | + +### Tennis + +| Status | Description | +| ------------ | ----------------------- | +| `scheduled` | Match not yet started | +| `inprogress` | Match currently playing | +| `suspended` | Match suspended | +| `finished` | Match completed | +| `postponed` | Match postponed | +| `cancelled` | Match canceled | diff --git a/PolymarketDocumentation-main/docs/market-data/websocket/user-channel.md b/PolymarketDocumentation-main/docs/market-data/websocket/user-channel.md new file mode 100644 index 00000000..8e8fff43 --- /dev/null +++ b/PolymarketDocumentation-main/docs/market-data/websocket/user-channel.md @@ -0,0 +1,124 @@ +> ## Documentation Index +> Fetch the complete documentation index at: https://docs.polymarket.com/llms.txt +> Use this file to discover all available pages before exploring further. + +# User Channel + +> Authenticated order and trade updates + +Authenticated channel for updates related to your orders and trades, filtered by API key. + +## Endpoint + +``` +wss://ws-subscriptions-clob.polymarket.com/ws/user +``` + +## Authentication + +Include API credentials in your subscription message: + +```json theme={null} +{ + "auth": { + "apiKey": "your-api-key", + "secret": "your-api-secret", + "passphrase": "your-passphrase" + }, + "markets": ["0x1234...condition_id"], + "type": "user" +} +``` + + + Never expose your API credentials in client-side code. Use the user channel + only from server environments. + + +## Message Types + +Each message includes a `type` field identifying the event. + +### trade + +Emitted when: + +* A market order is matched (`MATCHED`) +* A limit order for the user is included in a trade (`MATCHED`) +* Subsequent status changes for the trade (`MINED`, `CONFIRMED`, `RETRYING`, `FAILED`) + +```json theme={null} +{ + "asset_id": "52114319501245915516055106046884209969926127482827954674443846427813813222426", + "event_type": "trade", + "id": "28c4d2eb-bbea-40e7-a9f0-b2fdb56b2c2e", + "last_update": "1672290701", + "maker_orders": [ + { + "asset_id": "52114319501245915516055106046884209969926127482827954674443846427813813222426", + "matched_amount": "10", + "order_id": "0xff354cd7ca7539dfa9c28d90943ab5779a4eac34b9b37a757d7b32bdfb11790b", + "outcome": "YES", + "owner": "9180014b-33c8-9240-a14b-bdca11c0a465", + "price": "0.57" + } + ], + "market": "0xbd31dc8a20211944f6b70f31557f1001557b59905b7738480ca09bd4532f84af", + "match_time": "1672290701", + "outcome": "YES", + "owner": "9180014b-33c8-9240-a14b-bdca11c0a465", + "price": "0.57", + "side": "BUY", + "size": "10", + "status": "MATCHED", + "taker_order_id": "0x06bc63e346ed4ceddce9efd6b3af37c8f8f440c92fe7da6b2d0f9e4ccbc50c42", + "timestamp": "1672290701", + "trade_owner": "9180014b-33c8-9240-a14b-bdca11c0a465", + "type": "TRADE" +} +``` + +#### Trade Statuses + +``` +MATCHED → MINED → CONFIRMED + ↓ ↑ +RETRYING ───┘ + ↓ + FAILED +``` + +| Status | Terminal | Description | +| ----------- | -------- | ----------------------------------------------------------------------------------------------- | +| `MATCHED` | No | Trade has been matched and sent to the executor service by the operator | +| `MINED` | No | Trade observed to be mined into the chain, no finality threshold established | +| `CONFIRMED` | Yes | Trade has achieved strong probabilistic finality and was successful | +| `RETRYING` | No | Trade transaction has failed (revert or reorg) and is being retried/resubmitted by the operator | +| `FAILED` | Yes | Trade has failed and is not being retried | + +### order + +Emitted when: + +* An order is placed (`PLACEMENT`) +* An order is updated — some of it is matched (`UPDATE`) +* An order is cancelled (`CANCELLATION`) + +```json theme={null} +{ + "asset_id": "52114319501245915516055106046884209969926127482827954674443846427813813222426", + "associate_trades": null, + "event_type": "order", + "id": "0xff354cd7ca7539dfa9c28d90943ab5779a4eac34b9b37a757d7b32bdfb11790b", + "market": "0xbd31dc8a20211944f6b70f31557f1001557b59905b7738480ca09bd4532f84af", + "order_owner": "9180014b-33c8-9240-a14b-bdca11c0a465", + "original_size": "10", + "outcome": "YES", + "owner": "9180014b-33c8-9240-a14b-bdca11c0a465", + "price": "0.57", + "side": "SELL", + "size_matched": "0", + "timestamp": "1672290687", + "type": "PLACEMENT" +} +``` diff --git a/PolymarketDocumentation-main/docs/market-makers/combos.md b/PolymarketDocumentation-main/docs/market-makers/combos.md new file mode 100644 index 00000000..0a7fa6af --- /dev/null +++ b/PolymarketDocumentation-main/docs/market-makers/combos.md @@ -0,0 +1,4038 @@ +> ## Documentation Index +> Fetch the complete documentation index at: https://docs.polymarket.com/llms.txt +> Use this file to discover all available pages before exploring further. + +# Combos + +> Build a market maker integration for pricing and executing Combos + +Combos are multi-leg positions that combine multiple underlying market outcomes +into one YES or NO position. Each Combo is defined by its legs and identified by +derived YES and NO position IDs. + +The request for quote (RFQ) system enables quote-based Combo execution between +two participants: Polymarket users (requesters) and market makers (quoters). A +user creates a Request, which starts an auction among connected market makers. +Market makers compete by submitting Quotes: executable prices they are willing to +fill. + +```mermaid theme={null} +sequenceDiagram + autonumber + participant Requester as Polymarket User + participant RFQ as RFQ System + participant Quoter as Market Maker + participant Execution as Execution + + Requester->>RFQ: Request a Combo price + RFQ->>Quoter: Send quote request + activate Quoter + Note right of Quoter: 400 ms max + Quoter->>RFQ: Submit executable price + deactivate Quoter + RFQ->>Requester: Return best quote + activate Requester + Note left of Requester: 10 seconds max + Requester->>RFQ: Accept quote + deactivate Requester + opt Last Look enabled + RFQ->>Quoter: Request Last Look confirmation + activate Quoter + Note right of Quoter: 1 second max + Quoter->>RFQ: Confirm fill + deactivate Quoter + end + RFQ->>Execution: Execute accepted Combo + Execution-->>Requester: Send execution update + Execution-->>Quoter: Send execution update + RFQ-->>Quoter: Broadcast confirmed trade +``` + +1. **User creates an unsigned Request** for a Combo price. +2. **RFQ system sends the Request** to connected market makers. +3. **Market makers submit signed Quotes** within the 400 ms submission window. +4. **RFQ system returns the best Quote** to the user. +5. **User accepts the Quote** by signing the trade within the 10-second + acceptance window. +6. **RFQ system requests Last Look confirmation** when Last Look is enabled. +7. **Market maker confirms or declines** within the 1-second confirmation window. +8. **RFQ system executes the accepted Combo**. +9. **User receives execution updates**. +10. **Market maker receives execution updates**. +11. **Connected market makers receive confirmed trade broadcasts**. + + + Combo position IDs are complementary to CLOB token IDs. A user can trade the + market on the CLOB or can include the market as a leg of a Combo. + + +This guide shows market makers how to handle Combo RFQs. You will open a quoting +session, respond to incoming requests, cancel submitted quotes when needed, +confirm fills through Last Look, and monitor execution updates. + + + For development updates on market making for Combos, join the [Combos market + maker Telegram group](https://t.me/+eyMtdtKasWZjYTMx). + + +## Start Quoting + +Start by preparing an authenticated quoting session with the RFQ system. You +need a Polymarket account; create one at [polymarket.com](https://polymarket.com). + + + + + + Install the Unified TypeScript SDK with the package manager of your choice. + + + ```bash pnpm theme={null} + pnpm add @polymarket/client@beta viem + ``` + + ```bash npm theme={null} + npm install @polymarket/client@beta viem + ``` + + ```bash yarn theme={null} + yarn add @polymarket/client@beta viem + ``` + + + + This page uses Viem for wallet signing. See the [TypeScript tooling + guide](/dev-tooling/typescript#wallet-integrations) for other wallet library + integrations. + + + + + Create an instance of `SecureClient` with a wallet that has funds for fulfilling + user requests and its signer details. + + ```ts theme={null} + import { createSecureClient, relayerApiKey } from "@polymarket/client"; + import { privateKey } from "@polymarket/client/viem"; + + const client = await createSecureClient({ + wallet: process.env.POLYMARKET_WALLET_ADDRESS!, + signer: privateKey(process.env.PRIVATE_KEY!), + apiKey: relayerApiKey({ + key: process.env.RELAYER_API_KEY!, + address: process.env.RELAYER_API_KEY_ADDRESS!, + }), + }); + ``` + + The Relayer API key is necessary for setting up trading approvals in the next + step. Create a [Relayer API key](https://polymarket.com/settings?tab=api-keys) + from polymarket.com → Settings → API Keys. + + + + Set up the approvals required to fill user requests. + + ```ts theme={null} + await client.setupTradingApprovals(); + ``` + + + + Open the RFQ session. + + ```ts theme={null} + const session = await client.openRfqSession(); + + for await (const event of session) { + // event: RfqEvent + } + ``` + + + + You can close the session at any time by calling `session.close()`. + + ```ts theme={null} + for await (const event of session) { + if (shouldCloseSession) { + await session.close(); + break; + } + + // … + } + ``` + + + + + + + + Install the Python SDK with the package manager of your choice. + + + ```bash uv theme={null} + uv add polymarket-client + ``` + + ```bash pip theme={null} + pip install polymarket-client + ``` + + ```bash poetry theme={null} + poetry add polymarket-client + ``` + + + + + Create an `AsyncSecureClient` with a wallet that has funds for fulfilling user + requests and its signer details. + + ```python theme={null} + import os + + from polymarket import AsyncSecureClient, RelayerApiKey + + + client = await AsyncSecureClient.create( + private_key=os.environ["PRIVATE_KEY"], + wallet=os.environ["POLYMARKET_WALLET_ADDRESS"], + api_key=RelayerApiKey( + key=os.environ["RELAYER_API_KEY"], + address=os.environ["RELAYER_API_KEY_ADDRESS"], + ), + ) + ``` + + The Relayer API key is necessary for setting up trading approvals in the next + step. Create a [Relayer API key](https://polymarket.com/settings?tab=api-keys) + from polymarket.com → Settings → API Keys. + + + + Set up the approvals required to fill user requests. + + ```python theme={null} + await client.setup_trading_approvals() + ``` + + + + Open the RFQ session. + + ```python theme={null} + async with client.open_rfq_session() as session: + async for event in session: + # event: RfqEvent + ... + ``` + + + + You can close the session at any time by calling `await session.close()`. + + ```python theme={null} + async with client.open_rfq_session() as session: + async for event in session: + if should_close_session: + await session.close() + break + + ... + ``` + + + + + + + Use Polygon mainnet chain ID `137` for CLOB authentication and Exchange v3 + order signing. + + + + + Connect to the RFQ system WebSocket. + + ```text theme={null} + wss://combos-rfq-gateway-quoter.polymarket.com/ws/rfq + ``` + + To inspect the stream before integrating: + + ```bash theme={null} + wscat -c "wss://combos-rfq-gateway-quoter.polymarket.com/ws/rfq" + ``` + + Some write operations are also available through the REST API. + + ```text theme={null} + https://combos-rfq-api.polymarket.com + ``` + + + + RFQ WebSocket authentication uses CLOB API credentials: API key, secret, and + passphrase. If you need credentials, start with [Getting API + Credentials](/api-reference/authentication#using-the-rest-api). + + + + Resolve the order signer identity before sending `auth`. The RFQ system needs + the address that signs the order, the wallet that funds the order, and the + signature type that connects those two addresses. + + | Wallet Type | `signature_type` | `signer_address` | `maker_address` | + | -------------- | ---------------- | ----------------------------- | -------------------- | + | Deposit Wallet | `3` POLY\_1271 | Deposit wallet address | Deposit wallet | + | Safe Wallet | `2` Safe | Authenticated signing address | Derived Safe wallet | + | Poly Proxy | `1` Proxy | Authenticated signing address | Derived proxy wallet | + | EOA | `0` EOA | EOA address | Same EOA address | + + For more detail, see [Signature Types and + Funder](/api-reference/authentication#signature-types-and-funder). + + + + Send `auth` as the first WebSocket message within 30 seconds. Include the CLOB + credentials and the `signer_address`, `maker_address`, and `signature_type` + values resolved in the previous step. This example uses a Deposit Wallet. + + ```json theme={null} + { + "type": "auth", + "auth": { + "apiKey": "YOUR_API_KEY", + "secret": "YOUR_API_SECRET", + "passphrase": "YOUR_API_PASSPHRASE" + }, + "identity": { + "signer_address": "", + "maker_address": "", + "signature_type": 3 // + } + } + ``` + + Authentication returns a success or failure response. + + + ```json Success theme={null} + { + "type": "auth", + "success": true, + "address": "0xAuthenticatedAddress", + "role": "maker" + } + ``` + + ```json Failure theme={null} + { + "type": "auth", + "success": false, + "error": "unauthenticated" + } + ``` + + + + The RFQ system uses WebSocket protocol heartbeat frames to keep the connection + alive. It sends a ping frame every 30 seconds with payload `rfq`; your client + must respond with a pong frame that echoes the same payload. Most WebSocket + clients handle this automatically. These are protocol frames, not JSON + messages in the RFQ event stream. The gateway closes stale connections after 2 + minutes without an inbound message or pong. + + + + + Before posting quotes, `maker_address` must approve the contracts that may + transfer assets during RFQ execution. + + | Approval | Required when | Contract call | + | --------------------------- | --------------------------------------------- | ------------------------------------------------------- | + | pUSD collateral | The quoted order transfers pUSD | `CollateralToken.approve(ExchangeV3, maxUint256)` | + | Combo positions | The quoted order transfers Combo positions | `PositionManager.setApprovalForAll(ExchangeV3, true)` | + | AutoRedeemer Combo operator | You want automatic redemption flows to use it | `PositionManager.setApprovalForAll(AutoRedeemer, true)` | + + Use these contract addresses to build the approval calls. + + | Contract | Address | + | --------------------- | -------------------------------------------- | + | pUSD collateral token | `0xC011a7E12a19f7B1f670d46F03B03f3342E82DFB` | + | Exchange v3 | `0xe3333700cA9d93003F00f0F71f8515005F6c00Aa` | + | PositionManager | `0x006F54F7f9A22e0000CC2AB60031000000ae9fEF` | + | AutoRedeemer | `0xa1200000d0002264C9a1698e001292D00E1b00af` | + + + The following steps show the Deposit Wallet + [batch](/trading/deposit-wallets#submit-a-deposit-wallet-batch) path. If you + are trading with an EOA, submit the approvals directly from `maker_address`. + For Safe or Poly Proxy wallet flows, use an SDK. + + + + + Encode the approval calls that are not already in place. + + + ```solidity ERC-20 Approval theme={null} + function approve(address spender, uint256 amount) returns (bool); + ``` + + ```solidity ERC-1155 Approval theme={null} + function setApprovalForAll(address operator, bool approved); + ``` + + + Build a relayer call list from the encoded calldata. + + ```json theme={null} + [ + { + "target": "0xC011a7E12a19f7B1f670d46F03B03f3342E82DFB", + "value": "0", + "data": "" + }, + { + "target": "0x006F54F7f9A22e0000CC2AB60031000000ae9fEF", + "value": "0", + "data": "" + }, + { + "target": "0x006F54F7f9A22e0000CC2AB60031000000ae9fEF", + "value": "0", + "data": "" + } + ] + ``` + + + + Fetch a fresh `WALLET` nonce before signing the batch. + + ```bash theme={null} + curl -G "https://relayer-v2.polymarket.com/v1/account/transactions/params" \ + -H "RELAYER_API_KEY: $RELAYER_API_KEY" \ + -H "RELAYER_API_KEY_ADDRESS: $RELAYER_API_KEY_ADDRESS" \ + --data-urlencode "address=$RELAYER_API_KEY_ADDRESS" \ + --data-urlencode "type=WALLET" + ``` + + The response includes the nonce to sign with the transaction. + + ```json theme={null} + { + "address": "", + "nonce": "" + } + ``` + + + + Build and sign a Deposit Wallet `Batch` with the owner. Use the approval calls + from the call-list step as `calls`. + + ```json EIP-712 Batch theme={null} + { + "domain": { + "name": "DepositWallet", + "version": "1", + "chainId": 137, + "verifyingContract": "" + }, + "types": { + "Call": [ + { "name": "target", "type": "address" }, + { "name": "value", "type": "uint256" }, + { "name": "data", "type": "bytes" } + ], + "Batch": [ + { "name": "wallet", "type": "address" }, + { "name": "nonce", "type": "uint256" }, + { "name": "deadline", "type": "uint256" }, + { "name": "calls", "type": "Call[]" } + ] + }, + "primaryType": "Batch", + "message": { + "wallet": "", + "nonce": "", + "deadline": "", + "calls": [ + { + "target": "0xC011a7E12a19f7B1f670d46F03B03f3342E82DFB", + "value": "0", + "data": "" + } + ] + } + } + ``` + + Submit the signed batch to the relayer. + + ```bash theme={null} + curl -X POST "https://relayer-v2.polymarket.com/submit" \ + -H "Content-Type: application/json" \ + -H "RELAYER_API_KEY: $RELAYER_API_KEY" \ + -H "RELAYER_API_KEY_ADDRESS: $RELAYER_API_KEY_ADDRESS" \ + -d '{ + "type": "WALLET", + "from": "", + "to": "0x00000000000Fb5C9ADea0298D729A0CB3823Cc07", + "nonce": "", + "signature": "", + "metadata": "Approve Combo RFQ contracts", + "depositWalletParams": { + "depositWallet": "", + "deadline": "", + "calls": [ + { + "target": "0xC011a7E12a19f7B1f670d46F03B03f3342E82DFB", + "value": "0", + "data": "" + } + ] + } + }' + ``` + + The response includes the relayer transaction ID. + + ```json theme={null} + { + "transactionID": "", + "state": "STATE_NEW" + } + ``` + + + + Poll the relayer transaction until it reaches `STATE_CONFIRMED` before posting + quotes that rely on those approvals. + + ```bash theme={null} + curl "https://relayer-v2.polymarket.com/v1/account/transactions/" \ + -H "RELAYER_API_KEY: $RELAYER_API_KEY" \ + -H "RELAYER_API_KEY_ADDRESS: $RELAYER_API_KEY_ADDRESS" + ``` + + ```json theme={null} + { + "transaction_id": "", + "transaction_hash": "", + "state": "STATE_CONFIRMED", + "error_msg": null + } + ``` + + Treat `STATE_FAILED` and `STATE_INVALID` as terminal failures. + + + + + +## Handle Quote Requests + +Quote requests describe a user's intent to buy or sell shares in a Combo defined +by a given set of legs. A quote request can currently only buy or sell the YES +side of a Combo. + +The following cases show how a market maker can satisfy a user's buy or sell +request using collateral or inventory. + +| Quote Request | Using Collateral | From Inventory | +| ------------- | --------------------- | ---------------------- | +| Buy YES | Buy NO at `1 - price` | Sell YES at `price` | +| Sell YES | Buy YES at `price` | Sell NO at `1 - price` | + +See [Combinatorial Positions](/trading/ctf/combinatorial) for more detail on the +YES/NO position model. + +The diagram below shows the maker-side quote lifecycle, from receiving a quote +request through its terminal outcome. + +```mermaid theme={null} +flowchart TD + A[Receive request] --> B[Send quote] + B --> C[Active quote] + C --> D[Canceled] + C --> E[Selected] + E --> F{Last Look?} + F -->|No| G[Execution] + + subgraph lastLook["Last Look"] + F -->|Yes| H[Review fill] + H --> I[Confirm] + H --> J[Decline] + H --> K[Timeout] + end + + I --> G + G --> L[Confirmed] + G --> M[Failed] + + style lastLook fill:#165DFC14,stroke:#165DFC66,stroke-width:1px +``` + +### Authorize the Quote + +Authorize each quote by pricing the request and returning a signed order to the +RFQ system. Quoters should respond within the **400 ms** submission window. + + + + + + First, switch on `event.type` to handle quote requests from the session stream. + + ```ts theme={null} + switch (event.type) { + case "quote_request": + // event: RfqQuoteRequestEvent + void handleQuoteRequest(event); + break; + + // … + } + ``` + + + + Then, inspect the `RfqQuoteRequestEvent` before pricing it. + + | Field | Type | Description | + | -------------------- | ---------------------- | ------------------------------------------ | + | `rfqId` | `RfqId` | RFQ identifier used to correlate responses | + | `requestorPublicId` | `RfqRequestorPublicId` | Public identifier for the user request | + | `conditionId` | `ComboConditionId` | Derived Combo condition ID | + | `direction` | `RfqDirection` | Whether the user wants to buy or sell | + | `side` | `RfqSide.Yes` | Currently always `RfqSide.Yes` | + | `requestedSize` | `RfqRequestedSize` | User-requested notional or share size | + | `yesPositionId` | `PositionId` | Derived YES Combo position ID | + | `noPositionId` | `PositionId` | Derived NO Combo position ID | + | `legPositionIds` | `PositionId[]` | Underlying leg position IDs | + | `submissionDeadline` | `EpochMilliseconds` | Unix-millisecond quote submission deadline | + + `requestedSize` is an `RfqRequestedSize` value that describes how the user sized + the request. + + ```ts theme={null} + type RfqRequestedSize = + | { + unit: RfqRequestedSizeUnit.Notional; + value: DecimalString; + } + | { + unit: RfqRequestedSizeUnit.Shares; + value: DecimalString; + }; + ``` + + Where: + + * `notional`: the target value of the request in collateral currency. For + example, `"3"` means the user wants roughly 3 pUSD worth of the Combo, with the + resulting share size derived from the quote price. `notional` is always and only used by BUY requests. + * `shares`: the target number of Combo outcome tokens. For example, `"10"` means + the user wants 10 shares, or 10,000,000 base units. `shares` is always and only used by SELL requests. + + In both cases, `value` is a normalized decimal string. + + + + Finally, handle pricing, quote submission, and persistence outside the session + loop before the `event.submissionDeadline` deadline. Price the request as pUSD + per YES Combo share; for example, `0.45` means `0.45` pUSD per share. If you do + not want to quote the request, skip submission. + + ```ts theme={null} + async function handleQuoteRequest(event: RfqQuoteRequestEvent) { + const price = priceComboRequest(event); + + if (price === undefined) return; + + const reference = await event.quote({ price }); + + storeQuoteReference(reference); + } + ``` + + + + + + + + First, use `isinstance(...)` to handle quote requests from the session stream. + + ```python theme={null} + from polymarket import RfqQuoteRequestEvent + + + async for event in session: + if isinstance(event, RfqQuoteRequestEvent): + await handle_quote_request(event) + ``` + + + + Then, inspect the `RfqQuoteRequestEvent` before pricing it. + + | Field | Type | Description | + | --------------------- | ------------------------ | ------------------------------------------ | + | `rfq_id` | `RfqId` | RFQ identifier used to correlate responses | + | `requestor_public_id` | `RfqRequestorPublicId` | Public identifier for the user request | + | `condition_id` | `ComboConditionId` | Derived Combo condition ID | + | `direction` | `RfqDirection` | Whether the user wants to buy or sell | + | `side` | `RfqSide` | Currently always `RfqSide.YES` | + | `requested_size` | `RfqRequestedSize` | User-requested notional or share size | + | `yes_position_id` | `PositionId` | Derived YES Combo position ID | + | `no_position_id` | `PositionId` | Derived NO Combo position ID | + | `leg_position_ids` | `tuple[PositionId, ...]` | Underlying leg position IDs | + | `submission_deadline` | `int` | Unix-millisecond quote submission deadline | + + `requested_size` is an `RfqRequestedSize` value that describes how the user sized + the request. + + ```python theme={null} + from dataclasses import dataclass + from decimal import Decimal + + from polymarket import RfqRequestedSizeUnit + + + @dataclass(frozen=True, slots=True, kw_only=True) + class RfqRequestedSize: + unit: RfqRequestedSizeUnit + value: Decimal + ``` + + Where: + + * `RfqRequestedSizeUnit.NOTIONAL`: the target value of the request in collateral + currency. For example, `Decimal("3")` means the user wants roughly 3 pUSD worth + of the Combo, with the resulting share size derived from the quote price. + BUY RFQs will always use `NOTIONAL`. + * `RfqRequestedSizeUnit.SHARES`: the target number of Combo outcome tokens. For + example, `Decimal("10")` means the user wants 10 shares, or 10,000,000 base + units. SELL RFQs will always use `SHARES`. + + In both cases, `value` is a `Decimal`. + + + + Finally, handle pricing, quote submission, and persistence outside the session + loop before the `event.submission_deadline` deadline. Price the request as pUSD + per YES Combo share; for example, `Decimal("0.45")` means `0.45` pUSD per share. + If you do not want to quote the request, skip submission. + + ```python theme={null} + from decimal import Decimal + + from polymarket import RfqQuoteRequestEvent + + + async def handle_quote_request(event: RfqQuoteRequestEvent) -> None: + price = price_combo_request(event) + + if price is None: + return + + reference = await event.quote(price=price) + + store_quote_reference(reference) + ``` + + + + + + + + The RFQ system sends `RFQ_REQUEST` messages over the authenticated WebSocket. + Inspect the request before pricing it. + + + ```json Notional Request theme={null} + { + "type": "RFQ_REQUEST", + "rfq_id": "", + "requestor_public_id": "", + "leg_position_ids": ["", ""], + "condition_id": "", + "yes_position_id": "", + "no_position_id": "", + "direction": "BUY", + "side": "YES", + "requested_size": { + "unit": "notional", + "value_e6": "1000000" + }, + "submission_deadline": "" + } + ``` + + ```json Shares Request theme={null} + { + "type": "RFQ_REQUEST", + "rfq_id": "", + "requestor_public_id": "", + "leg_position_ids": ["", ""], + "condition_id": "", + "yes_position_id": "", + "no_position_id": "", + "direction": "SELL", + "side": "YES", + "requested_size": { + "unit": "shares", + "value_e6": "1000000" + }, + "submission_deadline": "" + } + ``` + + + A `BUY` request always uses `notional` sizing, which specifies a target pUSD + amount and derives the fillable share size from the quote price. A `SELL` + request always uses `shares` sizing, which specifies the exact number of Combo + outcome tokens requested to sell. + + + + Decide the `price` in base units for a full share. A full share is `1000000` + share base units, and `1` pUSD is `1000000` pUSD base units. For example, a + price of `0.45` pUSD per share means `price = 450000`. + + Determine `size` from the request: + + | `requested_size.unit` | `size` | + | --------------------- | -------------------------------------------------- | + | `notional` | `floor(requested_size.value_e6 * 1000000 / price)` | + | `shares` | `requested_size.value_e6` | + + Then determine the order token and amounts: + + | Quote Request | Token | `makerAmount` | `takerAmount` | + | ------------- | ----------------- | ------------------------------------------ | ------------- | + | `SELL` YES | `yes_position_id` | `ceil(price * size / 1000000)` | `size` | + | `BUY` YES | `no_position_id` | `ceil((1000000 - price) * size / 1000000)` | `size` | + + The examples below quote `1` share, so `size = 1000000`. + + + ```json SELL Request theme={null} + { + "salt": "", + "maker": "", + "signer": "", + "tokenId": "", + "makerAmount": "450000", + "takerAmount": "1000000", + "side": 0, + "signatureType": 3, // + "timestamp": "", + "metadata": "0x0000000000000000000000000000000000000000000000000000000000000000", + "builder": "0x0000000000000000000000000000000000000000000000000000000000000000" + } + ``` + + ```json BUY Request theme={null} + { + "salt": "", + "maker": "", + "signer": "", + "tokenId": "", + "makerAmount": "550000", + "takerAmount": "1000000", + "side": 0, + "signatureType": 3, // + "timestamp": "", + "metadata": "0x0000000000000000000000000000000000000000000000000000000000000000", + "builder": "0x0000000000000000000000000000000000000000000000000000000000000000" + } + ``` + + + + + Build the EIP-712 typed-data payload for your wallet type: + + * Use `depositWalletTypedData` when `signature_type` is `3`. + * Use `exchangeV3OrderTypedData` when `signature_type` is `0`, `1`, or `2`. + + + ```json depositWalletTypedData theme={null} + { + "domain": { + "name": "Polymarket CTF Exchange", + "version": "3", + "chainId": 137, + "verifyingContract": "0xe3333700cA9d93003F00f0F71f8515005F6c00Aa" + }, + "types": { + "Order": [ + { "name": "salt", "type": "uint256" }, + { "name": "maker", "type": "address" }, + { "name": "signer", "type": "address" }, + { "name": "tokenId", "type": "uint256" }, + { "name": "makerAmount", "type": "uint256" }, + { "name": "takerAmount", "type": "uint256" }, + { "name": "side", "type": "uint8" }, + { "name": "signatureType", "type": "uint8" }, + { "name": "timestamp", "type": "uint256" }, + { "name": "metadata", "type": "bytes32" }, + { "name": "builder", "type": "bytes32" } + ], + "TypedDataSign": [ + { "name": "contents", "type": "Order" }, + { "name": "name", "type": "string" }, + { "name": "version", "type": "string" }, + { "name": "chainId", "type": "uint256" }, + { "name": "verifyingContract", "type": "address" }, + { "name": "salt", "type": "bytes32" } + ] + }, + "primaryType": "TypedDataSign", + "message": { + "contents": { + "salt": "", + "maker": "", + "signer": "", + "tokenId": "", + "makerAmount": "450000", + "takerAmount": "1000000", + "side": 0, + "signatureType": 3, // + "timestamp": "", + "metadata": "0x0000000000000000000000000000000000000000000000000000000000000000", + "builder": "0x0000000000000000000000000000000000000000000000000000000000000000" + }, + "name": "DepositWallet", + "version": "1", + "chainId": 137, + "verifyingContract": "0xYourDepositWallet", + "salt": "0x0000000000000000000000000000000000000000000000000000000000000000" + } + } + ``` + + ```json exchangeV3OrderTypedData theme={null} + { + "domain": { + "name": "Polymarket CTF Exchange", + "version": "3", + "chainId": 137, + "verifyingContract": "0xe3333700cA9d93003F00f0F71f8515005F6c00Aa" + }, + "types": { + "EIP712Domain": [ + { "name": "name", "type": "string" }, + { "name": "version", "type": "string" }, + { "name": "chainId", "type": "uint256" }, + { "name": "verifyingContract", "type": "address" } + ], + "Order": [ + { "name": "salt", "type": "uint256" }, + { "name": "maker", "type": "address" }, + { "name": "signer", "type": "address" }, + { "name": "tokenId", "type": "uint256" }, + { "name": "makerAmount", "type": "uint256" }, + { "name": "takerAmount", "type": "uint256" }, + { "name": "side", "type": "uint8" }, + { "name": "signatureType", "type": "uint8" }, + { "name": "timestamp", "type": "uint256" }, + { "name": "metadata", "type": "bytes32" }, + { "name": "builder", "type": "bytes32" } + ] + }, + "primaryType": "Order", + "message": { + "salt": "", + "maker": "0xYourEoaAddress", + "signer": "0xYourEoaAddress", + "tokenId": "", + "makerAmount": "450000", + "takerAmount": "1000000", + "side": 0, + "signatureType": 0, // + "timestamp": "", + "metadata": "0x0000000000000000000000000000000000000000000000000000000000000000", + "builder": "0x0000000000000000000000000000000000000000000000000000000000000000" + } + } + ``` + + + Both payloads use the Exchange v3 EIP-712 domain. `exchangeV3OrderTypedData` is + the direct Exchange v3 `Order` payload. `depositWalletTypedData` is a + `TypedDataSign` wrapper whose `contents` field is the Exchange v3 order and + whose message includes the Deposit Wallet validation fields. + + + + Sign the typed-data payload for the wallet type you authenticated with. The + normal Exchange v3 payload and the Deposit Wallet payload are different: + + | Wallet Type | `signatureType` | Payload to sign | `signed_order.signature` | + | -------------- | --------------- | -------------------------- | ------------------------------ | + | Deposit Wallet | `3` | `depositWalletTypedData` | ERC-7739-wrapped signature | + | Safe Wallet | `2` | `exchangeV3OrderTypedData` | Standard 65-byte EVM signature | + | Poly Proxy | `1` | `exchangeV3OrderTypedData` | Standard 65-byte EVM signature | + | EOA | `0` | `exchangeV3OrderTypedData` | Standard 65-byte EVM signature | + + The example below shows how to produce `signature` with Viem for both signing + paths. + + + ```ts sign.ts theme={null} + import { privateKeyToAccount } from "viem/accounts"; + import { wrapDepositWalletSignature } from "./wrapDepositWalletSignature"; + + const signer = privateKeyToAccount(""); + + const signature = + signatureType === 3 + ? wrapDepositWalletSignature( + await signer.signTypedData(depositWalletTypedData), + depositWalletTypedData, + ) + : await signer.signTypedData(exchangeV3OrderTypedData); + ``` + + ```ts wrapDepositWalletSignature.ts theme={null} + import { + concatHex, + encodeAbiParameters, + keccak256, + toHex, + type Address, + type Hex, + } from "viem"; + import type { DepositWalletTypedData } from "./types"; + + const ORDER_TYPE = + "Order(uint256 salt,address maker,address signer,uint256 tokenId,uint256 makerAmount,uint256 takerAmount,uint8 side,uint8 signatureType,uint256 timestamp,bytes32 metadata,bytes32 builder)"; + const EIP712_DOMAIN_TYPE = + "EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)"; + + export function wrapDepositWalletSignature( + innerSignature: Hex, + depositWalletTypedData: DepositWalletTypedData, + ): Hex { + const order = depositWalletTypedData.message.contents; + const exchangeV3Domain = depositWalletTypedData.domain; + + const appDomainSeparator = keccak256( + encodeAbiParameters( + [ + { type: "bytes32" }, + { type: "bytes32" }, + { type: "bytes32" }, + { type: "uint256" }, + { type: "address" }, + ], + [ + keccak256(toHex(EIP712_DOMAIN_TYPE)), + keccak256(toHex(exchangeV3Domain.name)), + keccak256(toHex(exchangeV3Domain.version)), + BigInt(exchangeV3Domain.chainId), + exchangeV3Domain.verifyingContract, + ], + ), + ); + const contentsHash = keccak256( + encodeAbiParameters( + [ + { type: "bytes32" }, + { type: "uint256" }, + { type: "address" }, + { type: "address" }, + { type: "uint256" }, + { type: "uint256" }, + { type: "uint256" }, + { type: "uint8" }, + { type: "uint8" }, + { type: "uint256" }, + { type: "bytes32" }, + { type: "bytes32" }, + ], + [ + keccak256(toHex(ORDER_TYPE)), + BigInt(order.salt), + order.maker, + order.signer, + BigInt(order.tokenId), + BigInt(order.makerAmount), + BigInt(order.takerAmount), + order.side, + order.signatureType, + BigInt(order.timestamp), + order.metadata, + order.builder, + ], + ), + ); + + return concatHex([ + innerSignature, + appDomainSeparator, + contentsHash, + toHex(ORDER_TYPE), + toHex(ORDER_TYPE.length, { size: 2 }), + ]); + } + ``` + + ```ts types.ts theme={null} + import type { Address, Hex } from "viem"; + + export type DepositWalletTypedData = { + domain: { + name: string; + version: string; + chainId: number; + verifyingContract: Address; + }; + message: { + contents: { + salt: string; + maker: Address; + signer: Address; + tokenId: string; + makerAmount: string; + takerAmount: string; + side: number; + signatureType: number; + timestamp: string; + metadata: Hex; + builder: Hex; + }; + }; + types: Record; + primaryType: "TypedDataSign"; + }; + ``` + + + + + Before `submission_deadline`, submit the RFQ ID, quote price, fillable size, and + signed order. Add the signature from the previous step as + `signed_order.signature`. + + + ```json WebSocket theme={null} + { + "type": "RFQ_QUOTE", + "rfq_id": "", + "price_e6": "450000", + "size_e6": "1000000", + "signed_order": { + "salt": "", + "maker": "", + "signer": "", + "tokenId": "", + "makerAmount": "450000", + "takerAmount": "1000000", + "side": 0, + "signatureType": 3, // + "timestamp": "", + "metadata": "0x0000000000000000000000000000000000000000000000000000000000000000", + "builder": "0x0000000000000000000000000000000000000000000000000000000000000000", + "signature": "" + } + } + ``` + + ```bash REST theme={null} + curl -X POST "https://combos-rfq-api.polymarket.com/v1/maker/quotes" \ + -H "Content-Type: application/json" \ + -H "POLY_ADDRESS: " \ + -H "POLY_SIGNATURE: " \ + -H "POLY_TIMESTAMP: " \ + -H "POLY_API_KEY: " \ + -H "POLY_PASSPHRASE: " \ + -d '{ + "quote_id": "", + "rfq_id": "", + "signer_address": "", + "maker_address": "", + "signature_type": 3, + "price_e6": "450000", + "size_e6": "1000000", + "signed_order": { + "salt": "", + "maker": "", + "signer": "", + "tokenId": "", + "makerAmount": "450000", + "takerAmount": "1000000", + "side": 0, + "signatureType": 3, + "timestamp": "", + "metadata": "0x0000000000000000000000000000000000000000000000000000000000000000", + "builder": "0x0000000000000000000000000000000000000000000000000000000000000000", + "signature": "" + } + }' + ``` + + + + REST submissions require a client-generated `quote_id`. Use an opaque unique + value; the RFQ system uses the `quote_` prefix followed by 32 lowercase hex + characters. + + + + + After submitting a quote, store the RFQ ID and quote ID together. WebSocket + submissions receive both values in the acknowledgement. REST submissions return + the current RFQ snapshot, so use the client-generated `quote_id` from the request. + + + ```json WebSocket theme={null} + { + "type": "ACK_RFQ_QUOTE", + "rfq_id": "", + "quote_id": "" + } + ``` + + ```json REST theme={null} + { + "request": { + "rfq_id": "" + // … + }, + "status": "COLLECTING_QUOTES", + "competition_started_at": 1780963200000, + "competition_ends_at": 1780963200400 + } + ``` + + + This reference identifies the submitted quote. + + + + + +### Quote Partial Fills + + + + If you only want to fill part of the requested size, pass `size` with the quote. + `size` is a normalized decimal value: `"10"` means 10 shares, or 10,000,000 base + units. When omitted, the SDK quotes the full requested size. + + ```ts theme={null} + await event.quote({ + price: "0.45", + size: "10", + }); + ``` + + + + If you only want to fill part of the requested size, pass `size` with the quote. + `size` is a `Decimal`-compatible value: `Decimal("10")` means 10 shares, or + 10,000,000 base units. When omitted, the SDK quotes the full requested size. + + ```python theme={null} + from decimal import Decimal + + + await event.quote( + price=Decimal("0.45"), + size=Decimal("10"), + ) + ``` + + + + Partial fills use the same signed-order flow as a full quote. + + + + Start by converting `requested_size` into the full request size in share base + units. + + | `requested_size.unit` | Full request size | + | --------------------- | -------------------------------------------------- | + | `notional` | `floor(requested_size.value_e6 * 1000000 / price)` | + | `shares` | `requested_size.value_e6` | + + Choose a partial `size` in share base units that is smaller than the full request + size. + + + + Compute the signed order amounts from the partial `size`. + + | Quote Request | Token | `makerAmount` | `takerAmount` | + | ------------- | ----------------- | ------------------------------------------ | ------------- | + | `SELL` YES | `yes_position_id` | `ceil(price * size / 1000000)` | `size` | + | `BUY` YES | `no_position_id` | `ceil((1000000 - price) * size / 1000000)` | `size` | + + This example quotes half of a `1` share request at `0.45` pUSD per share, so + `size = 500000`: + + + ```json SELL Request theme={null} + { + "salt": "", + "maker": "", + "signer": "", + "tokenId": "", + "makerAmount": "225000", + "takerAmount": "500000", + "side": 0, + "signatureType": 3, // + "timestamp": "", + "metadata": "0x0000000000000000000000000000000000000000000000000000000000000000", + "builder": "0x0000000000000000000000000000000000000000000000000000000000000000" + } + ``` + + ```json BUY Request theme={null} + { + "salt": "", + "maker": "", + "signer": "", + "tokenId": "", + "makerAmount": "275000", + "takerAmount": "500000", + "side": 0, + "signatureType": 3, // + "timestamp": "", + "metadata": "0x0000000000000000000000000000000000000000000000000000000000000000", + "builder": "0x0000000000000000000000000000000000000000000000000000000000000000" + } + ``` + + + + + Sign the partial order, then submit the quote. + + ```json theme={null} + { + "type": "RFQ_QUOTE", + "rfq_id": "", + "price_e6": "450000", + "size_e6": "500000", + "signed_order": { + "salt": "", + "maker": "", + "signer": "", + "tokenId": "", + "makerAmount": "225000", + "takerAmount": "500000", + "side": 0, + "signatureType": 3, // + "timestamp": "", + "metadata": "0x0000000000000000000000000000000000000000000000000000000000000000", + "builder": "0x0000000000000000000000000000000000000000000000000000000000000000", + "signature": "" + } + } + ``` + + + + + +### Use Inventory + + + + By default, quotes use collateral (pUSD) to buy YES or NO tokens as needed to + satisfy the quote request according to the combinatorial position logic. Pass + `source: "inventory"` when you want to quote from existing inventory instead. + + ```ts theme={null} + await event.quote({ + price: "0.45", + source: "inventory", + }); + ``` + + + + By default, quotes use collateral (pUSD) to buy YES or NO tokens as needed to + satisfy the quote request according to the combinatorial position logic. Pass + `source=RfqQuoteSource.INVENTORY` when you want to quote from existing inventory + instead. + + ```python theme={null} + from decimal import Decimal + + from polymarket import RfqQuoteSource + + + await event.quote( + price=Decimal("0.45"), + source=RfqQuoteSource.INVENTORY, + ) + ``` + + + + Inventory quotes sell existing outcome tokens instead of spending collateral. The + RFQ quote price still means pUSD per YES Combo share. + + + + Use the token you already hold for the side of the quote request. + + | Quote Request | Inventory Token | Order Side | + | ------------- | ----------------- | ---------- | + | `BUY` YES | `yes_position_id` | SELL | + | `SELL` YES | `no_position_id` | SELL | + + + + Compute the signed order amounts from the inventory `size`. + + | Quote Request | Order Price | `makerAmount` | `takerAmount` | + | ------------- | ----------------- | ------------- | ------------------------------------------- | + | `BUY` YES | `price` | `size` | `floor(price * size / 1000000)` | + | `SELL` YES | `1000000 - price` | `size` | `floor((1000000 - price) * size / 1000000)` | + + This example quotes `1` share at `0.45` pUSD per share, so `price = 450000` and + `size = 1000000`: + + + ```json BUY Request theme={null} + { + "salt": "", + "maker": "", + "signer": "", + "tokenId": "", + "makerAmount": "1000000", + "takerAmount": "450000", + "side": 1, + "signatureType": 3, // + "timestamp": "", + "metadata": "0x0000000000000000000000000000000000000000000000000000000000000000", + "builder": "0x0000000000000000000000000000000000000000000000000000000000000000" + } + ``` + + ```json SELL Request theme={null} + { + "salt": "", + "maker": "", + "signer": "", + "tokenId": "", + "makerAmount": "1000000", + "takerAmount": "550000", + "side": 1, + "signatureType": 3, // + "timestamp": "", + "metadata": "0x0000000000000000000000000000000000000000000000000000000000000000", + "builder": "0x0000000000000000000000000000000000000000000000000000000000000000" + } + ``` + + + + + Sign the inventory order, then submit the quote. + + ```json theme={null} + { + "type": "RFQ_QUOTE", + "rfq_id": "", + "price_e6": "450000", + "size_e6": "1000000", + "signed_order": { + "salt": "", + "maker": "", + "signer": "", + "tokenId": "", + "makerAmount": "1000000", + "takerAmount": "450000", + "side": 1, + "signatureType": 3, // + "timestamp": "", + "metadata": "0x0000000000000000000000000000000000000000000000000000000000000000", + "builder": "0x0000000000000000000000000000000000000000000000000000000000000000", + "signature": "" + } + } + ``` + + + + + +### Cancel Quotes + +After you submit a quote, keep the returned quote reference. If your price, +inventory, or risk changes before the quote is selected, use that reference to +request cancellation. + + + A cancellation acknowledgement means the RFQ system processed the cancellation + request. It does not guarantee the quote was withdrawn from an RFQ that was + already selected. + + + + + + + First, keep the quote reference returned by `event.quote(…)`. It contains the + `rfqId` and `quoteId` needed to cancel the quote. + + ```ts theme={null} + const reference = await event.quote({ price: 0.45 }); + + // reference.rfqId: RfqId + // reference.quoteId: RfqQuoteId + ``` + + + + Then, pass that reference to `session.cancelQuote(…)` on the same live RFQ + session. + + ```ts theme={null} + if (shouldCancelQuote) { + const ack = await session.cancelQuote(reference); + + // ack.rfqId: RfqId + // ack.quoteId: RfqQuoteId + } + ``` + + + + + + + + First, keep the quote reference returned by `event.quote(...)`. It contains the + `rfq_id` and `quote_id` needed to cancel the quote. + + ```python theme={null} + from decimal import Decimal + + + reference = await event.quote(price=Decimal("0.45")) + + # reference.rfq_id: RfqId + # reference.quote_id: RfqQuoteId + ``` + + + + Then, pass that reference to `session.cancel_quote(...)` on the same live RFQ + session. + + ```python theme={null} + if should_cancel_quote: + ack = await session.cancel_quote(reference) + + # ack.rfq_id: RfqId + # ack.quote_id: RfqQuoteId + ``` + + + + + + Send a cancellation request with the RFQ ID and quote ID. On the WebSocket, the + RFQ system acknowledges a processed cancellation request with + `ACK_RFQ_QUOTE_CANCEL`. + + + ```json Send theme={null} + { + "type": "RFQ_QUOTE_CANCEL", + "rfq_id": "", + "quote_id": "", + "signer_address": "", + "maker_address": "" + } + ``` + + ```json Receive theme={null} + { + "type": "ACK_RFQ_QUOTE_CANCEL", + "rfq_id": "", + "quote_id": "" + } + ``` + + + Alternatively, cancel the quote through the REST API. + + + ```bash Request theme={null} + curl -X POST "https://combos-rfq-api.polymarket.com/v1/maker/quotes/cancel" \ + -H "Content-Type: application/json" \ + -H "POLY_ADDRESS: " \ + -H "POLY_SIGNATURE: " \ + -H "POLY_TIMESTAMP: " \ + -H "POLY_API_KEY: " \ + -H "POLY_PASSPHRASE: " \ + -d '{ + "rfq_id": "", + "quote_id": "", + "signer_address": "", + "maker_address": "", + "signature_type": 3 + }' + ``` + + ```json Response theme={null} + { + "request": { + "rfq_id": "" + // … + }, + "status": "COLLECTING_QUOTES", + "competition_started_at": 1780963200000, + "competition_ends_at": 1780963200400 + } + ``` + + + + +### Last Look + +Last Look is a separate final review step for makers that have it enabled. If a +selected quote requires Last Look, run a final risk check before the deadline and +accept or reject the fill. + +Last Look is offered to makers with approximately \$2,500 in Combo notional +volume and an established line of communication with Polymarket. This keeps the +program reliable and helps Polymarket resolve system issues quickly. + +To request access, complete the [Last Look request +form](https://forms.gle/dk5A1DRw8EN5uP9z5). + + + Makers are expected to accept most selected quotes. We track acceptance rates, + and makers who reject more than 15% of selected quotes over a one-hour + lookback window may be paused from quoting for a few minutes. + + +Once access is enabled, your quoting system will immediately be asked to review +selected fills. Make sure it is ready to evaluate and answer them before approval +is activated. + + + + + + First, switch on `event.type` to handle confirmation requests from the same + session stream. + + ```ts theme={null} + switch (event.type) { + case "confirmation_request": + // event: RfqConfirmationRequestEvent + void handleConfirmationRequest(event); + break; + + // … + } + ``` + + + + Then, inspect the confirmation request before running your final risk check. It + includes the selected quote, the final fill size, and the `event.confirmBy` + deadline for your Last Look response. + + ```ts theme={null} + type RfqConfirmationRequestEvent = { + type: "confirmation_request"; + rfqId: RfqId; + quoteId: RfqQuoteId; + conditionId: ComboConditionId; + direction: RfqDirection; + side: RfqSide.Yes; + price: DecimalString; + fillSize: DecimalString; + yesPositionId: PositionId; + noPositionId: PositionId; + legPositionIds: PositionId[]; + confirmBy: EpochMilliseconds; + confirm(): Promise; + decline(): Promise; + }; + ``` + + + + Finally, run your final risk check outside the session loop and respond before + the `event.confirmBy` deadline. + + ```ts theme={null} + async function handleConfirmationRequest(event: RfqConfirmationRequestEvent) { + const canStillFill = runFinalRiskCheck(event); + + if (canStillFill) { + await event.confirm(); + return; + } + + await event.decline(); + } + ``` + + + + + + + + First, use `isinstance(...)` to handle confirmation requests from the same + session stream. + + ```python theme={null} + from polymarket import RfqConfirmationRequestEvent + + + async for event in session: + if isinstance(event, RfqConfirmationRequestEvent): + await handle_confirmation_request(event) + ``` + + + + Then, inspect the confirmation request before running your final risk check. It + includes the selected quote, the final fill size, and the `event.confirm_by` + deadline for your Last Look response. + + ```python theme={null} + class RfqConfirmationRequestEvent: + type: "confirmation_request" + rfq_id: RfqId + quote_id: RfqQuoteId + signer_address: EvmAddress + maker_address: EvmAddress + signature_type: int + condition_id: ComboConditionId + direction: RfqDirection + side: RfqSide + price: Decimal + fill_size: Decimal + yes_position_id: PositionId + no_position_id: PositionId + leg_position_ids: tuple[PositionId, ...] + confirm_by: int + + async def confirm(self) -> RfqConfirmationAck: ... + async def decline(self) -> RfqConfirmationAck: ... + ``` + + + + Finally, run your final risk check outside the session loop and respond before + the `event.confirm_by` deadline. + + ```python theme={null} + from polymarket import RfqConfirmationRequestEvent + + + async def handle_confirmation_request( + event: RfqConfirmationRequestEvent, + ) -> None: + can_still_fill = run_final_risk_check(event) + + if can_still_fill: + await event.confirm() + return + + await event.decline() + ``` + + + + + + If Last Look is enabled for your maker, the RFQ WebSocket sends + `RFQ_CONFIRMATION_REQUEST` after your quote is selected. + + ```json theme={null} + { + "type": "RFQ_CONFIRMATION_REQUEST", + "rfq_id": "", + "quote_id": "", + "signer_address": "", + "maker_address": "", + "signature_type": 3, // + "leg_position_ids": ["", ""], + "condition_id": "", + "yes_position_id": "", + "no_position_id": "", + "direction": "BUY", + "side": "YES", + "fill_size_e6": "1000000", + "price_e6": "450000", + "confirm_by": 1780963200000 + } + ``` + + Respond before `confirm_by` with `CONFIRM` or `DECLINE`. + + + ```json Confirm theme={null} + { + "type": "RFQ_CONFIRMATION_RESPONSE", + "rfq_id": "", + "quote_id": "", + "decision": "CONFIRM" + } + ``` + + ```json Decline theme={null} + { + "type": "RFQ_CONFIRMATION_RESPONSE", + "rfq_id": "", + "quote_id": "", + "decision": "DECLINE" + } + ``` + + + The RFQ system acknowledges the response with + `ACK_RFQ_CONFIRMATION_RESPONSE`. + + ```json theme={null} + { + "type": "ACK_RFQ_CONFIRMATION_RESPONSE", + "rfq_id": "", + "quote_id": "", + "decision": "CONFIRM" + } + ``` + + Do not include `signer_address`, `maker_address`, or `signature_type` in + `RFQ_CONFIRMATION_RESPONSE`. The RFQ system applies identity from the + authenticated session. + + Alternatively, send the Last Look decision through the REST API. The response + returns `execution` when your confirmation completes the bundle. If the RFQ is + still waiting on another maker confirmation, or if you decline, it returns + `snapshot`. + + + ```bash Request theme={null} + curl -X POST "https://combos-rfq-api.polymarket.com/v1/maker/confirmations" \ + -H "Content-Type: application/json" \ + -H "POLY_ADDRESS: " \ + -H "POLY_SIGNATURE: " \ + -H "POLY_TIMESTAMP: " \ + -H "POLY_API_KEY: " \ + -H "POLY_PASSPHRASE: " \ + -d '{ + "rfq_id": "", + "quote_id": "", + "signer_address": "", + "maker_address": "", + "signature_type": 3, + "decision": "CONFIRM" + }' + ``` + + ```json Execution Response theme={null} + { + "execution": { + "execution_id": "", + "quote_id": "", + "request": { + "rfq_id": "" + } + } + } + ``` + + ```json Snapshot Response theme={null} + { + "snapshot": { + "request": { + "rfq_id": "" + }, + "status": "AWAITING_MAKER_CONFIRMATION" + } + } + ``` + + + + +## Manage Combo Positions + +Use Combo position workflows to manage inventory throughout the quote lifecycle. + +### List Combo Positions + +List Combo positions as part of your background inventory sync. Keep this state +fresh outside the quote path. + + + + Use `client.listComboPositions(...)` to page through Combo positions for the + authenticated account. + + ```ts theme={null} + import { + ComboPositionSort, + ComboPositionStatus, + type ComboPosition, + } from "@polymarket/client"; + + const positions = client.listComboPositions({ + status: ComboPositionStatus.Open, + pageSize: 50, + }); + + for await (const page of positions) { + for (const position of page.items) { + // position: ComboPosition + } + } + ``` + + You can filter positions by the following criteria. `conditionId` accepts one + Combo condition ID or an array of Combo condition IDs. + + + ```ts Condition ID theme={null} + const positions = client.listComboPositions({ + conditionId: ["", ""], + }); + ``` + + ```ts Status theme={null} + const positions = client.listComboPositions({ + status: ComboPositionStatus.Open, + }); + ``` + + ```ts Incremental Sync theme={null} + const positions = client.listComboPositions({ + updatedAfter: lastWatermarkSeconds, + sort: ComboPositionSort.UpdatedAsc, + pageSize: 1000, + }); + ``` + + + Each returned item is a `ComboPosition`. + + + ```ts ComboPosition theme={null} + type ComboPosition = { + conditionId: ComboConditionId; + positionId: PositionId; + outcome: ComboPositionOutcome; + moduleId: number; + wallet: Address; + shares: DecimalString; + entryAvgPriceUsdc?: DecimalString | null; + entryCostUsdc?: DecimalString | null; + realizedPayoutUsdc?: DecimalString | null; + totalCostUsdc?: DecimalString | null; + status: ComboPositionStatus; + redeemable: boolean; + firstEntryAt: IsoDateTimeString; + resolvedAt?: IsoDateTimeString | null; + updatedAt?: IsoDateTimeString; + legsTotal: number; + legsResolved: number; + legsPending: number; + legs: ComboPositionLeg[]; + }; + ``` + + ```ts ComboPositionLeg theme={null} + type ComboPositionLeg = { + legIndex: number; + legPositionId: PositionId; + legConditionId: CtfConditionId; + legOutcomeIndex: number; + legOutcomeLabel?: string | null; + legStatus: ComboPositionStatus; + legResolvedAt?: IsoDateTimeString | null; + legCurrentPrice?: DecimalString | null; + market?: ComboPositionMarket | null; + }; + ``` + + ```ts ComboPositionMarket theme={null} + type ComboPositionMarket = { + marketId?: string | null; + slug?: string | null; + title?: string | null; + outcome?: string | null; + imageUrl?: string | null; + iconUrl?: string | null; + category?: string | null; + subcategory?: string | null; + tags?: string[] | null; + endDate?: IsoDateTimeString | null; + event?: ComboPositionMarketEvent | null; + }; + ``` + + ```ts ComboPositionMarketEvent theme={null} + type ComboPositionMarketEvent = { + eventId?: string | null; + eventSlug?: string | null; + eventTitle?: string | null; + eventImage?: string | null; + }; + ``` + + + For redeemed positions, `shares` and `entryCostUsdc` track remaining inventory, + so both can read as zero after a winning Combo is redeemed. Use + `realizedPayoutUsdc` for gross redemption proceeds and `totalCostUsdc` for + original cost basis; net result is `realizedPayoutUsdc - totalCostUsdc`. + + + + Use `client.list_combo_positions(...)` to page through Combo positions for the + authenticated wallet. The Python SDK returns snake\_case model fields and + `Decimal` values for numeric position amounts. + + ```python theme={null} + positions = client.list_combo_positions(status="OPEN") + + async for page in positions: + for position in page.items: + # position: ComboPosition + ... + ``` + + You can filter positions by the following criteria. `condition_id` accepts one + Combo condition ID or a sequence of Combo condition IDs. + + + ```python Condition ID theme={null} + positions = client.list_combo_positions( + condition_id=["", ""], + ) + ``` + + ```python Status theme={null} + positions = client.list_combo_positions( + status="OPEN", + ) + ``` + + ```python Incremental Sync theme={null} + positions = client.list_combo_positions( + updated_after=last_watermark_seconds, + sort="updated_asc", + page_size=1000, + ) + ``` + + + The returned `ComboPosition` models include the following fields: + + + ```python ComboPosition theme={null} + class ComboPosition: + condition_id: ComboConditionId + position_id: PositionId + outcome: ComboPositionOutcome + module_id: int + wallet: EvmAddress + shares: Decimal + entry_avg_price_usdc: Decimal | None + entry_cost_usdc: Decimal | None + realized_payout_usdc: Decimal | None + total_cost_usdc: Decimal | None + status: ComboPositionStatus + redeemable: bool + first_entry_at: datetime + resolved_at: datetime | None + updated_at: datetime | None + legs_total: int + legs_resolved: int + legs_pending: int + legs: tuple[ComboPositionLeg, ...] + ``` + + ```python ComboPositionLeg theme={null} + class ComboPositionLeg: + leg_index: int + leg_position_id: PositionId + leg_condition_id: CtfConditionId + leg_outcome_index: int + leg_outcome_label: str | None + leg_status: ComboPositionStatus + leg_resolved_at: datetime | None + leg_current_price: Decimal | None + market: ComboPositionMarket | None + ``` + + ```python ComboPositionMarket theme={null} + class ComboPositionMarket: + market_id: str | None + slug: str | None + title: str | None + outcome: str | None + image_url: str | None + icon_url: str | None + category: str | None + subcategory: str | None + tags: tuple[str, ...] | None + end_date: datetime | None + event: ComboPositionMarketEvent | None + ``` + + ```python ComboPositionMarketEvent theme={null} + class ComboPositionMarketEvent: + event_id: str | None + event_slug: str | None + event_title: str | None + event_image: str | None + ``` + + + For redeemed positions, `shares` and `entry_cost_usdc` track remaining + inventory, so both can be zero after a winning Combo is redeemed. Use + `realized_payout_usdc` for gross redemption proceeds and `total_cost_usdc` for + original cost basis; net result is `realized_payout_usdc - total_cost_usdc`. + + + + Use the Data API to list Combo positions for a wallet. + + ```bash theme={null} + curl -G "https://data-api.polymarket.com/v1/positions/combos" \ + --data-urlencode "user=" \ + --data-urlencode "limit=50" \ + --data-urlencode "status=OPEN" + ``` + + You can filter positions by the following query parameters: + + + ```bash Condition ID theme={null} + curl -G "https://data-api.polymarket.com/v1/positions/combos" \ + --data-urlencode "user=" \ + --data-urlencode "market_id=" + ``` + + ```bash Position ID theme={null} + curl -G "https://data-api.polymarket.com/v1/positions/combos" \ + --data-urlencode "user=" \ + --data-urlencode "combo_position_id=" + ``` + + ```bash Status theme={null} + curl -G "https://data-api.polymarket.com/v1/positions/combos" \ + --data-urlencode "user=" \ + --data-urlencode "status=OPEN" + ``` + + + The response returns Combo positions in `combos` and pagination metadata in + `pagination`. + + ```json theme={null} + { + "combos": [ + { + "combo_condition_id": "", + "combo_position_id": "", + "module_id": 3, + "user_address": "", + "shares_balance": "10", + "entry_avg_price_usdc": "0.45", + "entry_cost_usdc": "4.5", + "realized_payout_usdc": "0.00", + "total_cost_usdc": "4.50", + "status": "OPEN", + "first_entry_at": "2026-06-08T00:00:00Z", + "resolved_at": null, + "updated_at": "2026-06-08T00:00:00Z", + "legs_total": 2, + "legs_resolved": 0, + "legs_pending": 2, + "legs": [ + { + "leg_index": 0, + "leg_position_id": "", + "leg_condition_id": "", + "leg_outcome_index": 0, + "leg_outcome_label": "Yes", + "leg_status": "OPEN", + "leg_resolved_at": null, + "leg_current_price": "0.52" + } + ] + } + ], + "pagination": { + "limit": 50, + "offset": 0, + "has_more": true, + "next_cursor": "eyJsIjo1MCwibyI6NTB9" + } + } + ``` + + Use `cursor` from `pagination.next_cursor` to fetch the next page. Keep the same + filters and `sort`; `cursor` supersedes `offset`. A `null` cursor means there + are no more pages. + + ```bash Cursor theme={null} + curl -G "https://data-api.polymarket.com/v1/positions/combos" \ + --data-urlencode "user=" \ + --data-urlencode "limit=100" \ + --data-urlencode "sort=first_entry_desc" \ + --data-urlencode "cursor=" + ``` + + Use `updatedAfter` with `sort=updated_asc` to incrementally sync changed + positions. Store the newest `updated_at` you process as your next watermark; + boundary rows may re-deliver, so upsert by `(combo_condition_id, + combo_position_id)`. + + ```bash Incremental sync theme={null} + curl -G "https://data-api.polymarket.com/v1/positions/combos" \ + --data-urlencode "user=" \ + --data-urlencode "updatedAfter=" \ + --data-urlencode "sort=updated_asc" \ + --data-urlencode "limit=1000" + ``` + + For redeemed positions, `shares_balance` and `entry_cost_usdc` track remaining + inventory, so both can read as zero after a winning Combo is redeemed. Use + `realized_payout_usdc` for gross redemption proceeds and `total_cost_usdc` for + original cost basis; net result is `realized_payout_usdc - total_cost_usdc`. + + + +### List Combo Activity + +Use Combo activity when you need an audit trail for inventory-changing events, +including splits, merges, conversions, wraps, unwraps, and redeems. Use Combo +positions for current inventory state. + + + + Use `client.listComboActivity(...)` to page through Combo lifecycle activity for + the authenticated account. + + ```ts theme={null} + import { ComboActivityType, type ComboActivity } from "@polymarket/client"; + + const activity = client.listComboActivity({ pageSize: 50 }); + + for await (const page of activity) { + for (const item of page.items) { + // item: ComboActivity + if (item.type === ComboActivityType.Redeem) { + console.log(item.positionId, item.payout); + } + } + } + ``` + + Filter to one or more Combos with `conditionId`. + + ```ts theme={null} + const activity = client.listComboActivity({ + conditionId: ["", ""], + }); + ``` + + Each returned item is a discriminated `ComboActivity` union. All lifecycle rows + share the base fields; redeem rows also include the redeemed position ID and + payout. + + + ```ts ComboActivity theme={null} + type ComboActivity = + | ComboSplitActivity + | ComboMergeActivity + | ComboConvertActivity + | ComboCompressActivity + | ComboWrapActivity + | ComboUnwrapActivity + | ComboRedeemActivity; + ``` + + ```ts Split / Merge theme={null} + type ComboSplitActivity = { + id: ComboActivityId; + type: ComboActivityType.Split; + wallet: Address; + conditionId: ComboConditionId; + moduleId: number; + amount: DecimalString | null; + timestamp: EpochMilliseconds; + transactionAt: IsoDateTimeString; + transactionHash: TxHash; + logIndex: number; + blockNumber: number; + legs: ComboPositionLeg[]; + }; + + type ComboMergeActivity = { + id: ComboActivityId; + type: ComboActivityType.Merge; + wallet: Address; + conditionId: ComboConditionId; + moduleId: number; + amount: DecimalString | null; + timestamp: EpochMilliseconds; + transactionAt: IsoDateTimeString; + transactionHash: TxHash; + logIndex: number; + blockNumber: number; + legs: ComboPositionLeg[]; + }; + ``` + + ```ts Convert / Compress theme={null} + type ComboConvertActivity = { + id: ComboActivityId; + type: ComboActivityType.Convert; + wallet: Address; + conditionId: ComboConditionId; + moduleId: number; + amount: DecimalString | null; + timestamp: EpochMilliseconds; + transactionAt: IsoDateTimeString; + transactionHash: TxHash; + logIndex: number; + blockNumber: number; + legs: ComboPositionLeg[]; + }; + + type ComboCompressActivity = { + id: ComboActivityId; + type: ComboActivityType.Compress; + wallet: Address; + conditionId: ComboConditionId; + moduleId: number; + amount: DecimalString | null; + timestamp: EpochMilliseconds; + transactionAt: IsoDateTimeString; + transactionHash: TxHash; + logIndex: number; + blockNumber: number; + legs: ComboPositionLeg[]; + }; + ``` + + ```ts Wrap / Unwrap theme={null} + type ComboWrapActivity = { + id: ComboActivityId; + type: ComboActivityType.Wrap; + wallet: Address; + conditionId: ComboConditionId; + moduleId: number; + amount: DecimalString | null; + timestamp: EpochMilliseconds; + transactionAt: IsoDateTimeString; + transactionHash: TxHash; + logIndex: number; + blockNumber: number; + legs: ComboPositionLeg[]; + }; + + type ComboUnwrapActivity = { + id: ComboActivityId; + type: ComboActivityType.Unwrap; + wallet: Address; + conditionId: ComboConditionId; + moduleId: number; + amount: DecimalString | null; + timestamp: EpochMilliseconds; + transactionAt: IsoDateTimeString; + transactionHash: TxHash; + logIndex: number; + blockNumber: number; + legs: ComboPositionLeg[]; + }; + ``` + + ```ts ComboRedeemActivity theme={null} + type ComboRedeemActivity = { + id: ComboActivityId; + type: ComboActivityType.Redeem; + wallet: Address; + conditionId: ComboConditionId; + moduleId: number; + amount: DecimalString | null; + timestamp: EpochMilliseconds; + transactionAt: IsoDateTimeString; + transactionHash: TxHash; + logIndex: number; + blockNumber: number; + legs: ComboPositionLeg[]; + positionId: PositionId; + payout: DecimalString | null; + }; + ``` + + + + + Use `client.list_combo_activity(...)` to page through Combo lifecycle activity + for a wallet. + + ```python theme={null} + activity = client.list_combo_activity( + user="", + page_size=50, + ) + + for page in activity: + for item in page.items: + # item: ComboActivity + if item.type == "REDEEM": + print(item.position_id, item.payout) + ``` + + Filter to one or more Combos with `condition_id`. + + ```python theme={null} + activity = client.list_combo_activity( + user="", + condition_id=["", ""], + ) + ``` + + The returned `ComboActivity` models use a `type` discriminator. All lifecycle + rows share the base fields; redeem rows also include the redeemed position ID + and payout. + + + ```python ComboActivity theme={null} + ComboActivity = ( + ComboSplitActivity + | ComboMergeActivity + | ComboConvertActivity + | ComboCompressActivity + | ComboWrapActivity + | ComboUnwrapActivity + | ComboRedeemActivity + ) + ``` + + ```python Split / Merge theme={null} + class ComboSplitActivity: + id: ComboActivityId + type: Literal["SPLIT"] + wallet: EvmAddress + condition_id: ComboConditionId + module_id: int + amount: Decimal | None + timestamp: datetime + transaction_at: datetime + transaction_hash: TransactionHash + log_index: int + block_number: int + legs: tuple[ComboPositionLeg, ...] + + + class ComboMergeActivity: + id: ComboActivityId + type: Literal["MERGE"] + wallet: EvmAddress + condition_id: ComboConditionId + module_id: int + amount: Decimal | None + timestamp: datetime + transaction_at: datetime + transaction_hash: TransactionHash + log_index: int + block_number: int + legs: tuple[ComboPositionLeg, ...] + ``` + + ```python Convert / Compress theme={null} + class ComboConvertActivity: + id: ComboActivityId + type: Literal["CONVERT"] + wallet: EvmAddress + condition_id: ComboConditionId + module_id: int + amount: Decimal | None + timestamp: datetime + transaction_at: datetime + transaction_hash: TransactionHash + log_index: int + block_number: int + legs: tuple[ComboPositionLeg, ...] + + + class ComboCompressActivity: + id: ComboActivityId + type: Literal["COMPRESS"] + wallet: EvmAddress + condition_id: ComboConditionId + module_id: int + amount: Decimal | None + timestamp: datetime + transaction_at: datetime + transaction_hash: TransactionHash + log_index: int + block_number: int + legs: tuple[ComboPositionLeg, ...] + ``` + + ```python Wrap / Unwrap theme={null} + class ComboWrapActivity: + id: ComboActivityId + type: Literal["WRAP"] + wallet: EvmAddress + condition_id: ComboConditionId + module_id: int + amount: Decimal | None + timestamp: datetime + transaction_at: datetime + transaction_hash: TransactionHash + log_index: int + block_number: int + legs: tuple[ComboPositionLeg, ...] + + + class ComboUnwrapActivity: + id: ComboActivityId + type: Literal["UNWRAP"] + wallet: EvmAddress + condition_id: ComboConditionId + module_id: int + amount: Decimal | None + timestamp: datetime + transaction_at: datetime + transaction_hash: TransactionHash + log_index: int + block_number: int + legs: tuple[ComboPositionLeg, ...] + ``` + + ```python ComboRedeemActivity theme={null} + class ComboRedeemActivity: + id: ComboActivityId + type: Literal["REDEEM"] + wallet: EvmAddress + condition_id: ComboConditionId + module_id: int + amount: Decimal | None + timestamp: datetime + transaction_at: datetime + transaction_hash: TransactionHash + log_index: int + block_number: int + legs: tuple[ComboPositionLeg, ...] + position_id: PositionId + payout: Decimal | None + ``` + + + + + Use the Data API to list Combo lifecycle activity for a wallet. + + ```bash theme={null} + curl -G "https://data-api.polymarket.com/v1/activity/combos" \ + --data-urlencode "user=" \ + --data-urlencode "limit=50" + ``` + + Filter to specific Combos with `market_id`, which accepts comma-separated + `combo_condition_id` values. + + ```bash Filter by Combo theme={null} + curl -G "https://data-api.polymarket.com/v1/activity/combos" \ + --data-urlencode "user=" \ + --data-urlencode "market_id=," + ``` + + The response returns lifecycle events in `activity` and pagination metadata in + `pagination`. + + ```json theme={null} + { + "activity": [ + { + "id": "-", + "event_kind": "PositionsSplit", + "side": "Split", + "module_kind": "Combinatorial", + "user_address": "", + "combo_condition_id": "", + "combo_position_id": "", + "module_id": 3, + "amount_usdc": 10.0, + "payout_usdc": null, + "timestamp": 1783379945, + "tx_dttm": "2026-07-06T23:19:05Z", + "tx_hash": "", + "log_index": 2409, + "block_number": 89783300, + "legs": [ + { + "leg_index": 0, + "leg_position_id": "", + "leg_condition_id": "", + "leg_outcome_index": 0, + "leg_outcome_label": "Yes", + "leg_status": "OPEN", + "leg_resolved_at": null, + "leg_current_price": "0.52" + } + ] + } + ], + "pagination": { + "limit": 50, + "offset": 0, + "has_more": true, + "next_cursor": "eyJsIjo1MCwibyI6NTB9" + } + } + ``` + + Use `cursor` from `pagination.next_cursor` to fetch the next page. `cursor` + supersedes `offset`. A `null` cursor means there are no more pages. + + ```bash Cursor theme={null} + curl -G "https://data-api.polymarket.com/v1/activity/combos" \ + --data-urlencode "user=" \ + --data-urlencode "limit=50" \ + --data-urlencode "cursor=" + ``` + + + +### Inventory Management + +If you want to quote from inventory, build the inventory before quote requests +arrive. Splitting converts collateral into complementary Combo positions for a +set of legs. Merging converts matching complementary Combo positions back into +collateral. + + + + Use `client.splitPosition(...)` with `legs` to create Combo inventory from + collateral. `amount` is in pUSD base units. + + ```ts theme={null} + const split = await client.splitPosition({ + amount: 10_000_000n, + legs: ["", ""], + }); + + const splitOutcome = await split.wait(); + + // splitOutcome.transactionHash identifies the confirmed split transaction. + ``` + + Use `client.mergePositions(...)` with the same `legs` to merge complementary + Combo positions back into collateral. Pass `amount: "max"` to merge the largest + matching amount available. + + ```ts theme={null} + const merge = await client.mergePositions({ + amount: "max", + legs: ["", ""], + }); + + const mergeOutcome = await merge.wait(); + + // mergeOutcome.transactionHash identifies the confirmed merge transaction. + ``` + + + + Use `client.split_position(...)` with `legs` to create Combo inventory from + collateral. `amount` is in pUSD base units. + + ```python theme={null} + split = await client.split_position( + amount=10_000_000, + legs=["", ""], + ) + + split_outcome = await split.wait() + + # split_outcome.transaction_hash identifies the confirmed split transaction. + ``` + + Use `client.merge_positions(...)` with the same `legs` to merge complementary + Combo positions back into collateral. Pass `amount="max"` to merge the largest + matching amount available. + + ```python theme={null} + merge = await client.merge_positions( + amount="max", + legs=["", ""], + ) + + merge_outcome = await merge.wait() + + # merge_outcome.transaction_hash identifies the confirmed merge transaction. + ``` + + + + Use the Relayer API to split or merge Combo inventory by sending an ordered list + of encoded contract calls in one batch. The following steps assume you are using + a Deposit Wallet. + + + If you use a Safe or Poly Proxy wallet, use one of the SDKs instead because + those wallet integrations require wallet-specific signing and encoding. + + + Use these contract addresses when building the call list. + + | Contract | Address | + | --------------------- | -------------------------------------------- | + | CombinatorialModule | `0x30000034706c7d8e12009dab006be20000c031a8` | + | Router | `0x12121212006e4CD160D18e3f00711DA5c3372600` | + | PositionManager | `0x006F54F7f9A22e0000CC2AB60031000000ae9fEF` | + | pUSD collateral token | `0xC011a7E12a19f7B1f670d46F03B03f3342E82DFB` | + + + + First, determine whether the inventory action needs an approval. If approval is + already in place, skip this step. + + For a split, `` must approve pUSD spending by the Router. For a + merge, `` must approve the Router as a PositionManager ERC-1155 + operator. + + + ```solidity ERC-20 Approval theme={null} + function approve(address spender, uint256 amount) returns (bool); + ``` + + ```solidity ERC-1155 Approval theme={null} + function setApprovalForAll(address operator, bool approved); + ``` + + + Encode one of these approval calls when needed. Keep the resulting call object; + it will be added before the Combo calls in the next step. + + + ```json Split Approval Call theme={null} + [ + { + "target": "0xC011a7E12a19f7B1f670d46F03B03f3342E82DFB", + "value": "0", + "data": "" + } + ] + ``` + + ```json Merge Approval Call theme={null} + [ + { + "target": "0x006F54F7f9A22e0000CC2AB60031000000ae9fEF", + "value": "0", + "data": "" + } + ] + ``` + + + + + Then, add the Combo call objects to the ordered list. + + For a split, include `prepareCondition` before `split`. `prepareCondition` is + idempotent, so it is safe to include even when the Combo condition was already + prepared. For a merge, call `merge` directly with the Combo condition ID for the + positions being merged. + + ```solidity theme={null} + function prepareCondition(uint256[] legs) returns (bytes31); + function split(bytes31 conditionId, uint256 amount); + function merge(bytes31 conditionId, uint256 amount); + ``` + + Append these encoded calls after the approval call from the previous step, if one + was needed. + + + ```json Split Combo Calls theme={null} + [ + // Include the approval call first when needed. + // … + { + "target": "0x30000034706c7d8e12009dab006be20000c031a8", + "value": "0", + "data": "" + }, + { + "target": "0x12121212006e4CD160D18e3f00711DA5c3372600", + "value": "0", + "data": "" + } + ] + ``` + + ```json Merge Combo Calls theme={null} + [ + // Include the approval call first when needed. + // … + { + "target": "0x12121212006e4CD160D18e3f00711DA5c3372600", + "value": "0", + "data": "" + } + ] + ``` + + + + + Fetch a fresh `WALLET` nonce before each submission. + + ```bash theme={null} + curl -G "https://relayer-v2.polymarket.com/v1/account/transactions/params" \ + -H "RELAYER_API_KEY: $RELAYER_API_KEY" \ + -H "RELAYER_API_KEY_ADDRESS: $RELAYER_API_KEY_ADDRESS" \ + --data-urlencode "address=$RELAYER_API_KEY_ADDRESS" \ + --data-urlencode "type=WALLET" + ``` + + The response includes the nonce to sign with the transaction. + + ```json theme={null} + { + "address": "", + "nonce": "" + } + ``` + + + + Build the Deposit Wallet EIP-712 `Batch` typed data. + + ```json theme={null} + { + "domain": { + "name": "DepositWallet", + "version": "1", + "chainId": 137, + "verifyingContract": "" + }, + "types": { + "Call": [ + { "name": "target", "type": "address" }, + { "name": "value", "type": "uint256" }, + { "name": "data", "type": "bytes" } + ], + "Batch": [ + { "name": "wallet", "type": "address" }, + { "name": "nonce", "type": "uint256" }, + { "name": "deadline", "type": "uint256" }, + { "name": "calls", "type": "Call[]" } + ] + }, + "primaryType": "Batch", + "message": { + "wallet": "", + "nonce": "", + "deadline": "", + "calls": [ + // Use the final calls array from the previous steps. + // … + ] + } + } + ``` + + Sign the EIP-712 batch with your signer. Use the resulting signature as + `signature` in the relayer submission. + + + + Submit the signed transaction to the Relayer API. + + + ```bash Split theme={null} + curl -X POST "https://relayer-v2.polymarket.com/submit" \ + -H "Content-Type: application/json" \ + -H "RELAYER_API_KEY: $RELAYER_API_KEY" \ + -H "RELAYER_API_KEY_ADDRESS: $RELAYER_API_KEY_ADDRESS" \ + -d '{ + "type": "WALLET", + "from": "", + "to": "0x00000000000Fb5C9ADea0298D729A0CB3823Cc07", + "nonce": "", + "signature": "", + "metadata": "Split Combo position", + "depositWalletParams": { + "depositWallet": "", + "deadline": "", + "calls": [ + // Use the final calls array from the previous steps. + // … + ] + } + }' + ``` + + ```bash Merge theme={null} + curl -X POST "https://relayer-v2.polymarket.com/submit" \ + -H "Content-Type: application/json" \ + -H "RELAYER_API_KEY: $RELAYER_API_KEY" \ + -H "RELAYER_API_KEY_ADDRESS: $RELAYER_API_KEY_ADDRESS" \ + -d '{ + "type": "WALLET", + "from": "", + "to": "0x00000000000Fb5C9ADea0298D729A0CB3823Cc07", + "nonce": "", + "signature": "", + "metadata": "Merge Combo positions", + "depositWalletParams": { + "depositWallet": "", + "deadline": "", + "calls": [ + // Use the final calls array from the previous steps. + // … + ] + } + }' + ``` + + + The response includes the relayer transaction ID. + + ```json theme={null} + { + "transactionID": "", + "state": "STATE_NEW" + } + ``` + + + + Poll the relayer transaction until it reaches `STATE_CONFIRMED` before relying on + the updated inventory. + + ```bash theme={null} + curl "https://relayer-v2.polymarket.com/v1/account/transactions/" \ + -H "RELAYER_API_KEY: $RELAYER_API_KEY" \ + -H "RELAYER_API_KEY_ADDRESS: $RELAYER_API_KEY_ADDRESS" + ``` + + ```json theme={null} + { + "transaction_id": "", + "transaction_hash": "", + "state": "STATE_CONFIRMED", + "error_msg": null + } + ``` + + Treat `STATE_FAILED` and `STATE_INVALID` as terminal failures. + + + + + +### Redeem Resolved Positions + +When a Combo position resolves, redeem the winning position to settle it back to +collateral. + + + + Use `client.redeemPositions(...)` with a Combo `positionId`. The SDK redeems the + available balance for that resolved position. + + ```ts theme={null} + const redeem = await client.redeemPositions({ + positionId: "", + }); + + const redeemOutcome = await redeem.wait(); + + // redeemOutcome.transactionHash identifies the confirmed redemption transaction. + ``` + + You can list resolved winning positions first, then redeem each one. + + ```ts theme={null} + import { ComboPositionStatus } from "@polymarket/client"; + + for await (const page of client.listComboPositions({ + status: ComboPositionStatus.ResolvedWin, + })) { + for (const position of page.items) { + const redeem = await client.redeemPositions({ + positionId: position.positionId, + }); + + await redeem.wait(); + } + } + ``` + + + + Use `client.redeem_positions(...)` with a Combo `position_id`. The SDK redeems + the available balance for that resolved position. + + ```python theme={null} + redeem = await client.redeem_positions( + position_id="", + ) + + redeem_outcome = await redeem.wait() + + # redeem_outcome.transaction_hash identifies the confirmed redemption transaction. + ``` + + You can list resolved winning positions first, then redeem each one. + + ```python theme={null} + positions = client.list_combo_positions(status="RESOLVED_WIN") + + async for position in positions.iter_items(): + redeem = await client.redeem_positions( + position_id=position.position_id, + ) + + await redeem.wait() + ``` + + + + Use the Relayer API to redeem resolved Combo positions by sending an ordered list + of encoded contract calls in one batch. The following steps assume you are using + a Deposit Wallet. + + + If you use a Safe or Poly Proxy wallet, use one of the SDKs instead because + those wallet integrations require wallet-specific signing and encoding. + + + | Contract | Address | + | --------------- | -------------------------------------------- | + | Router | `0x12121212006e4CD160D18e3f00711DA5c3372600` | + | PositionManager | `0x006F54F7f9A22e0000CC2AB60031000000ae9fEF` | + + + + First, determine whether `` has approved the Router as a + PositionManager ERC-1155 operator. If approval is already in place, skip this + step. + + ```solidity theme={null} + function setApprovalForAll(address operator, bool approved); + ``` + + Encode the approval call when needed. The approval call becomes the first object + in the final `calls` array. + + ```json theme={null} + [ + { + "target": "0x006F54F7f9A22e0000CC2AB60031000000ae9fEF", + "value": "0", + "data": "" + } + ] + ``` + + + + Set the Router inputs for the redemption. + + | Value | Source | + | -------------- | ------------------------------------- | + | `conditionId` | `` | + | `outcomeIndex` | `0` for YES, `1` for NO | + | `amount` | Shares to redeem, in share base units | + + The Router accepts `conditionId`, `outcomeIndex`, and `amount`, not `positionId`. + + + + The Router redeem function is: + + ```solidity theme={null} + function redeem(bytes31 conditionId, uint256 outcomeIndex, uint256 amount); + ``` + + Append the redeem call after the approval call from the previous step, if one was + needed. + + ```json Redeem Calls theme={null} + [ + // Include the approval call first when needed. + // … + { + "target": "0x12121212006e4CD160D18e3f00711DA5c3372600", + "value": "0", + "data": "" + } + ] + ``` + + + + Fetch a fresh `WALLET` nonce before each submission. + + ```bash theme={null} + curl -G "https://relayer-v2.polymarket.com/v1/account/transactions/params" \ + -H "RELAYER_API_KEY: $RELAYER_API_KEY" \ + -H "RELAYER_API_KEY_ADDRESS: $RELAYER_API_KEY_ADDRESS" \ + --data-urlencode "address=$RELAYER_API_KEY_ADDRESS" \ + --data-urlencode "type=WALLET" + ``` + + The response includes the nonce to sign with the transaction. + + ```json theme={null} + { + "address": "", + "nonce": "" + } + ``` + + + + Build the Deposit Wallet EIP-712 `Batch` typed data. + + ```json theme={null} + { + "domain": { + "name": "DepositWallet", + "version": "1", + "chainId": 137, + "verifyingContract": "" + }, + "types": { + "Call": [ + { "name": "target", "type": "address" }, + { "name": "value", "type": "uint256" }, + { "name": "data", "type": "bytes" } + ], + "Batch": [ + { "name": "wallet", "type": "address" }, + { "name": "nonce", "type": "uint256" }, + { "name": "deadline", "type": "uint256" }, + { "name": "calls", "type": "Call[]" } + ] + }, + "primaryType": "Batch", + "message": { + "wallet": "", + "nonce": "", + "deadline": "", + "calls": [ + // Use the final calls array from the previous steps. + // … + ] + } + } + ``` + + Sign the EIP-712 batch with your signer. Use the resulting signature as + `signature` in the relayer submission. + + + + Submit the signed transaction to the Relayer API. + + ```bash theme={null} + curl -X POST "https://relayer-v2.polymarket.com/submit" \ + -H "Content-Type: application/json" \ + -H "RELAYER_API_KEY: $RELAYER_API_KEY" \ + -H "RELAYER_API_KEY_ADDRESS: $RELAYER_API_KEY_ADDRESS" \ + -d '{ + "type": "WALLET", + "from": "", + "to": "0x00000000000Fb5C9ADea0298D729A0CB3823Cc07", + "nonce": "", + "signature": "", + "metadata": "Redeem Combo position", + "depositWalletParams": { + "depositWallet": "", + "deadline": "", + "calls": [ + // Use the final calls array from the previous steps. + // … + ] + } + }' + ``` + + The response includes the relayer transaction ID. + + ```json theme={null} + { + "transactionID": "", + "state": "STATE_NEW" + } + ``` + + + + Poll the relayer transaction until it reaches `STATE_CONFIRMED` before relying on + the redeemed balance. + + ```bash theme={null} + curl "https://relayer-v2.polymarket.com/v1/account/transactions/" \ + -H "RELAYER_API_KEY: $RELAYER_API_KEY" \ + -H "RELAYER_API_KEY_ADDRESS: $RELAYER_API_KEY_ADDRESS" + ``` + + ```json theme={null} + { + "transaction_id": "", + "transaction_hash": "", + "state": "STATE_CONFIRMED", + "error_msg": null + } + ``` + + Treat `STATE_FAILED` and `STATE_INVALID` as terminal failures. + + + + + +## Get Combo Markets + +Use the Combo markets catalog to retrieve active markets that can be used as +Combo legs. Markets are ordered by volume descending. + + + + Use `client.listComboMarkets(...)` to page through markets that can be used as + Combo legs. + + ```ts theme={null} + const paginator = client.listComboMarkets({ pageSize: 50 }); + + for await (const page of paginator) { + // page.items: ComboMarket[] + } + ``` + + Use `exclude` to omit markets you have already shown or selected. + + ```ts theme={null} + const paginator = client.listComboMarkets({ + exclude: selectedConditionIds, + pageSize: 50, + }); + ``` + + The SDK returns structured YES and NO outcomes. + + ```ts theme={null} + type ComboMarket = { + id: MarketId; + conditionId: CtfConditionId; + slug: string; + title: string; + outcomes: { + yes: { + label: string; + positionId: PositionId; + price: DecimalString; + }; + no: { + label: string; + positionId: PositionId; + price: DecimalString; + }; + }; + image: string; + volume: number; + tags: string[]; + }; + ``` + + + + Use `client.list_combo_markets(...)` to page through markets that can be used as + Combo legs. + + ```python theme={null} + paginator = client.list_combo_markets(page_size=50) + + async for market in paginator.iter_items(): + print(market.title, market.outcomes.yes.position_id) + ``` + + Use `exclude` to omit markets you have already shown or selected. + + ```python theme={null} + paginator = client.list_combo_markets( + exclude=selected_condition_ids, + page_size=50, + ) + ``` + + The SDK returns structured YES and NO outcomes with snake\_case fields. + + ```python theme={null} + yes_position_id = market.outcomes.yes.position_id + yes_price = market.outcomes.yes.price + no_position_id = market.outcomes.no.position_id + no_price = market.outcomes.no.price + ``` + + + + Fetch the first page of Combo-enabled markets. + + ```bash theme={null} + curl -G "https://combos-rfq-api.polymarket.com/v1/rfq/combo-markets" \ + --data-urlencode "limit=50" + ``` + + Use `cursor` to fetch the next page, and use `exclude` to omit markets you have + already shown or selected. + + ```bash theme={null} + curl -G "https://combos-rfq-api.polymarket.com/v1/rfq/combo-markets" \ + --data-urlencode "limit=50" \ + --data-urlencode "cursor=" \ + --data-urlencode "exclude=," + ``` + + The response includes markets and an opaque `next_cursor`. A `null` cursor means + there are no more pages. + + ```json theme={null} + { + "markets": [ + { + "id": "1897034", + "condition_id": "0x4cd7...110ff", + "position_ids": ["1012585...362880", "1012585...362881"], + "slug": "fifwc-mex-rsa-2026-06-11-mex", + "title": "Will Mexico win on 2026-06-11?", + "outcomes": ["Yes", "No"], + "outcome_prices": ["0.685", "0.315"], + "image": "https://...", + "volume": 330327.7128580074, + "tags": ["sports", "soccer", "games", "world-cup"] + } + ], + "next_cursor": "Mg" + } + ``` + + For each market, `position_ids`, `outcomes`, and `outcome_prices` are aligned by + array index. Index `0` is the YES outcome, and index `1` is the NO outcome. + + + +## Map Legs to Markets + +Market makers should build their own view of the markets that support Combos +before quote requests arrive. Combo-enabled markets expose a list of position +IDs with two entries: the first is the YES position ID and the second is the NO +position ID. These IDs identify the outcome positions your pricing system can map +back to market data. + + + + Fetch non-closed markets and index them by position ID in your own market data + store. + + ```ts theme={null} + for await (const page of client.listMarkets({ closed: false })) { + for (const market of page.items) { + for (const positionId of market.positionIds) { + marketByPositionId.set(positionId, market); + } + } + } + ``` + + You can also fetch markets by leg position ID on demand, but most market makers + will want this context ready before the **400 ms** quote window starts. + + ```ts theme={null} + const page = await client + .listMarkets({ + positionIds: event.legPositionIds, + }) + .firstPage(); + + const markets = page.items; + ``` + + + + Fetch non-closed markets and index them by position ID in your own market data + store. + + ```python theme={null} + async for market in client.list_markets(closed=False).iter_items(): + for position_id in market.position_ids: + market_by_position_id[position_id] = market + ``` + + You can also fetch markets by leg position ID on demand, but most market makers + will want this context ready before the **400 ms** quote window starts. + + ```python theme={null} + page = await client.list_markets( + position_ids=event.leg_position_ids, + ).first_page() + + markets = page.items + ``` + + + + Use Gamma `GET /markets` to resolve Combo leg position IDs into market metadata. + Build this mapping outside the quote path. + + ```bash theme={null} + curl -G "https://gamma-api.polymarket.com/markets" \ + --data-urlencode "closed=false" \ + --data-urlencode "limit=100" + ``` + + Index every returned market by `positionIds`. + + ```json theme={null} + { + "id": "", + "conditionId": "", + "question": "Will example happen?", + "positionIds": ["", ""] + } + ``` + + You can also resolve markets by leg position ID on demand, but avoid doing this + inside the **400 ms** quote window. + + ```bash theme={null} + curl -G "https://gamma-api.polymarket.com/markets" \ + --data-urlencode "position_ids=" \ + --data-urlencode "position_ids=" + ``` + + + +## Listen to Execution Updates + +Execution updates tell you what happened after one of your quotes was selected. +Use them to reconcile RFQ state, transaction hashes, and terminal execution +outcomes in your own systems. + + + + + + First, switch on `event.type` to handle execution updates from the same session + stream. + + ```ts theme={null} + switch (event.type) { + case "execution_update": + // event: RfqExecutionUpdateEvent + handleExecutionUpdate(event); + break; + + // … + } + ``` + + + + Then, inspect the execution update before reconciling the selected RFQ. Execution + updates are correlated by `rfqId`. + + ```ts theme={null} + type RfqExecutionUpdateEvent = { + type: "execution_update"; + rfqId: RfqId; + status: RfqExecutionStatus; + txHash?: TxHash; + }; + ``` + + where `RfqExecutionStatus` could be: + + | Status | Meaning | + | ------------------------------ | ------------------------------------------------- | + | `RfqExecutionStatus.Matched` | The quote was selected and handed off to execute. | + | `RfqExecutionStatus.Mined` | The execution transaction was mined. | + | `RfqExecutionStatus.Retrying` | Execution is being retried. | + | `RfqExecutionStatus.Confirmed` | Execution completed successfully. | + | `RfqExecutionStatus.Failed` | Execution failed. | + + + + Finally, persist the update and treat `RfqExecutionStatus.Confirmed` and + `RfqExecutionStatus.Failed` as terminal states. + + ```ts theme={null} + function handleExecutionUpdate(event: RfqExecutionUpdateEvent) { + storeExecutionUpdate(event); + + if (event.status === RfqExecutionStatus.Confirmed) { + markQuoteConfirmed(event.rfqId); + return; + } + + if (event.status === RfqExecutionStatus.Failed) { + markQuoteFailed(event.rfqId); + } + } + ``` + + + + + + + + First, use `isinstance(...)` to handle execution updates from the same session + stream. + + ```python theme={null} + from polymarket import RfqExecutionUpdateEvent + + + async for event in session: + if isinstance(event, RfqExecutionUpdateEvent): + handle_execution_update(event) + ``` + + + + Then, inspect the execution update before reconciling the selected RFQ. Execution + updates are correlated by `rfq_id`. + + ```python theme={null} + class RfqExecutionUpdateEvent: + type: "execution_update" + rfq_id: RfqId + status: RfqExecutionStatus + tx_hash: TransactionHash | None + ``` + + where `RfqExecutionStatus` could be: + + | Status | Meaning | + | ------------------------------ | ------------------------------------------------- | + | `RfqExecutionStatus.MATCHED` | The quote was selected and handed off to execute. | + | `RfqExecutionStatus.MINED` | The execution transaction was mined. | + | `RfqExecutionStatus.RETRYING` | Execution is being retried. | + | `RfqExecutionStatus.CONFIRMED` | Execution completed successfully. | + | `RfqExecutionStatus.FAILED` | Execution failed. | + + + + Finally, persist the update and treat `RfqExecutionStatus.CONFIRMED` and + `RfqExecutionStatus.FAILED` as terminal states. + + ```python theme={null} + from polymarket import RfqExecutionStatus, RfqExecutionUpdateEvent + + + def handle_execution_update(event: RfqExecutionUpdateEvent) -> None: + store_execution_update(event) + + if event.status is RfqExecutionStatus.CONFIRMED: + mark_quote_confirmed(event.rfq_id) + return + + if event.status is RfqExecutionStatus.FAILED: + mark_quote_failed(event.rfq_id) + ``` + + + + + + Listen for `RFQ_EXECUTION_UPDATE` messages on the RFQ WebSocket after one of your + quotes is selected. + + ```json theme={null} + { + "type": "RFQ_EXECUTION_UPDATE", + "rfq_id": "", + "status": "MINED", + "tx_hash": "" + } + ``` + + Execution updates are correlated by `rfq_id`. + + | Status | Meaning | + | ----------- | ------------------------------------------------- | + | `MATCHED` | The quote was selected and handed off to execute. | + | `MINED` | The execution transaction was mined. | + | `RETRYING` | Execution is being retried. | + | `CONFIRMED` | Execution completed successfully. | + | `FAILED` | Execution failed. | + + Treat `CONFIRMED` and `FAILED` as terminal states. + + + +## Listen to Trade Broadcasts + +Confirmed trade broadcasts tell connected market makers when any Combo RFQ trade +has completed successfully. Use them to build a public trade tape, update risk, +or reconcile market activity that was filled by another maker. + +Trade broadcasts are best-effort and may be replayed after reconnects. Deduplicate +them by RFQ ID: `rfqId` in TypeScript or `rfq_id` in Python and raw WebSocket +messages. + + + + + + First, switch on `event.type` to handle trade broadcasts from the same session + stream. + + ```ts theme={null} + switch (event.type) { + case "trade": + // event: RfqTradeEvent + handleTrade(event); + break; + + // … + } + ``` + + + + Then, inspect the confirmed trade before storing or applying it. Trade broadcasts + exclude maker identity and per-maker fill allocations. + + ```ts theme={null} + type RfqTradeEvent = { + type: "trade"; + rfqId: RfqId; + requesterId: RfqRequestorPublicId; + conditionId: ComboConditionId; + legPositionIds: PositionId[]; + direction: RfqDirection; + side: RfqSide.Yes; + price: DecimalString; + size: DecimalString; + executedAt: EpochMilliseconds; + }; + ``` + + `price` is the accepted blended price in pUSD per YES Combo share. `size` is the + matched Combo share size. Both values are normalized decimal strings. + + + + Finally, persist the trade by RFQ ID and execution timestamp for downstream + reconciliation. + + ```ts theme={null} + function handleTrade(event: RfqTradeEvent) { + storeComboTrade({ + rfqId: event.rfqId, + conditionId: event.conditionId, + legPositionIds: event.legPositionIds, + requesterId: event.requesterId, + price: event.price, + size: event.size, + executedAt: event.executedAt, + }); + } + ``` + + + + + + + + First, use `isinstance(...)` to handle trade broadcasts from the same session + stream. + + ```python theme={null} + from polymarket import RfqTradeEvent + + + async for event in session: + if isinstance(event, RfqTradeEvent): + handle_trade(event) + ``` + + + + Then, inspect the confirmed trade before storing or applying it. Trade broadcasts + exclude maker identity and per-maker fill allocations. + + ```python theme={null} + from decimal import Decimal + + + class RfqTradeEvent: + type: "trade" + rfq_id: RfqId + requester_id: RfqRequestorPublicId + condition_id: ComboConditionId + leg_position_ids: tuple[PositionId, ...] + direction: RfqDirection + side: RfqSide + price: Decimal + size: Decimal + executed_at: int + ``` + + `price` is the accepted blended price in pUSD per YES Combo share. `size` is the + matched Combo share size. Both values are `Decimal` instances. + + + + Finally, persist the trade by RFQ ID and execution timestamp for downstream + reconciliation. + + ```python theme={null} + from polymarket import RfqTradeEvent + + + def handle_trade(event: RfqTradeEvent) -> None: + store_combo_trade( + rfq_id=event.rfq_id, + condition_id=event.condition_id, + leg_position_ids=event.leg_position_ids, + requester_id=event.requester_id, + price=event.price, + size=event.size, + executed_at=event.executed_at, + ) + ``` + + + + + + Listen for `RFQ_TRADE` messages on the RFQ WebSocket after Combo executions are + confirmed. These messages are sent to authenticated quoter sessions and exclude + maker identity and per-maker fill allocations. + + ```json theme={null} + { + "type": "RFQ_TRADE", + "rfq_id": "", + "requester_id": "", + "condition_id": "", + "leg_position_ids": ["", ""], + "direction": "BUY", + "side": "YES", + "price_e6": "125000", + "size_e6": "800000", + "executed_at": 1780854786039 + } + ``` + + `price_e6` is the accepted blended price in 6-decimal base units, and `size_e6` + is the matched Combo share size in 6-decimal base units. + + + +## Handle Errors + +In this section, we will talk you through how to handle errors with the RFQ system. + + + + ### Open the RFQ Session + + Wrap `client.openRfqSession()` in `try`/`catch` and use + `OpenRfqSessionError.isError(…)` to narrow the error type. + + ```ts theme={null} + try { + const session = await client.openRfqSession(); + } catch (error) { + if (!OpenRfqSessionError.isError(error)) throw error; + + switch (error.name) { + case "TransportError": + // error: TransportError + break; + } + } + ``` + + ### Submit a Quote + + Wrap `event.quote(…)` in `try`/`catch` and use `RfqQuoteError.isError(…)` to + narrow the error type. + + ```ts theme={null} + try { + const reference = await event.quote({ price }); + // … + } catch (error) { + if (!RfqQuoteError.isError(error)) throw error; + + switch (error.name) { + case "RfqQuoteRejectedError": + // error: RfqQuoteRejectedError + // error.rfqId: RfqId + // error.code: RfqErrorCode | undefined + break; + case "SigningError": + // error: SigningError + break; + case "TimeoutError": + // error: TimeoutError + break; + case "TransportError": + // error: TransportError + break; + case "UserInputError": + // error: UserInputError + break; + } + } + ``` + + ### Cancel a Quote + + Wrap `session.cancelQuote(…)` in `try`/`catch` and use + `RfqCancelQuoteError.isError(…)` to narrow the error type. + + ```ts theme={null} + try { + const ack = await session.cancelQuote(reference); + // … + } catch (error) { + if (!RfqCancelQuoteError.isError(error)) throw error; + + switch (error.name) { + case "RfqCancelQuoteRejectedError": + // error: RfqCancelQuoteRejectedError + // error.rfqId: RfqId + // error.quoteId: RfqQuoteId + // error.code: RfqErrorCode | undefined + break; + case "TimeoutError": + // error: TimeoutError + break; + case "TransportError": + // error: TransportError + break; + } + } + ``` + + ### Confirm or Decline + + Wrap `event.confirm()` or `event.decline()` in `try`/`catch` and use + `RfqConfirmationError.isError(…)` to narrow the error type. + + ```ts theme={null} + try { + if (canStillFill) { + await event.confirm(); + } else { + await event.decline(); + } + } catch (error) { + if (!RfqConfirmationError.isError(error)) throw error; + + switch (error.name) { + case "RfqConfirmationRejectedError": + // error: RfqConfirmationRejectedError + // error.rfqId: RfqId + // error.quoteId: RfqQuoteId + // error.code: RfqErrorCode | undefined + break; + case "TimeoutError": + // error: TimeoutError + break; + case "TransportError": + // error: TransportError + break; + } + } + ``` + + + + ### Open the RFQ Session + + Wrap `client.open_rfq_session()` in `try`/`except` and catch SDK exception types. + + ```python theme={null} + from polymarket import TimeoutError, TransportError + + + try: + async with client.open_rfq_session() as session: + async for event in session: + ... + except TimeoutError as error: + # error: TimeoutError + ... + except TransportError as error: + # error: TransportError + ... + ``` + + ### Submit a Quote + + Wrap `event.quote(...)` in `try`/`except` and catch the typed RFQ rejection, + timeout, and transport errors. + + ```python theme={null} + from decimal import Decimal + + from polymarket import RfqQuoteRejectedError, TimeoutError, TransportError + + + try: + reference = await event.quote(price=Decimal("0.45")) + except RfqQuoteRejectedError as error: + # error.rfq_id: RfqId + # error.code: RfqErrorCode | None + ... + except TimeoutError as error: + # error: TimeoutError + ... + except TransportError as error: + # error: TransportError + ... + ``` + + ### Cancel a Quote + + Wrap `session.cancel_quote(...)` in `try`/`except` and catch the typed RFQ + cancellation rejection, timeout, and transport errors. + + ```python theme={null} + from polymarket import RfqCancelQuoteRejectedError, TimeoutError, TransportError + + + try: + ack = await session.cancel_quote(reference) + except RfqCancelQuoteRejectedError as error: + # error.rfq_id: RfqId + # error.quote_id: RfqQuoteId + # error.code: RfqErrorCode | None + ... + except TimeoutError as error: + # error: TimeoutError + ... + except TransportError as error: + # error: TransportError + ... + ``` + + ### Confirm or Decline + + Wrap `event.confirm()` or `event.decline()` in `try`/`except` and catch the typed + RFQ confirmation rejection, timeout, and transport errors. + + ```python theme={null} + from polymarket import RfqConfirmationRejectedError, TimeoutError, TransportError + + + try: + if can_still_fill: + await event.confirm() + else: + await event.decline() + except RfqConfirmationRejectedError as error: + # error.rfq_id: RfqId + # error.quote_id: RfqQuoteId + # error.code: RfqErrorCode | None + ... + except TimeoutError as error: + # error: TimeoutError + ... + except TransportError as error: + # error: TransportError + ... + ``` + + + + When a WebSocket command fails validation or cannot be applied, the RFQ system + sends `RFQ_ERROR`. + + ```json theme={null} + { + "type": "RFQ_ERROR", + "request_type": "RFQ_QUOTE", + "rfq_id": "", + "quote_id": "", + "code": "SUBMISSION_WINDOW_CLOSED", + "error": "submission window closed" + } + ``` + + Use `request_type`, `rfq_id`, and `quote_id` to correlate the error with the + command you sent. + + | Field | Description | + | -------------- | ----------------------------------------------- | + | `type` | Always `RFQ_ERROR` | + | `request_type` | Inbound command that failed, when parsed | + | `rfq_id` | RFQ ID, when present on the failed command | + | `quote_id` | Quote ID, when present on the failed command | + | `code` | Stable machine-readable error code | + | `error` | Human-readable detail for logging and debugging | + + The `request_type` value identifies the command that failed. + + | `request_type` | Failed command | + | --------------------------- | --------------------------------- | + | `RFQ_QUOTE` | Quote submission | + | `RFQ_QUOTE_CANCEL` | Quote cancellation | + | `RFQ_CONFIRMATION_RESPONSE` | Last Look confirmation or decline | + + Error codes include: + + | Code | Meaning | + | ------------------------------------------ | -------------------------------------------------------------- | + | `INVALID_MESSAGE` | Message JSON or message type is invalid | + | `UNAUTHORIZED_ROLE` | Message is not allowed for the authenticated gateway role | + | `ADDRESS_MISMATCH` | Message identity does not match the authenticated session | + | `UNKNOWN_RFQ` | RFQ ID is not active or no longer exists | + | `EXPIRED_RFQ` | RFQ has expired | + | `SUBMISSION_WINDOW_CLOSED` | Quote arrived after the submission window closed | + | `ALLOWANCE_VALIDATION_FAILED` | Maker allowance is insufficient for the quoted order | + | `BALANCE_VALIDATION_FAILED` | Maker balance is insufficient for the quoted order | + | `PRE_EXECUTION_BALANCE_RESERVATION_FAILED` | Balance reservation failed before execution | + | `INVALID_QUOTE` | Quote payload or signed order is invalid | + | `INVALID_RFQ_STATE` | RFQ is not in a state that accepts the requested command | + | `INVALID_CONFIRMATION` | Last Look confirmation payload is invalid | + | `MAKER_NOT_REQUIRED` | This quote maker is not required for last-look confirmation | + | `MAKER_ALREADY_RESPONDED` | This quote maker already responded to the confirmation request | + | `SERVICE_UNAVAILABLE` | RFQ service dependency is temporarily unavailable | + + Treat these errors as command-level failures. Keep the WebSocket session alive + unless the connection itself closes or authentication fails. + + diff --git a/PolymarketDocumentation-main/docs/market-makers/getting-started.md b/PolymarketDocumentation-main/docs/market-makers/getting-started.md new file mode 100644 index 00000000..7d38c648 --- /dev/null +++ b/PolymarketDocumentation-main/docs/market-makers/getting-started.md @@ -0,0 +1,241 @@ +> ## Documentation Index +> Fetch the complete documentation index at: https://docs.polymarket.com/llms.txt +> Use this file to discover all available pages before exploring further. + +# Getting Started + +> One-time setup for market making on Polymarket + +Before you can start market making, you need to complete these one-time setup steps — deposit pUSD to Polygon, deploy a wallet, approve tokens for trading, and generate API credentials. + + + + Market makers need pUSD on Polygon to fund their trading operations. + + | Method | Best For | Documentation | + | ----------------------- | ------------------------------------ | ---------------------------------------------------- | + | Bridge API | Automated deposits from other chains | [Bridge Deposit](/trading/bridge/deposit) | + | Direct Polygon transfer | Already have pUSD on Polygon | N/A | + | Cross-chain bridge | Large deposits from Ethereum | [Supported Assets](/trading/bridge/supported-assets) | + + ### Using the Bridge API + + ```typescript theme={null} + // Get bridge addresses for your Polymarket wallet + const deposit = await fetch("https://bridge.polymarket.com/deposit", { + method: "POST", + headers: { "Content-Type": "application/json" }, + body: JSON.stringify({ + address: "YOUR_POLYMARKET_WALLET_ADDRESS", + }), + }); + + // Returns bridge addresses for EVM, SVM, and BTC networks + const addresses = await deposit.json(); + // Send USDC to the appropriate address for your source chain + ``` + + + + ### EOA + + Standard Ethereum wallet. You pay for all onchain transactions (approvals, splits, merges, trade execution). + + ### Deposit Wallet + + Deposit wallets are the recommended wallet path for new API users. They are + deployed through Polymarket's relayer and use `POLY_1271` order signatures. + + See the [Deposit Wallet Guide](/trading/deposit-wallets) for the + wallet creation, approval, balance sync, and order-signing flow. + + ### Existing Safe Wallets + + Existing Gnosis Safe users can continue using their current wallet. Safe wallets + are deployed via Polymarket's relayer and support: + + * **Gasless transactions** — Polymarket pays gas fees for onchain operations + * **Contract wallet** — Enables advanced features like batched transactions + + For existing Safe integrations, deploy a Safe wallet using the Relayer Client: + + + ```typescript TypeScript theme={null} + import { RelayClient, RelayerTxType } from "@polymarket/builder-relayer-client"; + + const client = new RelayClient({ + host: "https://relayer-v2.polymarket.com/", + chain: 137, + signer, + relayerApiKey: process.env.RELAYER_API_KEY!, + relayerApiKeyAddress: process.env.RELAYER_API_KEY_ADDRESS!, + txType: RelayerTxType.SAFE, + }); + + // Deploy the Safe wallet + const response = await client.deploy(); + const result = await response.wait(); + console.log("Safe Address:", result?.proxyAddress); + ``` + + ```python Python theme={null} + from py_builder_relayer_client.client import RelayClient + + # client initialized with Relayer API Key credentials (see Gasless Transactions) + + # Deploy the Safe wallet + response = client.deploy() + result = response.wait() + print("Safe Address:", result.get("proxyAddress")) + ``` + + + + See [Gasless Transactions](/trading/gasless) for full Relayer Client setup + including local and remote signing configurations. + + + + + Before trading, you must approve the exchange contracts to spend your tokens. + + ### Required Approvals + + | Token | Spender | Purpose | + | -------------------- | --------------------- | ------------------------------ | + | pUSD | CTF Contract | Split pUSD into outcome tokens | + | CTF (outcome tokens) | CTF Exchange | Trade outcome tokens | + | CTF (outcome tokens) | Neg Risk CTF Exchange | Trade neg-risk market tokens | + + ### Contract Addresses + + ```typescript theme={null} + const ADDRESSES = { + pUSD: "0xC011a7E12a19f7B1f670d46F03B03f3342E82DFB", + CTF: "0x4D97DCd97eC945f40cF65F87097ACe5EA0476045", + CTF_EXCHANGE: "0xE111180000d2663C0091e4f400237545B87B996B", + NEG_RISK_CTF_EXCHANGE: "0xe2222d279d744050d28e00520010520000310F59", + NEG_RISK_ADAPTER: "0xd91E80cF2E7be2e162c6513ceD06f1dD0dA35296", + }; + ``` + + ### Approve via Relayer Client + + + ```typescript TypeScript theme={null} + import { ethers } from "ethers"; + import { Interface } from "ethers/lib/utils"; + + const erc20Interface = new Interface([ + "function approve(address spender, uint256 amount) returns (bool)", + ]); + + // Approve pUSD for CTF contract + const approveTx = { + to: ADDRESSES.pUSD, + data: erc20Interface.encodeFunctionData("approve", [ + ADDRESSES.CTF, + ethers.constants.MaxUint256, + ]), + value: "0", + }; + + const response = await client.execute([approveTx], "Approve pUSD for CTF"); + await response.wait(); + ``` + + ```python Python theme={null} + from web3 import Web3 + + pUSD = "0xC011a7E12a19f7B1f670d46F03B03f3342E82DFB" + CTF = "0x4D97DCd97eC945f40cF65F87097ACe5EA0476045" + MAX_UINT256 = 2**256 - 1 + + approve_tx = { + "to": pUSD, + "data": Web3().eth.contract( + address=pUSD, + abi=[{ + "name": "approve", + "type": "function", + "inputs": [ + {"name": "spender", "type": "address"}, + {"name": "amount", "type": "uint256"} + ], + "outputs": [{"type": "bool"}] + }] + ).encode_abi(abi_element_identifier="approve", args=[CTF, MAX_UINT256]), + "value": "0" + } + + response = client.execute([approve_tx], "Approve pUSD for CTF") + response.wait() + ``` + + + + + To place orders and access authenticated endpoints, you need L2 API credentials derived from your wallet. + + + ```typescript TypeScript theme={null} + import { ClobClient } from "@polymarket/clob-client-v2"; + + const client = new ClobClient({ + host: "https://clob.polymarket.com", + chain: 137, + signer, + }); + + // Derive API credentials from your wallet + const credentials = await client.createOrDeriveApiKey(); + console.log("API Key:", credentials.key); + console.log("Secret:", credentials.secret); + console.log("Passphrase:", credentials.passphrase); + ``` + + ```python Python theme={null} + from py_clob_client_v2 import ClobClient + import os + + private_key = os.getenv("PRIVATE_KEY") + + temp_client = ClobClient("https://clob.polymarket.com", key=private_key, chain_id=137) + credentials = temp_client.create_or_derive_api_key() + ``` + + ```rust Rust theme={null} + use std::str::FromStr; + use polymarket_client_sdk_v2::POLYGON; + use polymarket_client_sdk_v2::auth::{LocalSigner, Signer}; + use polymarket_client_sdk_v2::clob::{Client, Config}; + + let private_key = std::env::var("POLYMARKET_PRIVATE_KEY")?; + let signer = LocalSigner::from_str(&private_key)? + .with_chain_id(Some(POLYGON)); + + // The Rust SDK derives credentials and initializes in one step + let client = Client::new("https://clob.polymarket.com", Config::default())? + .authentication_builder(&signer) + .authenticate() + .await?; + ``` + + + See [Authentication](/trading/overview#authentication) for full details on signature types and REST API headers. + + + +*** + +## Next Steps + + + + Post limit orders and manage quotes + + + + Connect to real-time market data + + diff --git a/PolymarketDocumentation-main/docs/market-makers/inventory.md b/PolymarketDocumentation-main/docs/market-makers/inventory.md new file mode 100644 index 00000000..97a6e480 --- /dev/null +++ b/PolymarketDocumentation-main/docs/market-makers/inventory.md @@ -0,0 +1,350 @@ +> ## Documentation Index +> Fetch the complete documentation index at: https://docs.polymarket.com/llms.txt +> Use this file to discover all available pages before exploring further. + +# Inventory Management + +> Managing outcome token inventory for market making + +Market makers need outcome tokens on both sides to quote a market. The three core inventory operations are **splitting** pUSD into YES/NO token pairs, **merging** pairs back into pUSD, and **redeeming** winning tokens after resolution — all executed gaslessly through the Relayer Client. + + + For a full breakdown of how the Conditional Token Framework works, see [CTF + Overview](/trading/ctf/overview). This page focuses on the MM workflow using + the Relayer Client. + + +*** + +## Splitting pUSD into Tokens + +Split converts pUSD into equal amounts of YES and NO tokens — creating the inventory you need to quote both sides of a market. + + + ```typescript TypeScript theme={null} + import { ethers } from "ethers"; + import { Interface } from "ethers/lib/utils"; + import { RelayClient, Transaction } from "@polymarket/builder-relayer-client"; + + const CTF_COLLATERAL_ADAPTER_ADDRESS = + "0xAdA100Db00Ca00073811820692005400218FcE1f"; + const pUSD_ADDRESS = "0xC011a7E12a19f7B1f670d46F03B03f3342E82DFB"; + + const collateralAdapterInterface = new Interface([ + "function splitPosition(address collateralToken, bytes32 parentCollectionId, bytes32 conditionId, uint[] partition, uint amount)", + ]); + + // Split $1000 pUSD into YES/NO tokens + const amount = ethers.utils.parseUnits("1000", 6); // pUSD has 6 decimals + + const splitTx: Transaction = { + to: CTF_COLLATERAL_ADAPTER_ADDRESS, + data: collateralAdapterInterface.encodeFunctionData("splitPosition", [ + pUSD_ADDRESS, // collateralToken + ethers.constants.HashZero, // parentCollectionId (always zero for Polymarket) + conditionId, // conditionId from market + [1, 2], // partition: [YES, NO] + amount, + ]), + value: "0", + }; + + const response = await client.execute([splitTx], "Split pUSD into tokens"); + const result = await response.wait(); + console.log("Split completed:", result?.transactionHash); + ``` + + ```python Python theme={null} + from web3 import Web3 + + CTF_COLLATERAL_ADAPTER_ADDRESS = "0xAdA100Db00Ca00073811820692005400218FcE1f" + pUSD_ADDRESS = "0xC011a7E12a19f7B1f670d46F03B03f3342E82DFB" + + collateral_adapter_abi = [{ + "name": "splitPosition", + "type": "function", + "inputs": [ + {"name": "collateralToken", "type": "address"}, + {"name": "parentCollectionId", "type": "bytes32"}, + {"name": "conditionId", "type": "bytes32"}, + {"name": "partition", "type": "uint256[]"}, + {"name": "amount", "type": "uint256"} + ], + "outputs": [] + }] + + # Split $1000 pUSD into YES/NO tokens + amount = 1000 * 10**6 # pUSD has 6 decimals + + split_tx = { + "to": CTF_COLLATERAL_ADAPTER_ADDRESS, + "data": Web3().eth.contract( + address=CTF_COLLATERAL_ADAPTER_ADDRESS, abi=collateral_adapter_abi + ).encode_abi( + abi_element_identifier="splitPosition", + args=[ + pUSD_ADDRESS, + bytes(32), # parentCollectionId (always zero) + condition_id, # conditionId from market + [1, 2], # partition: [YES, NO] + amount, + ] + ), + "value": "0" + } + + response = client.execute([split_tx], "Split pUSD into tokens") + response.wait() + ``` + + +After splitting 1000 pUSD, you receive 1000 YES tokens and 1000 NO tokens. Your pUSD balance decreases by 1000. + +*** + +## Merging Tokens to pUSD + +Merge converts equal amounts of YES and NO tokens back into pUSD — useful for reducing exposure, exiting a market, or freeing up capital. + + + ```typescript TypeScript theme={null} + const collateralAdapterInterface = new Interface([ + "function mergePositions(address collateralToken, bytes32 parentCollectionId, bytes32 conditionId, uint[] partition, uint amount)", + ]); + + // Merge 500 YES + 500 NO back to 500 pUSD + const amount = ethers.utils.parseUnits("500", 6); + + const mergeTx: Transaction = { + to: CTF_COLLATERAL_ADAPTER_ADDRESS, + data: collateralAdapterInterface.encodeFunctionData("mergePositions", [ + pUSD_ADDRESS, + ethers.constants.HashZero, + conditionId, + [1, 2], + amount, + ]), + value: "0", + }; + + const response = await client.execute([mergeTx], "Merge tokens to pUSD"); + await response.wait(); + ``` + + ```python Python theme={null} + merge_abi = [{ + "name": "mergePositions", + "type": "function", + "inputs": [ + {"name": "collateralToken", "type": "address"}, + {"name": "parentCollectionId", "type": "bytes32"}, + {"name": "conditionId", "type": "bytes32"}, + {"name": "partition", "type": "uint256[]"}, + {"name": "amount", "type": "uint256"} + ], + "outputs": [] + }] + + # Merge 500 YES + 500 NO back to 500 pUSD + amount = 500 * 10**6 + + merge_tx = { + "to": CTF_COLLATERAL_ADAPTER_ADDRESS, + "data": Web3().eth.contract( + address=CTF_COLLATERAL_ADAPTER_ADDRESS, abi=merge_abi + ).encode_abi( + abi_element_identifier="mergePositions", + args=[pUSD_ADDRESS, bytes(32), condition_id, [1, 2], amount] + ), + "value": "0" + } + + response = client.execute([merge_tx], "Merge tokens to pUSD") + response.wait() + ``` + + +After merging 500 of each, your YES and NO balances decrease by 500 and your pUSD balance increases by 500. + +*** + +## Redeeming After Resolution + +Once a market resolves, redeem winning tokens for pUSD. Each winning token is worth $1 — losing tokens redeem for $0. + +### Check Resolution Status + + + ```typescript TypeScript theme={null} + const market = await clobClient.getMarket(conditionId); + if (market.closed) { + const winningToken = market.tokens.find((t) => t.winner); + console.log("Winning outcome:", winningToken?.outcome); + } + ``` + + ```python Python theme={null} + market = clob_client.get_market(condition_id) + if market.get("closed"): + winning = next(t for t in market["tokens"] if t.get("winner")) + print("Winning outcome:", winning["outcome"]) + ``` + + ```rust Rust theme={null} + let market = clob_client.market(condition_id).await?; + if market.closed { + if let Some(winner) = market.tokens.iter().find(|t| t.winner) { + println!("Winning outcome: {}", winner.outcome); + } + } + ``` + + +### Redeem Winning Tokens + + + ```typescript TypeScript theme={null} + const collateralAdapterInterface = new Interface([ + "function redeemPositions(address collateralToken, bytes32 parentCollectionId, bytes32 conditionId, uint[] indexSets)", + ]); + + const redeemTx: Transaction = { + to: CTF_COLLATERAL_ADAPTER_ADDRESS, + data: collateralAdapterInterface.encodeFunctionData("redeemPositions", [ + pUSD_ADDRESS, + ethers.constants.HashZero, + conditionId, + [1, 2], // Redeem both YES and NO (only winners pay out) + ]), + value: "0", + }; + + const response = await client.execute([redeemTx], "Redeem winning tokens"); + await response.wait(); + ``` + + ```python Python theme={null} + redeem_abi = [{ + "name": "redeemPositions", + "type": "function", + "inputs": [ + {"name": "collateralToken", "type": "address"}, + {"name": "parentCollectionId", "type": "bytes32"}, + {"name": "conditionId", "type": "bytes32"}, + {"name": "indexSets", "type": "uint256[]"} + ], + "outputs": [] + }] + + redeem_tx = { + "to": CTF_COLLATERAL_ADAPTER_ADDRESS, + "data": Web3().eth.contract( + address=CTF_COLLATERAL_ADAPTER_ADDRESS, abi=redeem_abi + ).encode_abi( + abi_element_identifier="redeemPositions", + args=[pUSD_ADDRESS, bytes(32), condition_id, [1, 2]] + ), + "value": "0" + } + + response = client.execute([redeem_tx], "Redeem winning tokens") + response.wait() + ``` + + +*** + +## Negative Risk Markets + +Multi-outcome markets use the Neg Risk CTF Exchange for trading and the Neg Risk CTF Collateral Adapter for pUSD-native split, merge, and redeem actions. Split and merge work the same way, but use different contract addresses: + +```typescript theme={null} +const NEG_RISK_CTF_EXCHANGE = "0xe2222d279d744050d28e00520010520000310F59"; +const NEG_RISK_CTF_COLLATERAL_ADAPTER = + "0xadA2005600Dec949baf300f4C6120000bDB6eAab"; +``` + +See [Negative Risk Markets](/advanced/neg-risk) for details on how multi-outcome token mechanics differ. + +*** + +## Inventory Strategies + +### Before Quoting + +1. Check market metadata via the [Gamma API](/market-data/fetching-markets) +2. Split sufficient pUSD to cover your expected quoting size +3. Set token approvals if not already done (see [Getting Started](/market-makers/getting-started)) + +### During Trading + +* **Skew quotes** when inventory becomes imbalanced on one side +* **Merge excess tokens** to free up capital for other markets +* **Split more** when inventory on either side runs low + +### After Resolution + +1. Cancel all open orders in the market +2. Wait for resolution to complete +3. Redeem winning tokens +4. Merge any remaining YES/NO pairs + +*** + +## Batch Operations + +Execute multiple inventory operations in a single relayer call for efficiency: + +```typescript theme={null} +const transactions: Transaction[] = [ + // Split on Market A + { + to: CTF_COLLATERAL_ADAPTER_ADDRESS, + data: collateralAdapterInterface.encodeFunctionData("splitPosition", [ + pUSD_ADDRESS, + ethers.constants.HashZero, + conditionIdA, + [1, 2], + ethers.utils.parseUnits("1000", 6), + ]), + value: "0", + }, + // Split on Market B + { + to: CTF_COLLATERAL_ADAPTER_ADDRESS, + data: collateralAdapterInterface.encodeFunctionData("splitPosition", [ + pUSD_ADDRESS, + ethers.constants.HashZero, + conditionIdB, + [1, 2], + ethers.utils.parseUnits("1000", 6), + ]), + value: "0", + }, +]; + +const response = await client.execute(transactions, "Batch inventory setup"); +await response.wait(); +``` + +*** + +## Next Steps + + + + How the Conditional Token Framework works under the hood + + + + Detailed split function parameters and prerequisites + + + + Detailed merge function parameters + + + + Relayer Client setup and configuration + + diff --git a/PolymarketDocumentation-main/docs/market-makers/liquidity-rewards.md b/PolymarketDocumentation-main/docs/market-makers/liquidity-rewards.md new file mode 100644 index 00000000..80126ab3 --- /dev/null +++ b/PolymarketDocumentation-main/docs/market-makers/liquidity-rewards.md @@ -0,0 +1,182 @@ +> ## Documentation Index +> Fetch the complete documentation index at: https://docs.polymarket.com/llms.txt +> Use this file to discover all available pages before exploring further. + +# Liquidity Rewards + +> Earn rewards for providing liquidity on Polymarket + +By posting resting limit orders, liquidity providers (makers) are automatically eligible for Polymarket's incentive program. Rewards are distributed directly to maker addresses daily at midnight UTC. + +The program is designed to: + +* Catalyze liquidity across all markets +* Encourage liquidity throughout a market's entire lifecycle +* Motivate passive, balanced quoting tight to a market's midpoint +* Encourage trading activity +* Discourage blatantly exploitative behaviors + + + The minimum reward payout is **\$1**; amounts below this will not be paid. + + + + Both `min_incentive_size` and `max_incentive_spread` can be fetched alongside + full market objects via the CLOB API and [Markets + API](/market-data/fetching-markets). Reward allocations for an epoch can also + be fetched via the Markets API. + + +*** + +## Methodology + +Liquidity providers are rewarded based on a formula that rewards participation in markets, boosts two-sided depth (single-sided orders still score), and tighter spread vs the size-cutoff-adjusted midpoint. Each market configures a max spread and min size cutoff within which orders are considered. The average of rewards earned is determined by the relative share of each participant's Qn in market m. + +### Variables + +| Variable | Description | +| -------------- | ---------------------------------------------------------------- | +| S | Order position scoring function | +| v | Max spread from midpoint (in cents) | +| s | Spread from size-cutoff-adjusted midpoint | +| b | In-game multiplier | +| m | Market | +| m' | Market complement (i.e. NO if m = YES) | +| n | Trader index | +| u | Sample index | +| c | Scaling factor (currently 3.0 on all markets) | +| Qne | Point total for book one for a sample | +| Qno | Point total for book two for a sample | +| Spread% | Distance from midpoint (bps or relative) for order n in market m | +| BidSize | Share-denominated quantity of bid | +| AskSize | Share-denominated quantity of ask | + +*** + +## Equations + +### 1. Order Scoring Function + +Quadratic scoring rule for an order based on position between the adjusted midpoint and the minimum qualifying spread: + +$S(v,s)= (\frac{v-s}{v})^2 \cdot b$ + +### 2. First Market Side Score + +$Q_{one}= S(v,Spread_{m_1}) \cdot BidSize_{m_1} + S(v,Spread_{m_2}) \cdot BidSize_{m_2} + \dots $ +$ + S(v, Spread_{m^\prime_1}) \cdot AskSize_{m^\prime_1} + S(v, Spread_{m^\prime_2}) \cdot AskSize_{m^\prime_2}$ + +### 3. Second Market Side Score + +$Q_{two}= S(v,Spread_{m_1}) \cdot AskSize_{m_1} + S(v,Spread_{m_2}) \cdot AskSize_{m_2} + \dots $ +$ + S(v, Spread_{m^\prime_1}) \cdot BidSize_{m^\prime_1} + S(v, Spread_{m^\prime_2}) \cdot BidSize_{m^\prime_2}$ + +### 4. Minimum Score + +Boosts two-sided liquidity by taking the minimum of Qne and Qno, while still rewarding single-sided liquidity at a reduced rate (divided by c). + +**If midpoint is in range \[0.10, 0.90]** — single-sided liquidity can score: + +$Q_{\min} = \max(\min({Q_{one}, Q_{two}}), \max(Q_{one}/c, Q_{two}/c))$ + +**If midpoint is in range \[0, 0.10) or (0.90, 1.0]** — liquidity must be double-sided to score: + +$Q_{\min} = \min({Q_{one}, Q_{two}})$ + +### 5. Normalized Score + +Qmin of a market maker divided by the sum of all Qmin across market makers in a given sample: + +$Q_{normal} = \frac{Q_{min}}{\sum_{n=1}^{N}{(Q_{min})_n}}$ + +### 6. Epoch Score + +Sum of all Qnormal for a trader across all samples in an epoch: + +$Q_{epoch} = \sum_{u=1}^{10,080}{(Q_{normal})_u}$ + +### 7. Final Score + +Normalizes Qepoch by dividing by the sum of all market makers' Qepoch in a given epoch. This value is multiplied by the rewards available for the market to get a trader's reward: + +$Q_{final}=\frac{Q_{epoch}}{\sum_{n=1}^{N}{(Q_{epoch})_n}}$ + +*** + +## Worked Example + +Assume an adjusted market midpoint of 0.50 and a max spread config of 3 cents for both m and m'. + +### Step 2 - First Side Score + +A trader has the following open orders: + +* 100Q bid on m @ 0.49 (spread = 1 cent) +* 200Q bid on m @ 0.48 (spread = 2 cents) +* 100Q ask on m' @ 0.51 (spread = 1 cent) + +$$ +Q_{ne} = \left( \frac{(3-1)}{3} \right)^2 \cdot 100 + \left( \frac{(3-2)}{3} \right)^2 \cdot 200 + \left( \frac{(3-1)}{3} \right)^2 \cdot 100 +$$ + +Qne is calculated every minute using random sampling. + +### Step 3 - Second Side Score + +The same trader also has: + +* 100Q bid on m @ 0.485 (spread = 1.5 cents) +* 100Q bid on m' @ 0.48 (spread = 2 cents) +* 200Q ask on m' @ 0.505 (spread = 0.5 cents) + +$$ +Q_{no} = \left( \frac{(3-1.5)}{3} \right)^2 \cdot 100 + \left( \frac{(3-2)}{3} \right)^2 \cdot 100 + \left( \frac{(3-.5)}{3} \right)^2 \cdot 200 +$$ + +Qno is calculated every minute using random sampling. + +### Steps 4-7 + +4. Take the minimum of Qne and Qno (with single-sided adjustment if midpoint is in \[0.10, 0.90]) +5. Normalize against all other market makers in the sample +6. Sum across all 10,080 samples in the epoch +7. Normalize again to get final reward share + +*** + +## World Cup 2026 — Liquidity Incentive Program + +Polymarket is distributing liquidity incentives for World Cup 2026 markets from June 11 through July 19, 2026. Rewards are split into **Pre** (pre-game) and **Live** (in-play) periods per game. + + + The values below are configured reward caps. Actual payouts depend on eligible + quoting and the reward methodology above. + + +### Stage Pools + +| Stage | Pre \$/Game | Live \$/Game | Total \$/Game | +| --------------------- | ----------- | ------------ | ------------- | +| Group Stage | \$2,139 | \$3,971 | \$6,110 | +| Group Stage — Marquee | \$3,754 | \$6,971 | \$10,725 | +| Round of 32 | \$4,778 | \$8,872 | \$13,650 | +| Round of 16 | \$6,370 | \$11,830 | \$18,200 | +| Quarterfinals | \$9,442 | \$17,533 | \$26,975 | +| Semifinals | \$13,423 | \$24,927 | \$38,350 | +| Third Place | \$5,460 | \$10,140 | \$15,600 | +| Final | \$18,200 | \$33,800 | \$52,000 | + +*** + +## Next Steps + + + + Order entry and quoting best practices + + + + Earn USDC rebates on eligible crypto and sports markets + + diff --git a/PolymarketDocumentation-main/docs/market-makers/maker-rebates.md b/PolymarketDocumentation-main/docs/market-makers/maker-rebates.md new file mode 100644 index 00000000..0b06b098 --- /dev/null +++ b/PolymarketDocumentation-main/docs/market-makers/maker-rebates.md @@ -0,0 +1,169 @@ +> ## Documentation Index +> Fetch the complete documentation index at: https://docs.polymarket.com/llms.txt +> Use this file to discover all available pages before exploring further. + +# Maker Rebates Program + +> Earn daily pUSD rebates by providing liquidity on Polymarket + +Polymarket charges taker fees across multiple market categories. Fees are determined by the protocol at match time and fund a **Maker Rebates** program that pays daily pUSD rebates to liquidity providers. + +*** + +## Why Maker Rebates + +Deeper liquidity means tighter spreads, lower price impact, more reliable fills, and greater resilience during volatility. Maker Rebates incentivize **consistent, competitive quoting** so everyone gets a better trading experience. + +*** + +## How Maker Rebates Work + +* **Paid daily in pUSD:** Rebates are calculated and distributed every day. +* **Performance-based:** You earn based on the share of liquidity you provided that actually got taken. + +### Eligibility + +Place orders that add liquidity to the book and get filled (i.e., your liquidity is taken by another trader). + +### Payment + +Rebates are paid daily in pUSD, directly to your wallet. A minimum accrued rebate of **\$1 pUSD** is required for a payout. + +*** + +## Funding + +Maker Rebates are funded by taker fees collected in eligible markets. A percentage of these fees are redistributed to makers who keep the markets liquid. The rebate percentage differs by market type. + +| Category | Maker Rebate | Distribution Method | +| --------------- | ------------ | ------------------- | +| Crypto | 20% | Fee-curve weighted | +| Sports | 15% | Fee-curve weighted | +| Finance | 25% | Fee-curve weighted | +| Politics | 25% | Fee-curve weighted | +| Economics | 25% | Fee-curve weighted | +| Culture | 25% | Fee-curve weighted | +| Weather | 25% | Fee-curve weighted | +| Other / General | 25% | Fee-curve weighted | +| Mentions | 25% | Fee-curve weighted | +| Tech | 25% | Fee-curve weighted | +| Geopolitics | — | Fee-free | + + + Polymarket collects taker fees in eligible markets across all fee-enabled categories. + The rebate percentage is at the sole discretion of Polymarket + and may change over time. + + +*** + +## Fee-Curve Weighted Rebates + +Rebates are distributed using the **same formula as taker fees**. This ensures makers are rewarded proportionally to the fee value their liquidity generates. + +For each filled maker order: + +```text theme={null} +fee_equivalent = C × feeRate × p × (1 - p) +``` + +Where **C** = number of shares traded and **p** = price of the shares. The fee parameters differ by market type: + +| Category | Taker Fee Rate | Maker Fee Rate | +| --------------- | -------------- | -------------- | +| Crypto | 0.07 | 0 | +| Sports | 0.05 | 0 | +| Finance | 0.04 | 0 | +| Politics | 0.04 | 0 | +| Economics | 0.05 | 0 | +| Culture | 0.05 | 0 | +| Weather | 0.05 | 0 | +| Other / General | 0.05 | 0 | +| Mentions | 0.04 | 0 | +| Tech | 0.04 | 0 | +| Geopolitics | 0 | 0 | + +Your daily rebate: + +```text theme={null} +rebate = (your_fee_equivalent / total_fee_equivalent) * rebate_pool +``` + +Totals are calculated per market, so you only compete with other makers in the same market. + +*** + +## Taker Fee Structure + +Taker fees are calculated in pUSD and vary based on the share price. The fee amount in pUSD is symmetric around 50% probability — a trade at 30¢ incurs the same dollar fee as a trade at 70¢. + + +
+