Skip to content

JDDavenport/polymarket-trading-agent

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

1 Commit
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

🎯 Polymarket Trading Agent

Autonomous AI-powered trading system for prediction markets. Systematic edge detection through LLM-driven fair value estimation.

Python 3.9+ Claude AI Polymarket License: MIT

An algorithmic trading agent that exploits prediction market inefficiencies by combining AI-generated probability estimates with quantitative position sizing. Built on proven quant principles: edge detection, Kelly optimization, and rigorous risk management.

Inspired by @Argona0x's results: $50 → $2,980 in 48 hours through systematic mispricing arbitrage.


🏗️ Architecture

                    AUTONOMOUS TRADING SYSTEM
    ┌──────────────────────────────────────────────────────────┐
    │                                                          │
    │   ┌─────────────┐      ┌──────────────┐                 │
    │   │   Market    │─────▶│    Claude    │                 │
    │   │   Scanner   │      │   Analyzer   │                 │
    │   │             │      │              │                 │
    │   │ • Gamma API │      │ • Fair Value │                 │
    │   │ • Liquidity │      │ • Confidence │                 │
    │   │ • Volume    │      │ • Reasoning  │                 │
    │   └─────────────┘      └──────────────┘                 │
    │          │                     │                         │
    │          │                     ▼                         │
    │          │             ┌──────────────┐                 │
    │          │             │    Kelly     │                 │
    │          │             │    Sizer     │                 │
    │          │             │              │                 │
    │          │             │ • Kelly Calc │                 │
    │          │             │ • Quarter-K  │                 │
    │          │             │ • Max Caps   │                 │
    │          │             └──────────────┘                 │
    │          │                     │                         │
    │          │                     ▼                         │
    │          │             ┌──────────────┐                 │
    │          └────────────▶│     CLOB     │                 │
    │                        │    Trader    │                 │
    │                        │              │                 │
    │    ┌─────────────┐     │ • Execution  │                 │
    │    │    Risk     │────▶│ • Position   │                 │
    │    │   Manager   │     │   Tracking   │                 │
    │    │             │     │ • P&L Log    │                 │
    │    │ • Circuit   │     └──────────────┘                 │
    │    │   Breakers  │              │                       │
    │    │ • Loss Caps │              │                       │
    │    │ • Kill      │              ▼                       │
    │    │   Switch    │     ┌──────────────┐                 │
    │    └─────────────┘     │  Polymarket  │                 │
    │            ▲           │     CLOB     │                 │
    │            │           │   (Polygon)  │                 │
    │    ┌───────┴─────┐     └──────────────┘                 │
    │    │    Edge     │                                      │
    │    │   Sources   │                                      │
    │    │             │                                      │
    │    │ • NOAA      │◀── External Data Feeds               │
    │    │ • Odds API  │                                      │
    │    │ • CoinGecko │                                      │
    │    └─────────────┘                                      │
    │                                                          │
    └──────────────────────────────────────────────────────────┘

⚡ How It Works

The agent operates in a continuous loop, executing this five-phase workflow every 10 minutes:

1️⃣ Market Discovery & Filtering

  • Queries Polymarket's Gamma API for active markets
  • Applies liquidity filters (min volume: $10k, sufficient order book depth)
  • Prioritizes markets with high volume/spread inefficiency ratios

2️⃣ AI-Powered Fair Value Estimation

  • Sends market context + external edge sources to Claude (Sonnet 4.5)
  • Receives probabilistic fair value estimate (0-100%) with confidence score
  • Claude reasons through fundamentals, incorporates real-time data signals
  • Example: "BTC at $105k with strong institutional momentum, technical breakout confirmed → 55% probability YES (confidence: 0.72)"

3️⃣ Edge Detection & Mispricing Identification

  • Compares AI estimate vs. current market odds
  • Calculates expected value: EV = (p_estimated - p_market) / (1 - p_market)
  • Only trades if edge > 8% threshold (configurable)

4️⃣ Quantitative Position Sizing (Kelly Criterion)

  • Applies Kelly formula for optimal bet sizing: f* = (p·b - q) / b
  • Uses quarter-Kelly (25% of full Kelly) for safety margin
  • Scales by Claude's confidence level
  • Hard caps: max 6% of bankroll per position, $10 absolute max

