Skip to content

Dhaiwat10/polymarket-ai

Repository files navigation

Polymarket AI πŸ€–πŸ“ˆ

An autonomous AI trading system for Polymarket prediction markets. Watch multiple AI agents compete in real-time as they analyze markets, gather news, and execute tradesβ€”all tracked through a beautiful live dashboard.

✨ Features

  • Multi-Agent Trading Arena: Multiple AI agents (OpenAI, Claude) compete simultaneously with independent portfolios
  • Real-Time Dashboard: Live equity charts, position tracking, and trade history visualization
  • Intelligent Market Analysis: Agents gather news via Exa API and analyze Polymarket events to make trading decisions
  • Risk Management: Configurable position sizing with per-trade caps (percentage and absolute USD limits)
  • Persistent Storage: SQLite-backed data persistence for production deployments
  • Docker-Ready: One-command deployment with Docker Compose

πŸ—οΈ Architecture

β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
β”‚  Next.js Web UI β”‚  ← Live dashboard at /arena
β””β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”˜
         β”‚
    β”Œβ”€β”€β”€β”€β–Όβ”€β”€β”€β”€β”
    β”‚  API    β”‚  ← REST endpoints for snapshots & history
    β””β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”˜
         β”‚
    β”Œβ”€β”€β”€β”€β–Όβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
    β”‚  AI Engine Loop   β”‚  ← Continuously analyzes markets
    β”‚  - Find Markets   β”‚
    β”‚  - Gather News    β”‚
    β”‚  - Analyze & Tradeβ”‚
    β””β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜
         β”‚
    β”Œβ”€β”€β”€β”€β–Όβ”€β”€β”€β”€β”
    β”‚ SQLite  β”‚  ← Persistent storage
    β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜

The engine runs in a continuous loop, discovering new Polymarket events, gathering relevant news, and having AI agents analyze and trade on them. Each agent maintains an independent portfolio and makes autonomous trading decisions.

πŸš€ Quick Start

Prerequisites

  • Node.js 18+ (or Bun)
  • OpenAI API key
  • OpenRouter API key (for Claude agent via OpenRouter)
  • Exa API key (for news gathering)

Local Development

  1. Clone and install dependencies:
git clone <your-repo-url>
cd polymarket-ai
bun install  # or npm install
  1. Set up environment variables:

Create a .env file:

OPENAI_API_KEY=your_openai_key_here
OPENROUTER_API_KEY=your_openrouter_key_here
EXA_API_KEY=your_exa_key_here
  1. Run the AI engine (in one terminal):
bun run arena:dev
  1. Run the web app (in another terminal):
bun run dev
  1. Open the dashboard:

Navigate to http://localhost:3000/arena to see the live trading arena.

πŸ“Š Agent Arena Dashboard

The /arena page provides a real-time view of all AI agents:

  • Equity Charts: Historical performance visualization for each agent
  • Portfolio Metrics: Wallet balance, equity, unrealized P&L
  • Open Positions: Current market positions with entry prices
  • Trade History: Recent buy/sell transactions
  • Live Status: Real-time indicator showing if the engine is running

The dashboard polls every 2 seconds for updates and displays the latest snapshot from the engine.

βš™οΈ Configuration

Engine Settings

Control the engine behavior via environment variables:

# Engine timing
ENGINE_TICK_MS=120000              # Milliseconds between ticks (default: 120s)
ENGINE_MAX_NEW_MARKETS=5           # Max new markets analyzed per tick
ENGINE_MAX_CONCURRENCY=2           # Concurrent market analyses per agent

# Risk Management (BUY orders only)
RISK_MAX_TRADE_PCT=0.15            # Max % of wallet per trade (default: 15%)
RISK_MAX_TRADE_USD=200             # Absolute USD cap per trade (default: $200)

# Persistence (SQLite only)
SQLITE_PATH=/app/data/arena.db     # SQLite database path

# Arena Control
ARENA_CONTROL_PASSWORD=your_secret_password  # Password for pause/unpause API endpoint

