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.
- 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
- 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
- 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
- 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
- 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
pip install -r requirements.txtCopy the example environment file and add your credentials:
cp .env.example .envEdit .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
python run_bots.py --paperpython run_bots.py --paper --bots 2python run_bots.py --live| 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 |
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
- Detects price deviations from moving average
- Uses EMA/SMA/WMA with configurable periods
- Z-score threshold for entry signals
- Best in ranging markets
- Follows price trends using MA crossovers
- RSI confirmation for overbought/oversold
- MACD-like signal generation
- Best in trending markets
- Trades breakouts from Bollinger Bands
- ATR-based position sizing
- Volume confirmation optional
- Best in volatile markets
- High-frequency micro-momentum trades
- Tight spreads and quick exits
- Tick direction consistency
- Best in liquid markets
- Provides liquidity and captures spread
- Inventory-aware quoting
- Dynamic position skewing
- Best in stable markets
- Combines signals from multiple strategies
- Weighted voting based on recent performance
- Consensus threshold for execution
- Adaptive weight adjustment
- Signal Generation: Multiple strategies vote
- Position Sizing: Kelly criterion or fixed
- Entry: Smart order routing (TWAP/VWAP/Iceberg)
- Management: Trailing stops, dynamic exits
- Stake Progression: $5 → $10 → $20 → $40 → $80
- Max Streak (4 wins): Pocket profits, reset to $5
- 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
start_stake = 5.0 # Initial bet amount
max_streak = 4 # Cap winning streak
stake_multiplier = 2.0 # Double on windaily_risk_cap = 1600.0 # Max daily exposure
daily_loss_limit = 500.0 # Stop-loss threshold
max_open_positions = 20 # Concurrent position limitmin_swing_percent = 10.0 # Minimum swing to trigger
max_swing_percent = 15.0 # Maximum swing to consider
lookback_seconds = 300 # 5-minute windowColumns: timestamp, bot_id, event_id, token_id, action, stake, price, result, streak, daily_pnl, notes
Contains debug info, errors, and system events.
Configure Slack/Discord webhooks to receive alerts for:
- Trade executions
- Max streak achievements
- Errors and failures
- Daily limit warnings
- Kill switch activations
- DigitalOcean (NYC/Chicago regions)
- Linode
- Vultr
# 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_botCreate /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.targetEnable and start:
sudo systemctl enable trading-bot
sudo systemctl start trading-bot
sudo systemctl status trading-bot- Paper Trade First: Run 2-3 complete market cycles
- Validate Swing Detection: Check logs for signal accuracy
- Test Stake Progression: Verify doubling logic
- Test Kill Switch: Ensure immediate halt works
- Scale Gradually: Start with 2 bots, increase to 20
Access the real-time dashboard at http://localhost:8080 when running:
python run_bots.py --paper --dashboard- 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
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}%")- Walk-Forward Optimization: Rolling train/test windows
- Monte Carlo Simulation: Assess strategy robustness
- Parameter Grid Search: Find optimal settings
The system includes lightweight ML models:
- Naive Bayes: Direction classification
- K-Nearest Neighbors: Pattern matching
- Linear Regression: Price change prediction
- Ensemble: Combines all models
- Price (SMA, EMA, ranges)
- Momentum (ROC, RSI, MACD)
- Volatility (ATR, Bollinger width)
- Volume (ratios, correlation)
- Patterns (higher highs/lows)
- Time (cyclical hour/day)
- Never commit
.envfiles - 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
- Check API credentials
- Verify Polymarket API is accessible
- In paper mode, mock markets are used automatically
- System auto-reconnects with exponential backoff
- Check network stability
- Verify firewall allows WebSocket connections
- Built-in rate limiter prevents API abuse
- Exponential backoff on 429 responses
- Reduce bot count if persistent
MIT License - Use at your own risk. This software is provided as-is without warranty. Trading involves significant financial risk.