5️⃣ Order Execution & Risk Management

  • Places limit orders via Polymarket CLOB API (Polygon network)
  • Tracks open positions with 30% stop-loss triggers
  • Enforces portfolio constraints: max 8 concurrent positions
  • Logs all trades with full reasoning chain for post-analysis

Risk Controls:

  • Daily loss limit: halt trading if down >15%
  • Consecutive loss circuit breaker: pause after 5 losses in a row
  • Bankroll floor: agent "dies" if balance < $5
  • Manual kill switch: create KILL_SWITCH file for instant halt

🔧 Tech Stack

Component Technology Purpose
AI/ML Anthropic Claude (Sonnet 4.5) Fair value estimation & market analysis
Position Sizing Kelly Criterion (quarter-Kelly variant) Optimal bet sizing with risk management
Exchange API Polymarket CLOB (py-clob-client) Order execution & market data
Blockchain Polygon (web3.py) On-chain trade settlement
Data Sources NOAA, The Odds API, CoinGecko External signals for edge detection
Language Python 3.9+ Core implementation
Async Framework asyncio + aiohttp Concurrent API calls
Config Management YAML + pydantic Type-safe configuration
Logging structlog + JSONL Structured audit trail
Testing pytest Unit & integration tests

📊 Strategy: The Quantitative Edge

Core Thesis

Prediction markets are inefficient. Human traders anchor on recent news, overreact to volatility, and misprice tail risks. An AI system with access to structured data can estimate fairer probabilities.

The Edge

Market says: Bitcoin will hit $120k by March → 40% YES
AI estimates: Based on current price action, institutional flows, 
              technical breakouts → 55% probability (confidence: 0.70)

Expected Value = (0.55 - 0.40) / (1 - 0.40) = 25% edge

Quarter-Kelly Size = 0.25 × 0.25 × 0.70 = 4.375% of bankroll
On $50 → $2.19 position

Why It Works

  1. Information aggregation: AI synthesizes multiple data sources (weather alerts, sports odds, crypto technicals) faster than human traders
  2. Probability calibration: LLMs trained on vast datasets provide well-calibrated probability estimates
  3. Emotional neutrality: No FOMO, no revenge trading, pure EV-driven decisions
  4. Systematic execution: Exploits mispricings at scale across dozens of markets

Historical Performance Benchmark

  • Starting capital: $50
  • Target: 10-20% weekly ROI through high-Sharpe ratio bets
  • Volatility: High (small sample size amplifies variance)
  • Max drawdown tolerance: 30% (circuit breakers activate)

Note: This is experimental. Past performance ≠ future results.


🚀 Quick Start

Prerequisites

  • Python 3.9+ (tested on 3.11, 3.13)
  • Polygon wallet with USDC (for live trading)
  • Anthropic API key (get one here)
  • Optional: NOAA token, The Odds API key (free tiers available)

Installation

# Clone the repository
git clone https://github.com/yourusername/trading-agent.git
cd trading-agent

# Create virtual environment
python3 -m venv .venv
source .venv/bin/activate  # On Windows: .venv\Scripts\activate

# Install dependencies
pip install -r requirements.txt

Configuration

  1. Set up environment variables:
# Copy example files
cp .env.example .env

# Edit .env with your credentials
nano .env

Add your keys:

ANTHROPIC_API_KEY=sk-ant-api03-...
POLYMARKET_PRIVATE_KEY=0x...  # Your Polygon wallet private key
NOAA_API_TOKEN=your-token-here  # Optional
ODDS_API_KEY=your-key-here      # Optional
  1. Customize trading parameters:
cp config.yaml config.local.yaml
nano config.local.yaml

Key settings:

risk:
  initial_bankroll: 50.0       # Starting USDC
  min_edge_threshold: 0.08     # Only trade if edge > 8%
  kelly_fraction: 0.25         # Quarter-Kelly for safety
  max_position_pct: 0.06       # Max 6% per trade
  max_daily_loss_pct: 0.15     # Halt if down >15% today

loop:
  interval_seconds: 600        # Check markets every 10 min
  min_volume: 10000            # Skip markets with <$10k volume

Running the Agent

Dry-run mode (recommended for first run):

# Test single cycle
python main.py --once

# Continuous loop (no real money)
python main.py

Live trading (real money at risk!):

# Ensure wallet has USDC on Polygon
python main.py --live

Custom parameters:

