Skip to content

shibasushi/polymark_bot_elis

Repository files navigation

Polymarket 20-Bot Arbitrage System

A sophisticated Python-based automated trading bot swarm designed for Bitcoin 5-minute up/down markets on Polymarket. Features multiple trading strategies, machine learning integration, advanced analytics, and a real-time web dashboard.

Features

Core Trading

  • 20 Independent Bots: Each bot operates autonomously with configurable strategies
  • Real-Time Price Monitoring: WebSocket-based low-latency price tracking
  • Multiple Strategies: Mean reversion, momentum, volatility breakout, scalping, market making
  • Strategy Ensemble: Combines multiple strategies with weighted voting
  • Martingale Staking: Bets double on wins ($5 → $10 → $20 → $40 → $80)
  • 4-Win Streak Cap: Profits pocketed at max streak, then reset

Advanced Features

  • Machine Learning Integration: Naive Bayes, KNN, and linear regression for price prediction
  • Adaptive Parameters: Auto-tuning strategy parameters based on performance
  • Smart Order Routing: Optimal execution with TWAP, VWAP, and iceberg orders
  • Backtesting Engine: Walk-forward optimization and Monte Carlo simulation
  • Web Dashboard: Real-time monitoring with charts and controls

Risk Management

  • Daily Exposure Cap: Maximum $1,600 total exposure
  • Dynamic Position Sizing: Kelly criterion and volatility-based sizing
  • Trailing Stops: Automatic stop-loss adjustment
  • Kill Switch: Immediate halt capability
  • Value at Risk (VaR): Risk assessment and monitoring

Analytics

  • Performance Metrics: Sharpe ratio, Sortino ratio, Calmar ratio
  • Drawdown Analysis: Track and visualize drawdowns
  • Strategy Comparison: Compare performance across strategies
  • Trade Logging: Comprehensive trade history with analysis

Infrastructure

  • Event-Driven Architecture: Decoupled components with pub/sub
  • SQLite Database: Persistent storage for trades and analytics
  • Paper Trading Mode: Test strategies with simulated funds
  • Notifications: Slack/Discord alerts for trades and errors

Quick Start

1. Install Dependencies

pip install -r requirements.txt

2. Configure Environment

Copy the example environment file and add your credentials:

cp .env.example .env

Edit .env with your settings:

POLYMARKET_API_KEY=your_api_key
POLYMARKET_API_SECRET=your_api_secret
POLYMARKET_PRIVATE_KEY=your_private_key
SLACK_WEBHOOK_URL=https://hooks.slack.com/...
DISCORD_WEBHOOK_URL=https://discord.com/api/webhooks/...
PAPER_TRADE=true

3. Run Paper Trading

python run_bots.py --paper

4. Run with Fewer Bots (Testing)

python run_bots.py --paper --bots 2

5. Go Live (Use with Caution)

python run_bots.py --live

Command Line Options

Option Description
--paper Run in paper trading mode (default)
--live Run in live trading mode
--bots N Start with N bots (1-20, default: 20)
--interactive Run with interactive control menu
--status Show system status and exit

Project Structure

trading_bot/
├── run_bots.py          # Main entry point with CLI
├── config.py            # Configuration settings
│
├── Core Trading
│   ├── bot.py               # Basic trading bot
│   ├── enhanced_bot.py      # Advanced bot with ML/multi-strategy
│   ├── bot_manager.py       # Bot swarm management
│   ├── polymarket_client.py # API client (REST + WebSocket)
│   └── order_manager.py     # Smart order routing & execution
│
├── Strategies
│   ├── strategies.py        # Multiple trading strategies
│   ├── swing_detector.py    # Price swing detection
│   └── ml_models.py         # Machine learning models
│
├── Risk & Analytics
│   ├── risk_manager.py      # Risk management & kill switch
│   ├── analytics.py         # Performance metrics & analysis
│   └── backtester.py        # Backtesting engine
│
├── Infrastructure
│   ├── events.py            # Event-driven architecture
│   ├── database.py          # SQLite persistence
│   ├── trade_logger.py      # Logging & notifications
│   └── dashboard.py         # Web dashboard
│
├── Configuration
│   ├── requirements.txt     # Dependencies
│   ├── .env.example         # Environment template
│   └── .gitignore           # Git ignore rules
│
└── Data
    ├── logs/                # Trade and system logs
    └── data/                # SQLite database

Trading Strategies

1. Mean Reversion

  • Detects price deviations from moving average
  • Uses EMA/SMA/WMA with configurable periods
  • Z-score threshold for entry signals
  • Best in ranging markets

2. Momentum

  • Follows price trends using MA crossovers
  • RSI confirmation for overbought/oversold
  • MACD-like signal generation
  • Best in trending markets

3. Volatility Breakout

  • Trades breakouts from Bollinger Bands
  • ATR-based position sizing
  • Volume confirmation optional
  • Best in volatile markets

4. Scalping

  • High-frequency micro-momentum trades
  • Tight spreads and quick exits
  • Tick direction consistency
  • Best in liquid markets

5. Market Making

  • Provides liquidity and captures spread
  • Inventory-aware quoting
  • Dynamic position skewing
  • Best in stable markets

Strategy Ensemble

  • Combines signals from multiple strategies
  • Weighted voting based on recent performance
  • Consensus threshold for execution
  • Adaptive weight adjustment

Bet Execution

  1. Signal Generation: Multiple strategies vote
  2. Position Sizing: Kelly criterion or fixed
  3. Entry: Smart order routing (TWAP/VWAP/Iceberg)
  4. Management: Trailing stops, dynamic exits
  5. Stake Progression: $5 → $10 → $20 → $40 → $80
  6. Max Streak (4 wins): Pocket profits, reset to $5