Example: Custom Risk Settings

RISK_MAX_TRADE_PCT=0.2 RISK_MAX_TRADE_USD=150 bun run arena:dev

This caps each BUY order at 20% of wallet or $150, whichever is lower.

🐳 Docker Deployment

Deploy everything on a single VM with persistent data storage.

Prerequisites

  • Docker & Docker Compose installed
  • OpenAI, OpenRouter, and Exa API keys

Steps

  1. Create .env file:
OPENAI_API_KEY=your_key_here
OPENROUTER_API_KEY=your_key_here
EXA_API_KEY=your_key_here
# Optional: customize engine settings
ENGINE_TICK_MS=120000
RISK_MAX_TRADE_PCT=0.15
RISK_MAX_TRADE_USD=200
  1. Build and start:
docker compose build
docker compose up -d
  1. Access the dashboard:

Open http://<your-vm-ip>:3000/arena in your browser.

Architecture

The Docker setup runs two services:

  • web: Next.js production server (next start)
  • engine: Long-running AI engine loop

Both services share a SQLite database via a Docker volume (arena-sqlite), ensuring data persists across container restarts and host reboots.

Management

# Stop services (data persists)
docker compose down

# View logs
docker compose logs -f engine
docker compose logs -f web

# Remove data volume (⚠️ deletes all data)
docker volume rm polymarket-ai_arena-sqlite

πŸ“‘ API Endpoints

The dashboard consumes these REST endpoints:

  • GET /api/arena - Returns latest arena snapshot (no caching)
  • GET /api/arena/history?limit=10000 - Returns recent equity history as JSON array
  • GET /api/arena/control - Get current pause status (requires Authorization: Bearer <ARENA_CONTROL_PASSWORD>)
  • POST /api/arena/control - Pause or unpause the arena (requires Authorization: Bearer <ARENA_CONTROL_PASSWORD>)
    • Body: { "paused": true } or { "paused": false }

πŸ§ͺ Testing

# Run tests
bun test

# Run tests with UI
bun run test:ui

# Run tests with coverage
bun run test:coverage

πŸ›οΈ Supported VM Providers

The Docker Compose setup works on any VM provider:

  • Cloud: AWS EC2, Google Compute Engine, Azure VMs
  • VPS: DigitalOcean Droplets, Hetzner Cloud, Vultr, Linode
  • Others: OVHcloud, Oracle Cloud (Ampere A1), Scaleway

Just ensure Docker and Docker Compose are installed, then follow the deployment steps above.

🧠 How It Works

  1. Market Discovery: Engine queries Polymarket's Gamma API for featured, active events
  2. News Gathering: For each market, agents fetch relevant news via Exa API
  3. AI Analysis: Agents analyze market data + news and generate trading recommendations
  4. Trade Execution: Valid recommendations are executed with risk management caps
  5. Portfolio Tracking: All trades are recorded, positions tracked, and equity calculated
  6. Snapshot Export: Engine writes snapshots to SQLite for dashboard consumption

Each agent operates independently with its own portfolio, making autonomous decisions based on market analysis.

πŸ“¦ Tech Stack

  • Framework: Next.js 16 (App Router)
  • AI SDK: Vercel AI SDK with OpenAI & Anthropic providers
  • Charts: Recharts
  • Database: SQLite (via better-sqlite3)
  • News: Exa API
  • Markets: Polymarket Gamma API
  • Runtime: Bun (or Node.js)
  • Deployment: Docker Compose

πŸ“ License

This project is licensed under the MIT License - see the LICENSE file for details.

🀝 Contributing

Contributions are welcome! Please feel free to submit a Pull Request. For major changes, please open an issue first to discuss what you would like to change.


⚠️ Disclaimer: This is an experimental project for educational purposes. Trading on prediction markets involves financial risk. Use at your own discretion.

About

AI agents battling on Polymarket

Topics

Resources

License

Stars

7 stars

Watchers

0 watching

Forks

Releases

No releases published

Packages

 
 
 

Contributors

Languages