Skip to content

tomron87/PolyBot

Repository files navigation

PolyBot

DISCLAIMER: This software is for educational and research purposes only. It is not financial advice. Trading on prediction markets involves substantial risk of loss. The authors are not responsible for any financial losses. Users must comply with their jurisdiction's laws and their LLM provider's terms of service.

AI-powered Polymarket trading bot that uses Claude LLMs to analyze prediction markets, with an IRT calibration layer that learns and corrects systematic biases over time.

How It Works

Screen Markets → Ensemble LLM Analysis → IRT Calibration → Risk Management → Execution
  1. Screen markets by volume, liquidity, price range, spread, and time to resolution
  2. Analyze each market using a 5-variant LLM ensemble (neutral, bull, bear, base_rate, decomposition) with a two-stage pipeline that skips markets with no detectable edge
  3. Calibrate probability estimates using Item Response Theory (2PL model + Platt scaling) trained on resolved predictions
  4. Trade on detected mispricings with Kelly-inspired position sizing and risk guardrails
  5. Learn from resolved predictions to improve future accuracy

Key Features

  • Multi-model ensemble — 5 analysis variants with trimmed mean aggregation to reduce individual model bias
  • Two-stage analysis — Stage 1 (neutral only) filters out no-edge markets before running the full ensemble, saving ~80% of LLM cost on low-signal markets
  • IRT calibration — learns per-market difficulty and per-analyst discrimination parameters from resolved outcomes
  • Risk management — position sizing limits, exposure caps, daily loss limits, and adaptive stop-loss
  • Position reconciliation — bidirectional sync between local DB and Polymarket with phantom trade detection and external trade import
  • News integration — Tavily-powered news search with resolution source detection and recency prioritization
  • Crypto awareness — detects crypto-category markets and enriches analysis with CoinGecko price/volume/trend data
  • Telegram bot — slash commands and natural language interaction via an agentic layer (Claude Haiku with tool use)
  • REST API — FastAPI endpoints for portfolio, positions, trades, P&L, and market data with JWT auth
  • Automation — launchd integration for scheduled trading, resolution, calibration, and portfolio summaries

Prerequisites

  • Python 3.11+
  • uv package manager
  • A Polymarket account with API credentials
  • An Anthropic API key (Claude)
  • Optional: Tavily API key (news search), Telegram bot token, Slack webhook

Quick Start

# Clone and install
git clone https://github.com/YOUR_USERNAME/PolyBot.git
cd PolyBot
uv sync

# Configure
cp config.yaml.example config.yaml    # Edit trading parameters
cp keys.env.example keys.env          # Fill in your API keys

# Verify setup
uv run pytest tests/ -v

# Paper trade (no real money)
uv run python -m src.main trade

# Live trade (real money — use with caution)
uv run python -m src.main trade --live

keys.env Format

# Polymarket wallet private key (without 0x prefix)
PK=your_private_key_here

# Your Polymarket profile address
FUNDER_ADDRESS=0xYourPolymarketProfileAddress

# Wallet type: 0=EOA/MetaMask, 1=Email/Magic, 2=Browser/GnosisSafe
SIGNATURE_TYPE=1

# Polymarket API credentials (generate via Polymarket)
POLY_API_KEY=
POLY_API_SECRET=
POLY_API_PASSPHRASE=

# Anthropic API key for Claude
ANTHROPIC_API_KEY=sk-ant-your-key-here

# Tavily API key for news search (optional, https://tavily.com)
TAVILY_API_KEY=tvly-your-key-here

# Telegram notifications (optional)
TELEGRAM_BOT_TOKEN=
TELEGRAM_CHAT_ID=

# Slack notifications (optional)
SLACK_WEBHOOK_URL=

CLI Commands

uv run python -m src.main --help        # List all commands

# Core pipeline
uv run python -m src.main trade         # Paper trade (screen → analyze → trade)
uv run python -m src.main trade --live   # Live trade
uv run python -m src.main resolve       # Resolve settled markets
uv run python -m src.main calibrate     # Refit IRT calibration model

# Portfolio
uv run python -m src.main summary       # Paper portfolio summary
uv run python -m src.main summary --live # Live portfolio summary

# Utilities
uv run python -m src.main serve         # Start REST API server
uv run python -m src.main screen        # Screen markets without trading
uv run python -m src.main analyze       # Analyze a single market

Telegram Bot

Start with: uv run python -m src.telegram_bot

The bot supports slash commands and natural language via an agentic layer:

/portfolio  /positions  /history  /status
/trade      /resolve    /sync     /review
/kill       /resume     /cost     /log
/config     /bankroll   /schedule /help

See Chat Manual for the full command and agent tool reference.

REST API

Start with: uv run python -m src.main serve

Key endpoints: /api/portfolio, /api/positions, /api/trades, /api/pnl, /api/markets, /api/calibration, /api/costs, /api/health. Auth via JWT bearer tokens (POST /api/auth/token with API key).

Project Structure

src/
├── main.py                    # CLI entry point (typer)
├── telegram_bot.py            # Telegram bot (long-polling)
├── agent.py                   # Agentic layer (Haiku tool-use loop)
├── config_manager.py          # Runtime config management
├── scheduler.py               # launchd schedule management
├── strategy/
│   ├── screener.py            # Market screening and scoring
│   ├── ensemble.py            # Multi-variant LLM ensemble
│   └── analyzer.py            # LLM analysis (Anthropic SDK)
├── calibration/
│   ├── irt_model.py           # 2PL IRT + Platt scaling
│   └── resolution.py          # Market outcome resolution
├── execution/
│   ├── paper_trader.py        # Paper trading engine
│   ├── live_trader.py         # Live trading engine
│   ├── risk_manager.py        # Position sizing and risk limits
│   └── sync_manager.py        # Polymarket sync and reconciliation
├── data/
│   ├── orm.py                 # SQLAlchemy ORM models
│   ├── database.py            # Database query functions
│   ├── models.py              # Pydantic data models
│   ├── news_client.py         # Tavily news search
│   ├── crypto_client.py       # CoinGecko crypto data
│   └── feature_extractor.py   # ML feature extraction
├── api/
│   ├── app.py                 # FastAPI application
│   ├── routes/                # API route handlers
│   ├── schemas.py             # API response schemas
│   └── dependencies.py        # Auth and DB dependencies
├── notifications/
│   └── notifier.py            # Telegram and Slack notifications
└── connection/
    ├── auth.py                # Polymarket client auth
    └── gamma_client.py        # Gamma API client

Automation (launchd)

Agent Schedule Command
com.polybot.trade 10:00, 22:00 trade --live
com.polybot.resolve Every 4 hours resolve
com.polybot.calibrate 03:00 daily calibrate
com.polybot.summary 20:00 daily summary --live
com.polybot.telegram Persistent (KeepAlive) telegram_bot

Schedules can be managed at runtime via the /schedule Telegram command.

Documentation

  • Setup Guide — Installation, API keys, configuration, automation, troubleshooting
  • Developer Guide — Project structure, architecture, patterns, testing, extending
  • Chat Manual — Telegram commands, agent tools, sync manager, example conversations

License

MIT License. See LICENSE for details.

About

Polymarket AI trading bot

Resources

License

Contributing

Stars

Watchers

Forks

Packages

 
 
 

Contributors