Professional automated trading solution for Polymarket prediction markets
- Overview
- Features
- Quick Start
- Configuration
- How It Works
- Advanced Features
- Deployment
- Troubleshooting
- Contributing
- Support
- Disclaimer
The Polymarket Copy Trading Bot is a production-ready, TypeScript-based automated trading solution designed for Polymarket prediction markets. It enables traders to automatically replicate successful trading strategies, monitor mempool activity, and execute trades with comprehensive risk management.
✨ Enterprise-Grade - Built with production-ready features including health monitoring, persistence, and graceful shutdown
🛡️ Risk Management - Built-in position tracking, slippage protection, and exposure limits
⚡ Real-Time - Hybrid monitoring using both mempool and Polymarket API for instant trade detection
🔒 Type-Safe - Full TypeScript support with comprehensive type definitions
🚀 Easy Setup - Get started in minutes with clear documentation and examples
|
Automatic Copy Trading
|
Mempool Monitoring
|
|
Gas Optimization
|
Real-Time Updates
|
- ✅ Position Tracking - Monitor all open positions with entry prices and sizes
- ✅ Slippage Protection - Configurable maximum slippage thresholds
- ✅ Exposure Limits - Per-market and total exposure limits
- ✅ Size Controls - Frontrun size multiplier (default: 50% of target)
- ✅ Dry-Run Mode - Test strategies without real trades
- 📊 Health Monitoring - HTTP endpoints for metrics and health checks
- 💾 MongoDB Persistence - Prevents duplicate trades after restarts
- ⚡ Rate Limiting - Protects against API bans
- 🔄 Connection Pooling - Optimized HTTP connections
- 📦 Order Book Caching - Reduces API calls and improves latency
- 🛑 Graceful Shutdown - Proper cleanup on termination
Before you begin, ensure you have:
- Node.js 18+ installed (Download)
- Polygon Wallet with USDC balance for trading
- POL/MATIC for gas fees (recommended: 0.5+ POL)
- MongoDB (Optional, but recommended for production)
# Clone the repository
git clone https://github.com/tomharvey1128/polymarket_copy_trading_bot.git
cd polymarket_copy_trading_bot
# Install dependencies
npm install
# Build the project
npm run build- Create environment file:
cp .env.example .env- Edit
.envwith your settings:
# Required: Basic Configuration
TARGET_ADDRESS=0x1234567890123456789012345678901234567890
PRIVATE_KEY=0x0000000000000000000000000000000000000000000000000000000000000000
# Copy Trading Configuration
COPY_TRADING_ENABLED=true
DRY_RUN=true # ⚠️ ALWAYS test with true first!
POSITION_SIZE_MULTIPLIER=1.0 # 0.5 = 50%, 1.0 = 100%, 2.0 = 200%
MAX_POSITION_SIZE=10000
MAX_TRADE_SIZE=5000
MIN_TRADE_SIZE=1
SLIPPAGE_TOLERANCE=1.0
# Monitoring Configuration
POLL_INTERVAL=30000 # 30 seconds- Run the bot:
# Development mode
npm run dev
# Production mode
npm start| Variable | Description | Example |
|---|---|---|
TARGET_ADDRESSES |
Comma-separated addresses to monitor | 0xabc...,0xdef... |
PUBLIC_KEY |
Your Polygon wallet address | 0xYourWalletAddress |
PRIVATE_KEY |
Your wallet private key | 0xYourPrivateKey |
RPC_URL |
Polygon RPC endpoint (must support pending tx) | https://polygon-mainnet.infura.io/v3/... |
Trading Parameters
FETCH_INTERVAL=1 # API polling interval (seconds)
MIN_TRADE_SIZE_USD=100 # Minimum trade size to frontrun (USD)
FRONTRUN_SIZE_MULTIPLIER=0.5 # Frontrun size as % of target (0.0-1.0)
GAS_PRICE_MULTIPLIER=1.2 # Gas price multiplier (1.2 = 20% higher)
USDC_CONTRACT_ADDRESS=0x2791... # USDC contract (default: Polygon mainnet)
RETRY_LIMIT=3 # Maximum retry attempts for failed ordersRisk Management
MAX_SLIPPAGE_PERCENT=2.0 # Maximum acceptable slippage (default: 2.0%)
MAX_POSITION_SIZE_USD=10000 # Maximum position size per market (USD)
MAX_TOTAL_EXPOSURE_USD=50000 # Maximum total exposure across all positions (USD)Infrastructure
MONGO_URI=mongodb://localhost:27017/polymarket-bot
HEALTH_CHECK_PORT=3000
TRADE_AGGREGATION_ENABLED=false
TRADE_AGGREGATION_WINDOW_SECONDS=300graph LR
A[Monitor Addresses] --> B[Detect Trades]
B --> C[Extract Details]
C --> D[Risk Validation]
D --> E[Execute Trade]
E --> F[Track Position]
- Address Monitoring - Bot monitors specified Polymarket trader addresses
- Trade Detection - Detects trades in real-time via API polling
- Signal Processing - Extracts trade details (market, outcome, side, size, price)
- Risk Validation - Validates minimum trade size, position limits, exposure limits, balance, and slippage
- Order Execution - Submits market order with configured position multiplier
- Position Tracking - Records position for ongoing management
- Mempool Detection - Monitor Polygon mempool for pending transactions
- API Monitoring - Poll Polymarket API for recent trades
- Signal Generation - Extract trade details, gas price, and transaction hash
- Gas Calculation - Calculate frontrun gas:
target_gas × GAS_PRICE_MULTIPLIER - Risk Checks - Validate all risk parameters
- Order Execution - Submit market order with priority gas price
- Position Tracking - Record position for management
Access real-time bot metrics via HTTP endpoints:
# Health check
curl http://localhost:3000/health
# Detailed metrics
curl http://localhost:3000/metricsAvailable Metrics:
- ⏱️ Uptime
- 📊 Trades executed/failed
- 🕐 Last trade timestamp
- 💰 Wallet balances (POL and USDC)
- ❌ Error history
- ✅ Health status
MongoDB is highly recommended for production to prevent duplicate trade execution.
Quick Setup:
# Option 1: Local MongoDB
mongod --dbpath /path/to/data
# Option 2: MongoDB Atlas (Cloud)
# Create free cluster at https://www.mongodb.com/cloud/atlasConnection String:
MONGO_URI=mongodb://localhost:27017/polymarket-bot
# or
MONGO_URI=mongodb+srv://user:pass@cluster.mongodb.net/polymarket-botRecommended Providers:
| Provider | Free Tier | WebSocket Support |
|---|---|---|
| Infura | ✅ Yes | ✅ Yes |
| Alchemy | ✅ Yes | ✅ Yes |
| QuickNode | ✅ Yes | ✅ Yes |
| Ankr | ✅ Yes |
Note: Free tier providers may have rate limits. For production, consider premium providers with WebSocket support.
For Fast Detection
FETCH_INTERVAL=0.5 # Faster polling (higher API load)
GAS_PRICE_MULTIPLIER=1.5 # Higher gas = better frontrun successFor Cost Efficiency
MIN_TRADE_SIZE_USD=500 # Only frontrun larger trades
FRONTRUN_SIZE_MULTIPLIER=0.3 # Smaller position sizes
GAS_PRICE_MULTIPLIER=1.1 # Lower gas costsFor Risk Management
MAX_SLIPPAGE_PERCENT=1.0 # Stricter slippage control
MAX_POSITION_SIZE_USD=5000 # Smaller position limits
MAX_TOTAL_EXPOSURE_USD=25000 # Lower total exposureBot not detecting trades
- ✅ Verify
TARGET_ADDRESSESare correct and active - ✅ Check RPC URL supports pending transaction monitoring
- ✅ Increase
FETCH_INTERVALif network is slow - ✅ Verify
MIN_TRADE_SIZE_USDthreshold
Orders failing
- ✅ Check USDC balance
- ✅ Verify POL/MATIC balance for gas (>0.2 POL recommended)
- ✅ Confirm RPC endpoint is accessible
- ✅ Check market is still active
High gas costs
- ✅ Lower
GAS_PRICE_MULTIPLIER(e.g., 1.1 instead of 1.2) - ✅ Increase
MIN_TRADE_SIZE_USDto only frontrun larger trades - ✅ Monitor network congestion
MongoDB connection errors
- ✅ Verify MongoDB is running
- ✅ Check connection string format
- ✅ Ensure network access if using cloud MongoDB
- ℹ️ Bot will continue without MongoDB (in-memory only)
| Command | Description |
|---|---|
npm run dev |
Development mode with hot reload |
npm run build |
Compile TypeScript to JavaScript |
npm start |
Production mode |
npm run lint |
Run ESLint linter |
npm run lint:fix |
Automatically fix linting errors |
npm run check-allowance |
Check token allowance for USDC |
npm run set-token-allowance |
Set token allowance for trading |
npm run manual-sell |
Manually sell positions |
npm run simulate |
Run simulation/backtesting |
- 🔒 Never commit
.envfile - Add to.gitignore - 🔑 Use environment variables - Store secrets securely
- 🔄 Rotate private keys - Regularly update credentials
- 📊 Monitor balances - Set up alerts for unusual activity
- 💼 Use hardware wallets - For production deployments
- 🛡️ Limit permissions - Use minimum required wallet permissions
- 📖 Complete Setup Guide - Detailed setup and configuration
- 💡 Example Transactions - View successful trades
- 🐛 Troubleshooting - Common issues and solutions
Contributions are welcome! Please feel free to submit a Pull Request.
- 🍴 Fork the repository
- 🌿 Create your feature branch (
git checkout -b feature/AmazingFeature) - 💾 Commit your changes (
git commit -m 'Add some AmazingFeature') - 📤 Push to the branch (
git push origin feature/AmazingFeature) - 🔀 Open a Pull Request
- 🔌 WebSocket mempool monitoring
- 📊 Advanced strategy backtesting
- 🖥️ Web dashboard UI
- 📱 Telegram notifications
- 👛 Multi-wallet support
- 📈 Advanced position management
- 💰 PnL tracking and reporting
IMPORTANT LEGAL DISCLAIMER
This software is provided "as-is" for educational and research purposes only. Trading cryptocurrencies and prediction markets involves substantial risk of loss.
| Warning | |
|---|---|
| 🚫 | No Warranty - The software is provided without any warranties |
| ⚡ | Use at Your Own Risk - You are solely responsible for any losses incurred |
| 📚 | Not Financial Advice - This is not investment or trading advice |
| ⚖️ | Compliance - Ensure compliance with local laws and regulations |
| 🧪 | Testing - Always test with small amounts first |
| ⚖️ | Legal - Frontrunning may have legal and ethical implications in some jurisdictions |
The authors and contributors are not responsible for any financial losses, damages, or legal issues arising from the use of this software.