Skip to content

Folders and files

NameName
Last commit message
Last commit date

Latest commit

Β 

History

4 Commits
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 

Repository files navigation

Polymarket AI Trading Bot

An AI-powered trading bot that replicates the strategy described in the viral "ilovecircle" Polymarket bot that earned $2.2M in 2 months with 74% accuracy. Also inspired by Polysol.fun and vladmeer/polymarket-copy-trading-bot.

How It Works

The bot implements a multi-phase strategy:

1. Signal Sweep πŸ”

  • Pulls top market data from Polymarket every few minutes
  • Monitors news feeds (NewsAPI, RSS)
  • Tracks Twitter/X for social sentiment
  • Watches volume flows and price movements

2. Neural Net Evaluation 🧠

  • Uses an ensemble of neural networks to predict market probabilities
  • Identifies markets where prices are mispriced vs. "true" probability
  • Calculates edge (difference between model prediction and market price)
  • Filters for high-confidence opportunities

3. AI Analysis (OpenAI GPT) πŸ€–

  • Uses GPT-4o-mini for market sentiment analysis
  • Provides reasoning and predicted direction
  • Enhances signals with natural language understanding
  • Runs every N cycles to save API costs

4. Auto Trading & Position Control πŸ“ˆ

  • Fires orders through the Polymarket CLOB API
  • Uses Kelly Criterion for position sizing
  • Manages multiple positions across sports, politics, crypto markets
  • Recalculates P&L and decides to keep, add, or close positions

5. Copy Trading πŸ‘₯

  • Track top-performing traders on the Polymarket leaderboard
  • Automatically copy trades from followed traders
  • Adjustable copy ratio (e.g., copy 10% of their position size)
  • Smart filtering to only copy high-conviction trades

6. Trader Discovery Scanner πŸ” (NEW!)

  • Mass scan markets to find profitable traders automatically
  • Backtest/simulate copy trading before committing real money
  • Risk metrics: Sharpe ratio, max drawdown, profit factor
  • Auto-follow excellent traders

7. Advanced Copy Strategies πŸ“Š (NEW!)

  • PERCENTAGE: Copy X% of trader's position size
  • FIXED: Use fixed $ amount per copy trade
  • ADAPTIVE: Tiered multipliers based on trade size
  • Trade aggregation (combine small trades into larger orders)
  • Stale position closing (auto-exit when tracked trader exits)

8. Risk Analytics πŸ“‰ (NEW!)

  • Sharpe ratio, Sortino ratio, Calmar ratio
  • Value at Risk (VaR) calculations
  • Win rate, profit factor, win/loss ratio
  • Comprehensive risk score (0-100)

Project Structure

poly/
β”œβ”€β”€ .env.example          # Environment variables template
β”œβ”€β”€ requirements.txt      # Python dependencies
β”œβ”€β”€ run_bot.py           # Main entry point
β”œβ”€β”€ scan_traders.py      # Trader discovery CLI (NEW!)
└── src/
    β”œβ”€β”€ __init__.py
    β”œβ”€β”€ config.py         # Configuration and settings
    β”œβ”€β”€ signal_sweep.py   # Market data and signal collection
    β”œβ”€β”€ evaluator.py      # ML model for market evaluation
    β”œβ”€β”€ trading_engine.py # Order execution and position management
    β”œβ”€β”€ copy_trading.py   # Basic copy trading and insider flow
    β”œβ”€β”€ ai_analyzer.py    # OpenAI GPT integration
    β”œβ”€β”€ trader_scanner.py # Trader discovery & backtesting (NEW!)
    β”œβ”€β”€ advanced_copy.py  # Advanced copy trading strategies (NEW!)
    β”œβ”€β”€ risk_analytics.py # Risk metrics & reporting (NEW!)
    └── bot.py            # Main orchestrator

Quick Start

1. Install Dependencies

pip install -r requirements.txt

2. Configure Environment

Copy .env.example to .env and fill in your credentials:

cp .env.example .env

Required:

  • POLYMARKET_PRIVATE_KEY - Your wallet's private key
  • POLYMARKET_FUNDER_ADDRESS - Address that holds your funds

Optional (for enhanced signals):

3. Run the Interactive Menu (Recommended!)

python menu.py

This opens a beautiful interactive menu where you can:

  • Start paper/live trading
  • Scan for profitable traders
  • Enable copy trading
  • View portfolio status
  • Check risk reports
  • And more!

4. Or use Command Line directly

Paper Mode (safe simulation):

python run_bot.py --mode paper --bankroll 1000

5. Discover Profitable Traders (NEW!)

# Scan markets to find traders to copy
python scan_traders.py --days 30 --traders 50 --min-roi 10

# Output includes command to copy best traders

6. Enable Copy Trading

# Basic copy trading
python run_bot.py --mode paper --copy-trading

# Advanced copy trading with ADAPTIVE strategy
python run_bot.py --mode paper --copy-trading --copy-strategy ADAPTIVE

# Follow specific traders
python run_bot.py --mode paper --copy-trading --follow 0x123...abc 0x456...def

# Scan + auto-follow profitable traders
python run_bot.py --mode paper --scan-traders --copy-trading

7. Get Risk Report

python run_bot.py --risk-report

8. Run Live Trading (Caution!)

python run_bot.py --mode live --bankroll 1000

⚠️ Warning: Live trading uses real money. Start with small amounts and monitor closely.

Configuration

Key settings in .env:

Setting Default Description
MAX_POSITION_SIZE 100 Maximum USD per position
MIN_EDGE_THRESHOLD 0.05 Minimum 5% edge to trade
MAX_DAILY_TRADES 50 Daily trade limit
RISK_PER_TRADE 0.02 Risk 2% of bankroll per trade
SCAN_INTERVAL_MINUTES 5 How often to scan markets
LOG_LEVEL INFO Logging level (set to DEBUG for troubleshooting)

Recent Changes

See CHANGELOG.md for a full list. Highlights:

  • Winners/losers/flat logic in position summary now uses a threshold to avoid floating-point noise and correctly classifies flat positions.
  • Top Losers display now only shows true negative P&L positions.
  • Scan interval now correctly loads from .env and respects SCAN_INTERVAL_MINUTES.
  • Confidence calculation for trading decisions is less aggressive, preventing the bot from getting stuck with no trades.
  • Persisted total_pnl and fixed nan/null handling in DB.
  • Division by zero in _paper_trade is now guarded.
  • Logging level can be set via .env (LOG_LEVEL).
  • Position summary now shows Flat positions.
  • Meta table for persistent total_pnl.
  • Confidence floor for trading decisions.

Key Features

Position Sizing with Kelly Criterion

The bot uses fractional Kelly Criterion (25% Kelly by default) to size positions based on:

  • Estimated edge over market price
  • Model confidence
  • Maximum position limits

Risk Management

  • Daily trade limits
  • Maximum position size caps
  • Automatic position rebalancing
  • Stop-loss on signal reversal

Market Filters

Only trades markets with:

  • Minimum $10k volume
  • Minimum $5k liquidity
  • Maximum 10% spread
  • Active order book

Supported Categories

  • Sports (NFL, NBA, MLB, etc.)
  • Politics (Elections, polls)
  • Crypto (BTC, ETH prices)
  • Finance (Interest rates, GDP)
  • Entertainment (Awards shows)

Architecture

β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”    β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”    β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
β”‚  Signal Sweep   │───▢│   Evaluator      │───▢│ Trading Engine  β”‚
β”‚                 β”‚    β”‚                  β”‚    β”‚                 β”‚
β”‚ - Market Data   β”‚    β”‚ - Neural Net     β”‚    β”‚ - Order Exec    β”‚
β”‚ - News/RSS      β”‚    β”‚ - Edge Calc      β”‚    β”‚ - Position Mgmt β”‚
β”‚ - Social Media  β”‚    β”‚ - Confidence     β”‚    β”‚ - P&L Tracking  β”‚
β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜    β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜    β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜
         β”‚                                              β”‚
         β”‚         β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”                 β”‚
         └────────▢│  Copy Trading    β”‚β—€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜
                   β”‚                  β”‚
                   β”‚ - Top Traders    β”‚
                   β”‚ - Insider Flow   β”‚
                   β”‚ - Whale Tracking β”‚
                   β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜

API Reference

TradingBot

from src import TradingBot, TradingMode

# Create bot in paper mode
bot = TradingBot(mode=TradingMode.PAPER)

# Run single cycle
await bot.run_cycle()

# Or run continuously
await bot.start(initial_bankroll=1000.0)

# Get status
status = bot.get_status()

SignalSweep

from src import SignalSweep

async with SignalSweep() as sweep:
    # Fetch markets
    markets = await sweep.fetch_markets()
    
    # Fetch news
    news = await sweep.fetch_news()
    
    # Generate signals
    signals = await sweep.generate_signals()

MarketEvaluator

from src import MarketEvaluator

evaluator = MarketEvaluator()

# Evaluate all signals
predictions = evaluator.evaluate_all(signals)

# Get trading opportunities
opportunities = evaluator.get_trading_opportunities(
    predictions,
    min_edge=0.05,
    min_confidence=0.3
)

Copy Trading

from src import TradingBot, TradingMode

# Create bot with copy trading enabled
bot = TradingBot(mode=TradingMode.PAPER, enable_copy_trading=True)

# Follow top traders
await bot.follow_trader("0x123...abc")

# Get top traders list
top_traders = await bot.get_top_traders(limit=20)

# Run with copy trading
await bot.start(initial_bankroll=1000.0)

Insider Flow Analysis

from src import TopTraderTracker, InsiderFlowAnalyzer

async with TopTraderTracker() as tracker:
    # Fetch leaderboard
    traders = await tracker.fetch_leaderboard()
    
    # Scan whale activity
    whales = await tracker.scan_whale_activity()
    
    # Analyze flow
    analyzer = InsiderFlowAnalyzer(tracker)
    hot_markets = analyzer.get_hot_markets(min_flow=10000)
    smart_signals = analyzer.get_smart_money_signals(min_score=0.5)

Database

The bot stores data in SQLite (data/trading_bot.db):

  • positions - Open positions
  • trades - Trade history
  • daily_stats - Daily performance

Logs

Logs are stored in logs/trading_bot.log with daily rotation.

Disclaimer

⚠️ This software is for educational purposes only.

  • Trading prediction markets involves substantial risk of loss
  • Past performance does not guarantee future results
  • The bot's ML model requires training data to be accurate
  • Always start with paper trading
  • Never trade more than you can afford to lose
  • Polymarket may have restrictions based on your jurisdiction

Contributing

  1. Fork the repository
  2. Create a feature branch
  3. Make your changes
  4. Submit a pull request

License

MIT License - See LICENSE file for details.

About

No description, website, or topics provided.

Resources

Stars

Watchers

Forks

Releases

Packages

Contributors

Languages