# Run with $100 bankroll, check every 5 minutes
python main.py --bankroll 100 --interval 300 --live

Emergency Stop

# Create kill switch file
echo "Emergency stop" > KILL_SWITCH

# Agent will halt at next cycle
# To resume: rm KILL_SWITCH

📁 Project Structure

trading-agent/
├── main.py                  # Entry point & CLI
├── config.yaml              # Default configuration
├── config.local.yaml        # Local overrides (gitignored)
├── .env                     # API keys (gitignored)
├── requirements.txt         # Python dependencies
├── KILL_SWITCH              # Create to halt agent (gitignored)
│
├── src/
│   ├── __init__.py
│   ├── agent.py             # Main orchestrator (TradingAgent class)
│   ├── config.py            # Configuration loader & validation
│   ├── logger.py            # Structured logging (JSONL + console)
│   ├── market_scanner.py    # Gamma API interface & filtering
│   ├── analyzer.py          # Claude API wrapper for market analysis
│   ├── position_sizer.py    # Kelly criterion implementation
│   ├── trader.py            # CLOB order execution & P&L tracking
│   ├── risk_manager.py      # Circuit breakers & kill switches
│   └── edge_sources.py      # External data feeds (NOAA, Odds, Crypto)
│
├── tests/
│   ├── __init__.py
│   └── test_sizer.py        # Kelly sizer unit tests
│
├── logs/                    # Runtime logs (gitignored)
│   ├── agent.log            # General activity
│   ├── trades.jsonl         # All executed trades
│   ├── analysis.jsonl       # Claude's reasoning per market
│   ├── pnl.jsonl            # P&L snapshots per cycle
│   └── agent_state.json     # Latest state for resume
│
└── data/                    # Cached market data (gitignored)

📊 Monitoring & Logs

All activity is logged in structured JSONL format for easy parsing:

Trade Log (logs/trades.jsonl)

{
  "type": "trade",
  "timestamp": "2026-03-06T18:30:00Z",
  "order_id": "0x7f8a...",
  "market_question": "Will Bitcoin hit $120k by March 2026?",
  "side": "YES",
  "price": 0.35,
  "size_usd": 2.19,
  "estimated_edge": 0.25,
  "estimated_prob": 0.55,
  "confidence": 0.70,
  "kelly_fraction": 0.04375,
  "reasoning": "BTC at $105k, strong institutional momentum, technical breakout confirmed on 4H chart. ETF flows positive. Macro backdrop supportive.",
  "bankroll_before": 50.00,
  "bankroll_after": 47.81
}

Analysis Log (logs/analysis.jsonl)

Contains Claude's full reasoning chain for each market analyzed.

P&L Log (logs/pnl.jsonl)

Snapshots of portfolio value, unrealized P&L, and trade count per cycle.


⚙️ Advanced Configuration

Kelly Sizing Parameters

The position sizer implements a modified Kelly Criterion with multiple safety layers:

# Raw Kelly fraction
f_kelly = (p_estimated - p_market) / (1 - p_market)

# Apply safety adjustments
f_adjusted = f_kelly * kelly_fraction * confidence

# Enforce caps
position_size = min(
    f_adjusted * bankroll,
    max_position_pct * bankroll,
    max_single_trade_usd
)

Why quarter-Kelly?

  • Full Kelly maximizes log growth but has high variance
  • Quarter-Kelly reduces volatility by ~50% while retaining ~75% of growth rate
  • Better suited for small bankrolls and uncertain edge estimates

Risk Management Layers

Layer Parameter Default Purpose
Kelly fraction kelly_fraction 0.25 Reduce full-Kelly variance
Confidence scaling Automatic Claude's 0-1 score Reduce size for uncertain estimates
Position cap max_position_pct 6% Hard limit per trade
Dollar cap max_single_trade_usd $10 Absolute max size
Portfolio cap max_positions 8 Total concurrent positions
Stop loss stop_loss_pct 30% Auto-exit losing positions
Daily loss limit max_daily_loss_pct 15% Circuit breaker
Consecutive losses max_consecutive_losses 5 Pause after streak
Bankroll floor min_bankroll_alive $5 Agent "dies" below this

Edge Sources Configuration

edge_sources:
  weather:
    enabled: true
    api: NOAA
    cache_minutes: 30
  
  sports:
    enabled: true
    api: the-odds-api
    sports: [basketball_nba, americanfootball_nfl]
  
  crypto:
    enabled: true
    apis: [coingecko, alternative_me]
    symbols: [BTC, ETH]

