neuralCPL/polymarket-trading-bot
polymarket trading bot, polymarket arbitrage bot, polymarket trading bot, polymarket arbitrage bot, polymarket trading bot, polymarket arbitrage bot, polymarket trading bot, polymarket arbitrage bot, polymarket trading bot, polymarket arbitrage bot, polymarket trading bot, polymarket arbitrage bot, polymarket trading bot, polymarket arbitrage bot,
项目说明
🤖 Polymarket BTC Up/Down Trading Bot
A production-ready Node.js trading bot for Polymarket's fast-paced 5-minute markets
Repository: github.com/neuralCPL/polymarket-trading-bot
🎯 Why This Bot?
You need trading software that actually works in production, not a toy script. This is it.
| Feature | What You Get |
|---|---|
| ✅ Real CLOB Auth | Full Polymarket authentication & order execution on Polygon |
| ✅ On-Chain Integration | Approvals, merges, and redemptions built in |
| ✅ Live Order Book | WebSocket monitoring with intelligent fallbacks |
| ✅ Safety First | Risk limits, circuit breakers, graceful shutdowns |
| ✅ Copy Trading | Mirror selected wallets automatically |
🚀 What This Bot Does
Core Strategy: Arbitrage + Copy Trading
The Main Arbitrage Engine:
- 📍 Finds the next BTC Up/Down 5-min market
- 📊 Posts buy ladders on both sides
- ⚡ Executes arbitrage when prices align
- 🔄 Merges matched pairs back into USDC
- 💰 Redeems winning positions after resolution
Plus: Integrated wallet-following and a dedicated copy-trading module for high-frequency mimics.
📋 Before You Start
You'll Need:
- ✔️ Node.js 18+
- ✔️ Polymarket account (with proxy wallet)
- ✔️ Polygon EOA private key
- ✔️ USDC on Polygon
- ✔️ Native MATIC for gas
- ✔️ Reliable Polygon RPC endpoint
We Recommend:
- 🔐 Use a dedicated wallet for bot operations
- 💰 Start with small size caps (really small)
- 🔌 Use a private RPC instead of public endpoints
- 🧪 Test everything with
COPY_DRY_RUN=truefirst
⚡ Quick Start (5 Minutes)
1️⃣ Install
npm install
2️⃣ Configure
cp .env.example .env
Then fill in these required fields:
PRIVATE_KEY— Your Polygon signerPROXY_WALLET— Your Polymarket proxy addressPOLYGON_RPC— Your Polygon RPC URL
3️⃣ Run
npm start
That's it. Your bot is now:
- Discovering markets
- Posting ladders
- Executing trades
- Logging everything to
bot.log
🛠️ Configuration Guide
Essential Settings
| Setting | Purpose | Example |
|---|---|---|
PRIVATE_KEY | Polygon signer for approvals & orders | 0x... |
PROXY_WALLET | Your Polymarket proxy address | 0x... |
POLYGON_RPC | Polygon RPC endpoint | https://... |
LOG_LEVEL | Logging verbosity | info, debug |
Strategy Controls
These shape how aggressively your bot trades:
# How much to spend per market
MAX_SPEND_PER_MARKET=1000
# Minimum edge before firing arb (e.g., 0.02 = 2%)
TARGET_EDGE=0.02
# Merge pairs when they reach this size
MERGE_THRESHOLD_USDC=500
# Maximum single taker order size
MAX_TAKER_FILL_USDC=200
# Stop if combined asks get too expensive
COMBINED_ASK_STOP=0.98
# Hourly loss limit (circuit breaker)
MAX_LOSS_PER_HOUR_USDC=500
# How many price levels to post on
LADDER_LEVELS=5
# How much per level
LADDER_SIZE_PER_LEVEL_USDC=100
Copy Trading: Two Modes
🎬 Integrated Mode (Mirror during main run)
TARGET_WALLET=0x...
COPY_TRADE_BUY_PERCENT=50
COPY_TRADE_POLL_MS=1000
Snapshots a target wallet and mirrors future buys.
🎯 Dedicated Mode (Buy-only, high-frequency)
COPY_TARGETS=0xWallet1,0xWallet2
COPY_SIZE_MODE=FIXED
COPY_FIXED_USDC=100
COPY_MAX_USDC_PER_TRADE=500
COPY_MAX_USDC_PER_HOUR=2000
COPY_DRY_RUN=true # Enable to test first!
Polls public trade data and reacts immediately.
🎮 Running Modes
Main Arbitrage Bot
npm start
or explicitly:
npm run arb
Development Mode (auto-reload)
npm run dev
Dedicated Copy Trader
node src/copy/index.js
📁 What's Inside
src/
├── index.js # Main bot lifecycle
├── trader.js # Per-market state machine
├── market.js # Polymarket API helpers
├── clob.js # CLOB client & auth
├── onchain.js # Approvals, merge, redeem
├── copy-trader.js # Integrated copy watcher
├── pnl.js # Profit/loss tracking
├── logger.js # Structured logging
└── copy/
├── index.js # Copy trader entrypoint
├── activityFeed.js # Trade polling
├── copyTrader.js # Copy execution
└── config.js # Copy settings
🔒 Risk Controls (Built-In)
Your bot has multiple safety mechanisms:
| Control | What It Does |
|---|---|
MAX_SPEND_PER_MARKET | Caps spending per 5-min cycle |
MAX_TAKER_FILL_USDC | Caps single order size |
MAX_INVENTORY_IMBALANCE_USDC | Prevents lopsided positions |
COMBINED_ASK_STOP | Stops buying if market gets too expensive |
MAX_LOSS_PER_HOUR_USDC | Hourly loss circuit breaker |
STOP_BUYING_BEFORE_CLOSE | Prevents last-minute risk |
These aren't optional. They define how your bot behaves.
📊 Logging & Monitoring
Your bot logs to two places:
Console → Colored, real-time output
bot.log → JSON structured logs (file)
Use these to:
- 📈 Monitor live trading
- 🐛 Debug failures
- 📋 Review order history
- ⏱️ Analyze timing & slippage
⚠️ Safety First
DO ✅
- Start with small caps and scale gradually
- Use a dedicated wallet for bot operations
- Test copy logic with
COPY_DRY_RUN=true - Review
bot.logafter each session - Use a private RPC for reliability
- Keep extra MATIC for gas
DON'T ❌
- Start with large sizing
- Use a wallet with unrelated funds
- Assume public RPC is production-ready
- Skip the
.env.examplecomments - Forget to verify your proxy wallet address
- Run without understanding the strategy
🆘 Troubleshooting
Bot exits immediately?
✓ Check .env has PRIVATE_KEY and PROXY_WALLET
✓ Verify values are not empty
✓ For copy trading, also check COPY_TARGETS
Orders failing or can't authenticate?
✓ Confirm signer matches your Polymarket account
✓ Verify PROXY_WALLET is correct for that signer
✓ Try a stable private RPC endpoint
✓ Leave POLY_API_* blank to auto-derive credentials
Copy trades not firing?
✓ Check target wallet is lowercased
✓ Verify target is placing fresh BUY orders
✓ Make sure spend caps aren't too restrictive
✓ Confirm COPY_DRY_RUN is set as intended
Merge or redeem failing?
✓ Did approvals complete successfully?
✓ Do you have enough matched positions?
✓ Is the market actually resolved?
✓ Check bot.log for the error details
🚦 Your First Run (Safest Path)
- Fill
.envwith real wallet values - Use a private RPC for stability
- Lower spend caps significantly (like 25% of what you think)
- Run with small sizing and watch the logs
- If testing copy: set
COPY_DRY_RUN=truefirst - Review bot.log after 1-2 markets
- Scale up gradually only if everything looks good
📸 Performance Examples
The bot in action:
- 1D Performance — See daily profits/losses
- Weekly Snapshot — Rolling week performance
- All-Time View — Long-term trends
- Activity Log — Real trades, real fills
(See img/ folder for screenshots)
🔑 Advanced: CLOB Credentials
The bot can auto-derive CLOB credentials from your signer:
# Leave these blank on first run
POLY_API_KEY=
POLY_API_SECRET=
POLY_API_PASSPHRASE=
# Bot will generate them automatically
If you want to supply them manually, get them from Polymarket CLOB docs.
💡 Strategy Deep Dive
The Arbitrage Loop
- Wait for open → Discover next market, idle until trading window
- Post ladder → Place buy orders at N price levels on both Up and Down
- Monitor book → WebSocket feed tracks best asks (REST fallback available)
- Fire arb → When
bestAskUp + bestAskDown < 1 - TARGET_EDGE, buy both sides - Merge pairs → If you hold enough matched pairs, merge back to USDC
- Close out → Stop buying as market approaches end, cancel orders
- Wait & redeem → After resolution, redeem winning positions
The Copy Trading Flow
Integrated Mode:
- Snapshots target wallet on startup
- Monitors for new buy activity
- Mirrors increases at
COPY_TRADE_BUY_PERCENT
Dedicated Mode:
- Polls target wallet trades every
COPY_POLL_MS - Filters by price, slippage, staleness
- Executes within spend caps
- Supports multiple targets
📚 File Reference
| File | Purpose |
|---|---|
src/index.js | Main loop, market discovery, graceful shutdown |
src/trader.js | Per-market state machine (ladder, arb, merge, redeem) |
src/market.js | Polymarket API (discovery, positions, resolution) |
src/clob.js | CLOB REST + WebSocket, auth, order signing |
src/onchain.js | Polygon approvals, balances, merge, redeem TXs |
src/copy-trader.js | Integrated target wallet mirroring |
src/copy/activityFeed.js | High-freq trade polling |
src/copy/copyTrader.js | Copy execution with filters & accounting |
🎓 Tips & Tricks
For Maximum Reliability
- Use Alchemy or Infura private RPC (not free public endpoints)
- Keep 2-3x gas reserves in your wallet
- Monitor bot.log in a separate terminal
For Copy Trading
- Start with tiny caps (
COPY_FIXED_USDC=10) - Use
COPY_DRY_RUN=truefor your first session - Pick proven traders for target wallets
- Set
COPY_MAX_SLIPPAGEstrictly (0.01 = 1%)
For Arbitrage
- Lower
TARGET_EDGEto catch more opportunities (but with more risk) - Increase
LADDER_LEVELSto post wider (but more capital tied up) - Reduce
STOP_BUYING_BEFORE_CLOSEto trade longer (but more tail risk)
⚖️ Disclaimer
This software is for research and experienced operators only. It is:
- ❌ NOT financial advice
- ❌ NOT a guaranteed money machine
- ⚠️ Full of risks: market risk, execution risk, smart contract risk, RPC risk, operational risk
You are 100% responsible for:
- How you configure it
- How you use it
- What happens when you run it
- All losses (and yes, there will be losses)
Real-money trading is serious. Use this code wisely.
🤝 Need Help?
- Check
bot.log— most errors are logged there - Review
.env.example— comments explain each setting - Read the strategy section above — understand what the bot is doing
- Start smaller — if in doubt, reduce all caps by 10x and try again
Ready to go? Run npm install and update that .env file. Good luck! 🚀