Risk Controls

  • Daily Cap: Maximum $1,600 total exposure
  • Daily Loss Limit: Stop trading after $500 loss
  • Kill Switch: Immediate halt capability
  • Position Timeout: Auto-close after 10 minutes
  • VaR Monitoring: Value at Risk calculations
  • Correlation Limits: Avoid concentrated positions

Configuration

Bot Parameters (config.py)

start_stake = 5.0      # Initial bet amount
max_streak = 4         # Cap winning streak
stake_multiplier = 2.0 # Double on win

Risk Parameters

daily_risk_cap = 1600.0   # Max daily exposure
daily_loss_limit = 500.0  # Stop-loss threshold
max_open_positions = 20   # Concurrent position limit

Swing Detection

min_swing_percent = 10.0  # Minimum swing to trigger
max_swing_percent = 15.0  # Maximum swing to consider
lookback_seconds = 300    # 5-minute window

Logging

Trade Log (logs/trade_log.csv)

Columns: timestamp, bot_id, event_id, token_id, action, stake, price, result, streak, daily_pnl, notes

System Log (logs/system.log)

Contains debug info, errors, and system events.

Notifications

Configure Slack/Discord webhooks to receive alerts for:

  • Trade executions
  • Max streak achievements
  • Errors and failures
  • Daily limit warnings
  • Kill switch activations

VPS Deployment

Recommended Providers

  • DigitalOcean (NYC/Chicago regions)
  • Linode
  • Vultr

Setup

# Create virtual environment
python -m venv venv
source venv/bin/activate  # Linux/Mac
.\venv\Scripts\activate   # Windows

# Install dependencies
pip install -r requirements.txt

# Configure environment
cp .env.example .env
nano .env  # Edit with your credentials

# Run with screen/tmux for persistence
screen -S trading_bot
python run_bots.py --paper

# Detach: Ctrl+A, D
# Reattach: screen -r trading_bot

Systemd Service (Linux)

Create /etc/systemd/system/trading-bot.service:

[Unit]
Description=Polymarket Trading Bot
After=network.target

[Service]
Type=simple
User=trader
WorkingDirectory=/home/trader/trading_bot
ExecStart=/home/trader/trading_bot/venv/bin/python run_bots.py --paper
Restart=always
RestartSec=10

[Install]
WantedBy=multi-user.target

Enable and start:

sudo systemctl enable trading-bot
sudo systemctl start trading-bot
sudo systemctl status trading-bot

Testing Recommendations

  1. Paper Trade First: Run 2-3 complete market cycles
  2. Validate Swing Detection: Check logs for signal accuracy
  3. Test Stake Progression: Verify doubling logic
  4. Test Kill Switch: Ensure immediate halt works
  5. Scale Gradually: Start with 2 bots, increase to 20

Web Dashboard

Access the real-time dashboard at http://localhost:8080 when running:

python run_bots.py --paper --dashboard

Dashboard Features

  • Live P&L Tracking: Real-time profit/loss display
  • Bot Grid: Visual status of all 20 bots
  • Equity Curve: Interactive chart of portfolio value
  • Strategy Performance: Compare strategy win rates
  • Trade History: Recent trades with details
  • Controls: Kill switch, reset, scale bots

Backtesting

Run strategy backtests before live trading:

from backtester import BacktestEngine, MarketDataGenerator
from strategies import MeanReversionStrategy

# Generate synthetic data
data_gen = MarketDataGenerator()
price_data = data_gen.generate_regime_switching(
    "btc_5min",
    start_date=datetime.now() - timedelta(days=7),
    end_date=datetime.now()
)

# Run backtest
engine = BacktestEngine()
strategy = MeanReversionStrategy()
result = engine.run(strategy, price_data)

print(f"Total Return: {result.total_return_pct:.2f}%")
print(f"Sharpe Ratio: {result.sharpe_ratio:.2f}")
print(f"Max Drawdown: {result.max_drawdown:.2f}%")

Advanced Backtesting

  • Walk-Forward Optimization: Rolling train/test windows
  • Monte Carlo Simulation: Assess strategy robustness
  • Parameter Grid Search: Find optimal settings

Machine Learning

The system includes lightweight ML models:

Models

  • Naive Bayes: Direction classification
  • K-Nearest Neighbors: Pattern matching
  • Linear Regression: Price change prediction
  • Ensemble: Combines all models

Features Extracted

  • Price (SMA, EMA, ranges)
  • Momentum (ROC, RSI, MACD)
  • Volatility (ATR, Bollinger width)
  • Volume (ratios, correlation)
  • Patterns (higher highs/lows)
  • Time (cyclical hour/day)

Safety Notes

  • Never commit .env files - contains secrets
  • Start with paper trading - validate strategy first
  • Monitor actively during initial live deployment
  • Set conservative limits when starting
  • Have kill switch ready for emergencies

Troubleshooting

No Markets Found

  • Check API credentials
  • Verify Polymarket API is accessible
  • In paper mode, mock markets are used automatically

WebSocket Disconnects

  • System auto-reconnects with exponential backoff
  • Check network stability
  • Verify firewall allows WebSocket connections

Rate Limiting

  • Built-in rate limiter prevents API abuse
  • Exponential backoff on 429 responses
  • Reduce bot count if persistent

License

MIT License - Use at your own risk. This software is provided as-is without warranty. Trading involves significant financial risk.

About

No description, website, or topics provided.

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

 
 
 

Contributors

Languages