🧪 Testing

# Run unit tests
pytest tests/

# Test Kelly sizer with sample probabilities
python -m pytest tests/test_sizer.py -v

# Dry-run single cycle (no API calls)
python main.py --once --dry-run

🔍 How Claude Analyzes Markets

Example prompt structure:

Market: "Will Bitcoin hit $120,000 by March 31, 2026?"
Current odds: YES 40% / NO 60%
Current BTC price: $105,234 (+8.2% this week)

External data:
- Fear & Greed Index: 68 (Greed)
- ETF net inflows: +$420M this week
- Technical: Broke resistance at $102k, next resistance $115k
- Time to event: 25 days

Your task: Estimate the TRUE probability (0-100%) that this event occurs.
Provide:
1. Probability estimate (integer 0-100)
2. Confidence in your estimate (0.0-1.0)
3. Reasoning (2-3 sentences)

Format response as JSON:
{"probability": 55, "confidence": 0.70, "reasoning": "..."}

Claude synthesizes:

  • Historical price patterns
  • Current momentum & technicals
  • External data signals
  • Time decay to event
  • Fundamental drivers

Output is parsed and fed into the Kelly sizer.


⚠️ Disclaimers & Legal

Financial Risk

  • This is experimental software. You can lose all your capital.
  • No guarantees of profitability. Markets are unpredictable.
  • Start with small amounts you can afford to lose entirely.
  • Always test in dry-run mode before risking real funds.

Regulatory Considerations

  • Polymarket Terms of Service prohibit U.S. persons from trading. Know your jurisdiction's laws.
  • Prediction markets may be subject to gambling regulations in some countries.
  • This software is provided for educational purposes.

API Costs

  • Anthropic Claude: ~$0.01-$0.05 per market analysis (Sonnet 4.5 pricing)
  • At 10-minute intervals analyzing 10 markets/cycle: ~$7-35/day
  • Budget accordingly for your use case

Blockchain Risks

  • Polygon network fees (negligible, ~$0.001-0.01 per transaction)
  • Smart contract risks (Polymarket CLOB has been audited but use at own risk)
  • Private key security: NEVER commit your private key to git or share it

No Warranty

This software is provided "AS IS" without warranty of any kind, express or implied, including but not limited to warranties of merchantability, fitness for a particular purpose, and non-infringement.


🛠️ Troubleshooting

Common Issues

Agent immediately halts

  • Check KILL_SWITCH file doesn't exist
  • Verify bankroll > min_bankroll_alive
  • Check daily loss limit not triggered

No markets found

  • Lower min_volume threshold in config
  • Check Gamma API is accessible (network issues?)
  • Verify markets exist with sufficient liquidity

API errors

  • Verify API keys in .env
  • Check Anthropic API quota/balance
  • Ensure Polygon wallet has USDC for gas + trades

Unexpected position sizes

  • Review Kelly parameters in config
  • Check Claude's confidence scores in logs/analysis.jsonl
  • Verify edge threshold is set appropriately

🚧 Roadmap

Future enhancements under consideration:

  • Multi-agent ensemble (combine multiple LLM estimates)
  • Backtesting framework on historical Polymarket data
  • Dynamic Kelly fraction based on win rate
  • Telegram bot for real-time notifications
  • Web dashboard for monitoring positions
  • Market-making strategy (provide liquidity vs. take)
  • Integration with additional prediction markets (Manifold, Metaculus)
  • Machine learning for edge source weighting

📄 License

MIT License

Copyright (c) 2026

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.


🤝 Contributing

Contributions welcome! This is an experimental project. If you:

  • Find bugs → open an issue
  • Have strategy improvements → submit a PR
  • Built something cool on top → share it!

Please ensure all PRs:

  1. Pass existing tests (pytest)
  2. Include tests for new features
  3. Follow existing code style
  4. Don't commit API keys or private data

📚 References


Built with ❤️ and ⚡ by quantitative AI enthusiasts.

Remember: The house always wins... unless you're the house. Trade responsibly.

About

Autonomous AI trading agent for Polymarket prediction markets — Claude analysis, Kelly criterion sizing, CLOB execution

Topics

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

 
 
 

Contributors

Languages