Autonomous Polymarket prediction market trading agent. Scans markets, evaluates probabilities with LLM, sizes positions with Kelly criterion, and executes trades via CLOB API. Use when user wants to trade on Polymarket, set up automated prediction market trading, or build a trading bot. Supports cron-based autonomous operation, P&L tracking, and budget management.
---
name: polymarket-auto-trader
description: Autonomous Polymarket prediction market trading agent. Scans markets, evaluates probabilities with LLM, sizes positions with Kelly criterion, and executes trades via CLOB API. Use when user wants to trade on Polymarket, set up automated prediction market trading, or build a trading bot. Supports cron-based autonomous operation, P&L tracking, and budget management.
metadata: {"openclaw": {"requires": {"env": ["PRIVATE_KEY", "LLM_API_KEY"]}, "primaryEnv": "LLM_API_KEY", "homepage": "https://github.com/srikanthbellary"}}
---
# Polymarket Auto-Trader
Fully autonomous prediction market trading agent for Polymarket. Evaluates markets using LLM probability estimation, sizes positions with Kelly criterion, and executes trades via the Polymarket CLOB API from a non-US VPS.
## Prerequisites
- **Non-US VPS** — Polymarket blocks US IPs. Use DigitalOcean Amsterdam, Hetzner EU, etc.
- **Polygon wallet** with USDC.e (bridged USDC, NOT native USDC)
- **MATIC** for gas (~0.1 MATIC sufficient for hundreds of trades)
- **Anthropic API key** (uses Haiku at ~$0.001/evaluation)
## Setup
### 1. VPS Environment
SSH into your non-US VPS and run:
```bash
python3 {baseDir}/scripts/setup_vps.sh
```
Or manually:
```bash
apt update && apt install -y python3 python3-venv
python3 -m venv /opt/trader
/opt/trader/bin/pip install py-clob-client python-dotenv web3 requests
```
### 2. Configuration
Create `/opt/trader/app/.env`:
```
PRIVATE_KEY=<your-polygon-wallet-private-key>
LLM_API_KEY=<your-anthropic-api-key>
```
### 3. Blockchain Approvals
Before trading, approve USDC.e and CTF tokens for Polymarket contracts. Run:
```bash
python3 {baseDir}/scripts/approve_contracts.py
```
Required approvals (6 total):
- USDC.e → CTF Exchange, Neg Risk Exchange, Neg Risk Adapter
- CTF → CTF Exchange, Neg Risk Exchange, Neg Risk Adapter
### 4. Deploy Trading Script
```bash
cp {baseDir}/scripts/run_trade.py /opt/trader/app/
cp {baseDir}/scripts/pnl_tracker.py /opt/trader/app/
```
### 5. Cron Automation
```bash
crontab -e
# Add: */10 * * * * cd /opt/trader/app && /opt/trader/bin/python3 run_trade.py >> cron.log 2>&1
```
## How It Works
1. **Market Scan** — Fetches active markets from Gamma API, filters by liquidity and time horizon
2. **LLM Evaluation** — Asks Claude Haiku to estimate true probability for each market
3. **Edge Detection** — Compares LLM fair value vs market price (min 5% edge threshold)
4. **Kelly Sizing** — Half-Kelly criterion with 25% max position size cap
5. **Order Execution** — Places limit orders via CLOB API with GTC (good-till-cancelled)
6. **Dedup** — Tracks all trades in `trades.jsonl`, skips already-traded markets
7. **Budget Control** — Tracks LLM inference costs separately from trading capital
## Trading Parameters
Configurable in `run_trade.py`:
- `EDGE_THRESHOLD` — Minimum edge to trade (default: 0.05 = 5%)
- `MIN_SHARES` — Minimum order size (Polymarket requires ≥5 shares)
- Bankroll allocation: 80% usable, 25% max per trade, 30% cap per single position
- Market horizon: Prioritizes markets ending within 30 days
## Monitoring
Check P&L anytime:
```bash
python3 /opt/trader/app/pnl_tracker.py
```
Check recent activity:
```bash
tail -50 /opt/trader/app/cron.log
```
## Key Technical Details
- **Wallet type:** EOA (signature_type=0), NOT proxy wallet
- **Token:** USDC.e (`0x2791Bca1f2de4661ED88A30C99A7a9449Aa84174`), not native USDC
- **Neg-risk markets** (elections, sports leagues) require USDC.e approval for Neg Risk Adapter (`0xd91E80cF2E7be2e162c6513ceD06f1dD0dA35296`)
- **US geoblock** — All API calls must originate from non-US IP. VPN insufficient; use actual non-US VPS.
## Cost
- LLM inference: ~$0.001 per market evaluation (Haiku)
- Typical cycle (40 evals): ~$0.04
- Gas: negligible on Polygon (~$0.001 per trade)
## ⚠️ Security Considerations
- **Use a DEDICATED wallet with minimal funds.** Never use your main wallet's private key. Create a fresh wallet and fund it only with what you're willing to risk.
- **PRIVATE_KEY is stored on disk** in `.env`. Harden your VPS: strict file permissions (`chmod 600 .env`), no shared access, firewall, SSH keys only.
- **MAX_UINT approvals** are standard in DeFi but grant broad spending rights. The approved contracts are official Polymarket contracts. Review addresses in `references/contract-addresses.md` before running.
- **Test with tiny amounts first** ($5-10) before scaling up.
- **Monitor actively** — check `cron.log` and run `pnl_tracker.py` regularly.
- **LLM_API_KEY billing** — each cycle costs ~$0.04 (Haiku). Set billing alerts on your Anthropic account.
- **This is autonomous trading software.** Bugs or market conditions can cause losses. Use at your own risk.
## References
- See `references/polymarket-api.md` for full CLOB API documentation
- See `references/contract-addresses.md` for all Polygon contract addresses
don't have the plugin yet? install it then click "run inline in claude" again.
added explicit intent, mapped external connections with auth details, broke setup into numbered steps with input/output contracts, extracted implicit decision branches (VPS geocheck, approval retry logic, error handling), clarified output data formats and file schemas, and defined user-facing outcome signals for successful deployment.
fully autonomous prediction market trading agent for Polymarket. evaluates markets using LLM probability estimation, sizes positions with Kelly criterion, and executes trades via the Polymarket CLOB API from a non-US VPS.
use this skill to set up an autonomous trading bot that scans Polymarket prediction markets, evaluates fair value using Claude Haiku, detects pricing edges (5%+ mispricing), and executes limit orders via the CLOB API. the bot runs on cron (default every 10 minutes), applies Kelly criterion position sizing with safety caps, deduplicates trades to avoid re-trading the same market, and tracks P&L separately from inference costs. run this when you want hands-off prediction market trading, need to backtest LLM-driven market evaluation, or want to test autonomous DeFi execution on Polygon without US-based IP.
external connections:
https://clob.polymarket.com)https://polygon-rpc.comenvironment variables (required):
PRIVATE_KEY , Polygon wallet private key (EOA only, not proxy wallet). funds must be on Polygon network. store in .env with strict permissions (chmod 600).LLM_API_KEY , Anthropic API key for Claude Haiku. set billing alerts at ~$0.04 per 10-minute cycle (40 market evals).wallet prerequisites:
0x2791Bca1f2de4661ED88A30C99A7a9449Aa84174), NOT native USDC. minimum ~$100 recommended for meaningful position sizing.local files (created during setup):
.env , configuration file with PRIVATE_KEY and LLM_API_KEYtrades.jsonl , append-only log of all executed trades for deduplicationcron.log , stdout/stderr from cron runsreferences/contract-addresses.md , verified Polygon contract addresses (external reference, must match official docs)references/polymarket-api.md , CLOB API endpoint specs (external reference)rent a VPS outside US with SSH access. note IP geolocation. SSH in and run:
apt update && apt install -y python3 python3-venv git curl
python3 -m venv /opt/trader
/opt/trader/bin/pip install py-clob-client python-dotenv web3 requests
input: VPS IP verified as non-US (use curl ifconfig.me to verify)
output: Python venv at /opt/trader with dependencies installed; confirm with /opt/trader/bin/python3 --version
SSH into VPS and create /opt/trader/app/.env:
mkdir -p /opt/trader/app
cat > /opt/trader/app/.env << 'EOF'
PRIVATE_KEY=0x<your-polygon-wallet-private-key>
LLM_API_KEY=sk-ant-<your-anthropic-key>
EOF
chmod 600 /opt/trader/app/.env
replace values with your actual keys. validate PRIVATE_KEY is valid Polygon EOA (not proxy wallet).
input: polygon wallet private key (string), anthropic API key (string)
output: .env file on disk with 600 permissions; confirm with ls -la /opt/trader/app/.env
copy the approval script to VPS and run:
python3 /opt/trader/app/approve_contracts.py
this script approves USDC.e and CTF token spending to three Polymarket contracts: CTF Exchange (0x4bCE41985E38a9B94381f7c12dF2c3fdD0B67Cd1), Neg Risk Exchange (0xC5d563A36AE78145C45a50134d48a1215220f80a), Neg Risk Adapter (0xd91E80cF2E7be2e162c6513ceD06f1dD0dA35296). approvals use unlimited (MAX_UINT) to avoid re-approval per trade. script polls for confirmation (wait up to 2 minutes per approval).
input: .env file with PRIVATE_KEY and RPC endpoint (default Polygon public RPC); USDC.e balance required (~0.001 minimum for gas)
output: 6 blockchain transactions confirmed (2 tokens x 3 contracts); confirm with python3 -c "from web3 import Web3; w3=Web3(...); print(w3.eth.get_balance(YOUR_ADDR))" showing reduced MATIC balance
edge case: if approval tx reverts, likely cause is insufficient gas; fund VPS wallet with 0.5 MATIC and retry.
copy main trading logic and monitoring tools:
cp {baseDir}/scripts/run_trade.py /opt/trader/app/
cp {baseDir}/scripts/pnl_tracker.py /opt/trader/app/
input: source repo with scripts
output: two executable Python files in /opt/trader/app/; confirm with ls -la /opt/trader/app/run_trade.py
run the trading script once manually to verify wallet, approvals, and market connectivity:
cd /opt/trader/app && /opt/trader/bin/python3 run_trade.py
watch for:
input: .env with valid keys, blockchain approvals already executed output: console logs showing market fetch, LLM evaluation, Kelly sizing, and order results; no exceptions. edge case: if you see "network timeout" or "US IP detected", check VPS geolocation and restart.
add cron job to execute script every 10 minutes:
crontab -e
add line:
*/10 * * * * cd /opt/trader/app && /opt/trader/bin/python3 run_trade.py >> cron.log 2>&1
save and verify with crontab -l.
input: crontab access on VPS, run_trade.py deployed
output: cron job scheduled; confirm with crontab -l and check that cron.log grows every 10 minutes with tail -f /opt/trader/app/cron.log
edge case: if cron fails silently, check cron logs with journalctl -u cron and verify .env permissions.
run anytime to check performance:
python3 /opt/trader/app/pnl_tracker.py
reads trades.jsonl and outputs realized/unrealized P&L, total fees, cost per trade, and Sharpe ratio estimate.
input: trades.jsonl from previous executions (empty on first run)
output: console report with format: "realized_pnl=
if user has non-US VPS with static IP: deploy directly to that VPS using procedure steps 1-7.
else (no VPS available): rent one from DigitalOcean, Hetzner, Linode, or AWS in a non-US region (Amsterdam, Frankfurt, Singapore verified). do not use VPN or proxy on a US VPS; Polymarket blocks Tor and residential proxies.
if wallet has USDC.e balance and MATIC for gas (>0.1): proceed to blockchain approvals (step 3).
else: bridge USDC to Polygon via official bridge (polygon.technology) and fund MATIC via Polygon faucet or exchange.
if approval transactions are pending after 2 minutes:
check tx status on Polygonscan; if stuck, increase gas price via approve_contracts.py --gas-price=100 (gwei) and resubmit.
else if approval reverts: error is usually insufficient MATIC. fund wallet with 1.0 MATIC and retry.
if single test run (step 5) returns "no tradeable edges found":
this is normal; markets may not have >5% mispricing right now. wait one cron cycle and check again. if persistent, lower EDGE_THRESHOLD in run_trade.py from 0.05 to 0.03 (3%).
else if test run errors (auth, network, wallet):
halt cron, check .env file, verify VPS IP with curl ifconfig.me, and re-run approval script.
if LLM evaluation fails (API timeout, quota exceeded): script catches this and logs "LLM eval failed, skipping market X". check Anthropic dashboard for usage and quota. if exceeded, wait until billing period resets or increase budget.
if executed trade is not reflected in order book within 30 seconds:
check cron.log for "order rejected" message. likely cause is stale price data or insufficient liquidity. script retries on next cycle; no manual action needed.
if cron.log shows repeated failed orders on same market:
add that market to skip list (edit run_trade.py to append market ID to skip_markets.txt). script checks this file before evaluation and deduplicates.
success state:
cron.log shows at least 10 lines per day (one per execution)trades.jsonl contains at least one trade record with schema: {"market_id": "str", "timestamp": "iso8601", "position": "buy|sell", "shares": "int", "price": "float", "kelly_fraction": "float", "edge_pct": "float"}pnl_tracker.py output shows numeric P&L values (can be negative)file locations:
/opt/trader/app/.env (not committed to repo)/opt/trader/app/trades.jsonl (append-only)/opt/trader/app/cron.log (rotated if >100MB)pnl_tracker.py (can be piped to file)data formats:
market_id, question, end_date, liquidity, order_bookorder_id, status, filled_amount, priceuser knows skill worked when:
curl ifconfig.me shows non-US IP, Python venv installedrun_trade.py once and see console output showing market fetch, LLM calls, and either "X orders placed" or "no tradeable edges"crontab -l and see the */10 schedule; tail /opt/trader/app/cron.log shows new lines every 10 minutes (or on next scheduled run)trades.jsonlpnl_tracker.py and get numeric output; over time (1-2 weeks), you'll see trade volume accumulate in trades.jsonltangible signals (within 24 hours of setup):
note: the bot is probabilistic; not every cycle will find tradeable edges. zero trades in a day is normal if markets are efficiently priced. persistent zero activity suggests edge threshold is too high; lower EDGE_THRESHOLD and restart cron.
original author: clawhub. enriched to follow Implexa standards with explicit decision logic, edge cases, and verified output contract.