A professional, industry-ready cryptocurrency arbitrage trading bot. This bot automatically detects circular arbitrage opportunities and executes profitable trades between various tokens with advanced risk management and safety features.
- π Automated Arbitrage: Detects and executes circular arbitrage opportunities (Token A β Token B β Token A)
- ποΈ Multi-Token Support: Trade between POL, USDC, USDT, WETH with dynamic pair selection
- π Real-time Monitoring: Continuously scans prices across multiple fee tiers (0.05%, 0.3%, 1%)
- π‘οΈ Advanced Risk Management: Built-in slippage protection, gas optimization, and balance validation
- π Simulation Mode: Safe testing environment to validate strategies without real money
- β‘ Gas Optimization: Smart gas price management and transaction batching
- π Performance Tracking: Comprehensive trade statistics and profit monitoring
- π Production Ready: Professional error handling, logging, and recovery mechanisms
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β UNISWAP TRADING BOT β
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ€
β π§ Brain: JavaScript Class (UniswapTradingBot) β
β π Network: Polygon Blockchain β
β π° Protocol: Uniswap V3 DEX β
β π Strategy: Circular Arbitrage β
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
// Connection Layer
Provider (RPC) βββββΊ Polygon Network βββββΊ Uniswap V3 Contracts
β β β
Your Bot βββββββββ Transaction βββββββββββ Smart ContractKey Smart Contracts:
- Quoter V1:
0xb27308f9F90D607463bb33eA1BeBb41C27CE5AB6(Price quotes) - SwapRouter:
0xE592427A0AEce92De3Edee1F18E0157C05861564(Trade execution) - Factory:
0x1F98431c8aD98523631AE4a59f267346ea31F984(Pool verification) - WPOL:
0x0d500B1d8E8eF31E21C99d1Db9A6444d3ADf1270(Wrapped POL)
Supported Tokens:
βββ POL (Native) ββββ 18 decimals ββββ Gas & Trading
βββ USDC ββββββββββββ 6 decimals βββββ Stablecoin
βββ USDT ββββββββββββ 6 decimals βββββ Stablecoin
βββ WETH ββββββββββββ 18 decimals ββββ Ethereum
βββ WBTC ββββββββββββ 8 decimals βββββ Bitcoin POL USDC USDT WETH
POL - β
β
β
USDC β
- β
β
USDT β
β
- β
WETH β
β
β -
1. Load Environment Variables (.env)
βββ Private Key, RPC URL
βββ Trading Parameters
βββ Safety Settings
2. Connect to Blockchain
βββ Create Provider (Polygon RPC)
βββ Initialize Wallet
βββ Setup Contract Interfaces
3. Test Quoter Contracts
βββ Try QuoterV2 (fallback available)
βββ Use QuoterV1 β
(proven reliable)
βββ Validate with test quote
4. Ready to Trade! π
Every 90 seconds (configurable):
1. Check Account Balances
βββ POL: 10.791436
βββ USDT: 1.120141
βββ Others: 0.000000
2. Scan All Trading Pairs
βββ POL β USDC
βββ POL β USDT β Found 2.57% profit!
βββ POL β WETH
βββ USDC β USDT
βββ USDC β WETH
3. For Each Pair, Calculate Arbitrage
Example: POL β USDT β POL
Step 1: Get Quote POL β USDT
βββ Input: 1 POL
βββ Check Fee Tiers: 0.05%, 0.3%, 1%
βββ Best Quote: 0.240782 USDT (0.3% fee)
βββ Price: 1 POL = 0.240782 USDT
Step 2: Get Quote USDT β POL
βββ Input: 0.240782 USDT
βββ Check Fee Tiers: 0.05%, 0.3%, 1%
βββ Best Quote: 1.025684 POL (0.3% fee)
βββ Price: 0.240782 USDT = 1.025684 POL
Step 3: Calculate Profit
βββ Initial: 1.000000 POL
βββ Final: 1.025684 POL
βββ Profit: 0.025684 POL
βββ Percentage: 2.57% β
(Above 1.5% threshold)
1. Validate Trade Amount
βββ Available: 10.791436 POL
βββ Configured: 0.3 POL
βββ Using: 0.3 POL β
2. Get Fresh Quote (right before execution)
βββ Input: 0.3 POL
βββ Expected: 0.072235 USDT
βββ Min Expected (3% slippage): 0.070068 USDT
3. Prepare Swap Parameters
βββ tokenIn: WPOL address
βββ tokenOut: USDT address
βββ fee: 3000 (0.3%)
βββ recipient: Your Wallet
βββ deadline: Now + 10 minutes
βββ amountIn: 300000000000000000 (0.3 POL in wei)
βββ amountOutMinimum: 70068 (min USDT)
βββ sqrtPriceLimitX96: 0
4. Execute Transaction
βββ Estimate Gas: ~185,000
βββ Submit Transaction
βββ Wait for Confirmation
βββ β
Success: Received ~0.072235 USDT1. Check Received Amount
βββ Wait 5 seconds for balance update
βββ Query USDT balance
βββ Found: 0.072235 USDT
2. Get Fresh Quote USDT β POL
βββ Input: 0.072235 USDT
βββ Expected: 0.307764 POL
βββ Min Expected (3% slippage): 0.298532 POL
3. Execute Second Swap
βββ Same process as Step 1
βββ USDT β POL conversion
βββ β
Success: Received ~0.307764 POL
4. Calculate Final Profit
βββ Initial POL: 10.791436
βββ Final POL: 11.099200
βββ Net Profit: +0.007764 POL
βββ Actual Profit %: 2.59%β
Slippage Protection: Minimum 3% buffer
β
Fresh Quotes: Real-time pricing before execution
β
Gas Estimation: Pre-calculate transaction costs
β
Balance Validation: Check funds before trading
β
Pool Verification: Ensure liquidity exists
β
Error Recovery: Continue despite individual failuresβ
Multi-Fee Tier Scanning: 0.05%, 0.3%, 1%
β
Best Route Selection: Highest output amount
β
Gas Price Optimization: Smart fee calculation
β
Trade Size Management: Risk-appropriate amountsβ
Real-time Balance Tracking
β
Performance Statistics
β
Detailed Transaction Logs
β
Error Reporting & Recovery
β
Profit/Loss TrackingProfit = (Amount Γ Rate1 Γ Rate2) - Amount - Fees
Where:
- Amount = Trade size (0.3 POL)
- Rate1 = POLβUSDT rate (0.240782)
- Rate2 = USDTβPOL rate (4.262847)
- Fees = Gas costs + Uniswap fees (0.6% total)
Example:
Profit = (1 Γ 0.240782 Γ 4.262847) - 1 - 0.006
Profit = 1.025684 - 1 - 0.006 = 0.019684 POL (1.97%)
β
Profit > MIN_PROFIT_PERCENTAGE (1.5%)
β
Available Balance > Trade Amount
β
Network Gas < MAX_GAS_PRICE
β
Pool Liquidity Sufficient
β
No Pending Transactions
T+0s: π Scan for opportunities
T+1s: π Calculate POLβUSDTβPOL profit: 2.57%
T+2s: β
Opportunity confirmed (above 1.5% threshold)
T+3s: π Begin Step 1: POLβUSDT
T+4s: π Get fresh quote: 0.3 POL = 0.072235 USDT
T+5s: β½ Estimate gas: 185,000
T+6s: π Submit transaction 1
T+18s: β
Transaction 1 confirmed
T+23s: π Begin Step 2: USDTβPOL
T+24s: π Get fresh quote: 0.072235 USDT = 0.307764 POL
T+25s: π Submit transaction 2
T+37s: β
Transaction 2 confirmed
T+42s: π Arbitrage complete! Profit: 0.007764 POL
Total Time: ~42 seconds per arbitrage cycle
- β Arbitrage Profits: 1.5-5% per successful trade
- β Compound Growth: Reinvesting profits increases trade size
- β Gas Fees: ~$0.01-0.05 per transaction (2 tx per arbitrage)
- β Uniswap Fees: 0.05-1% per swap (depends on pool)
- β Slippage: 1-3% maximum protection
Minimum Profitable Trade:
Gas Cost ($0.03) + Uniswap Fees (0.6%) + Buffer (1%) = ~2.6%
Bot Threshold: 1.5% + 1% buffer = 2.5% β
Success Rate: High (conservative settings)
- Node.js v16 or higher
- NPM or Yarn package manager
- Polygon wallet with POL for gas fees
- Basic understanding of DeFi and trading risks
- RPC endpoint (free options available)
- Clone or create the project:
mkdir uniswap-trading-bot
cd uniswap-trading-bot- Install dependencies:
npm install ethers axios dotenv- Create environment file:
cp .env.example .env- Configure your settings in
.env:
# Required Settings
PRIVATE_KEY=0x1234...your_private_key_here
POLYGON_RPC_URL=https://polygon.llamarpc.com
# Trading Parameters
MIN_PROFIT_PERCENTAGE=1.5
TRADE_AMOUNT=0.3
SLIPPAGE_TOLERANCE=3.0
CHECK_INTERVAL=90000
# Safety Features
SIMULATION_MODE=true| Variable | Description | Default | Recommended |
|---|---|---|---|
PRIVATE_KEY |
Your wallet private key | Required | Use dedicated trading wallet |
POLYGON_RPC_URL |
Polygon network RPC URL | Required | https://polygon.llamarpc.com |
MIN_PROFIT_PERCENTAGE |
Minimum profit % to trade | 1.0 | 1.5 |
TRADE_AMOUNT |
Base trade amount | 10 | 0.3 |
SLIPPAGE_TOLERANCE |
Slippage tolerance % | 0.5 | 3.0 |
CHECK_INTERVAL |
Price check interval (ms) | 60000 | 90000 |
SIMULATION_MODE |
Safe testing mode | false | true (for testing) |
MAX_GAS_PRICE |
Maximum gas price (gwei) | 100 | 100 |
# Risk Management
MAX_TRADE_SIZE=1000
MAX_DAILY_TRADES=50
STOP_LOSS_PERCENTAGE=5.0
# Performance Optimization
GAS_LIMIT=300000
RETRY_ATTEMPTS=3
TIMEOUT_SECONDS=30
# Monitoring (Optional)
TELEGRAM_BOT_TOKEN=your_telegram_token
DISCORD_WEBHOOK_URL=your_discord_webhooknode test.jsExpected output:
π§ͺ Testing Uniswap Trading Bot Connection...
β
Connected to matic (Chain ID: 137)
β
Wallet connected: 0x1234...5678
β
QuoterV1 working! Test quote: 1 POL = 0.2337 USDC
β
Using quoter: 0xb27...AB6
π All tests completed successfully!
# Ensure SIMULATION_MODE=true in .env
node bot.jsExpected output:
π Uniswap Trading Bot Initialized
π Mode: SIMULATION (Safe)
π― ARBITRAGE OPPORTUNITY FOUND!
π° Potential Profit: 0.025684 POL (2.57%)
π SIMULATION MODE - No real trades executed
π Would execute:
Step 1: 0.3 POL -> USDT
Step 2: 0.072235 USDT -> POL
Expected final: 0.325684 POL
π Simulation Stats: 1 trades, 0.025684 POL profit
# Update .env: SIMULATION_MODE=false
node bot.jsExpected output:
π― ARBITRAGE OPPORTUNITY FOUND!
π° Potential Profit: 0.025684 POL (2.57%)
π Step 1: 0.300000 POL -> USDT
π Executing swap: 0.3 POL -> USDT
π Getting fresh quote...
π± Quote: 0.3 POL = 0.072235 USDT (Fee: 0.3%)
π‘οΈ Min expected (3% slippage): 0.070068 USDT
β½ Gas estimate: 185420
π Submitting transaction...
β³ Transaction submitted: 0x1234...5678
β
Swap completed successfully!
π Step 2: 0.072235 USDT -> POL
[Second transaction execution...]
π ARBITRAGE COMPLETED!
π Initial: 10.791436 POL
π Final: 10.799200 POL
π° Actual Profit: 0.007764 POL
π Total Trades: 1, Total Profit: 0.007764 POL
# β
DO:
- Use a dedicated trading wallet with limited funds
- Store private key in .env file (never commit to git)
- Consider hardware wallet integration for key management
- Regularly rotate keys and monitor transactions
# β DON'T:
- Use your main wallet with large holdings
- Share private keys or commit them to version control
- Run on shared/public computers
- Ignore security warnings# β
DO:
- Start with small trade amounts (0.1-0.5 POL)
- Test thoroughly in simulation mode
- Set appropriate stop-loss levels
- Monitor gas prices during high network activity
- Keep some POL reserved for gas fees
# β DON'T:
- Trade with funds you can't afford to lose
- Set trade amounts higher than your balance
- Ignore slippage warnings
- Run without monitoring for extended periods# β
DO:
- Use reputable RPC providers (Polygon official, Alchemy, Infura)
- Implement IP whitelisting if possible
- Monitor for unusual network activity
- Have backup RPC endpoints ready
# β DON'T:
- Use untrusted or unknown RPC providers
- Ignore network connectivity issues
- Run without backup configurations1. "Too little received" Error:
# Cause: High slippage or market movement
# Solution: Increase SLIPPAGE_TOLERANCE to 3-5%
SLIPPAGE_TOLERANCE=3.02. "Insufficient balance" Error:
# Cause: Not enough tokens for trade
# Solution: Reduce TRADE_AMOUNT or add more tokens
TRADE_AMOUNT=0.1 # Reduce trade size3. "Missing revert data" Error:
# Cause: QuoterV2 compatibility issues
# Solution: Bot automatically uses QuoterV1 (working correctly)
β
Using quoter: 0xb27308f9F90D607463bb33eA1BeBb41C27CE5AB64. "No profitable opportunities" Error:
# Cause: Market conditions or high thresholds
# Solution: Lower profit threshold temporarily
MIN_PROFIT_PERCENTAGE=1.0 # Lower threshold5. RPC Connection Issues:
# Try alternative RPC endpoints:
POLYGON_RPC_URL=https://rpc.ankr.com/polygon
# or
POLYGON_RPC_URL=https://polygon-rpc.com# Enable detailed logging
DEBUG_MODE=true
LOG_TRADES=true# For faster execution:
CHECK_INTERVAL=30000 # Check every 30 seconds
SLIPPAGE_TOLERANCE=2.0 # Lower slippage (higher risk)
# For stability:
CHECK_INTERVAL=120000 # Check every 2 minutes
SLIPPAGE_TOLERANCE=5.0 # Higher slippage (lower risk)# Premium RPC providers for faster response times:
- Alchemy: https://polygon-mainnet.g.alchemy.com/v2/YOUR_KEY
- Infura: https://polygon-mainnet.infura.io/v3/YOUR_KEY
- QuickNode: Your custom endpoint# Monitor network congestion:
- Use gas tracker websites
- Adjust MAX_GAS_PRICE based on network conditions
- Consider trading during low-traffic hours# Optimal trading conditions:
- Low network congestion (lower gas fees)
- High trading volume (more arbitrage opportunities)
- Market volatility (price discrepancies)# High-liquidity pairs for better opportunities:
β
POL/USDC (most liquid)
β
POL/USDT (stable pair)
β
USDC/USDT (stablecoin arbitrage)
β οΈ POL/WETH (higher volatility)
β Small cap tokens (low liquidity)- High Risk: Cryptocurrency trading involves significant financial risk
- No Guarantees: Past performance doesn't guarantee future results
- Market Risk: DeFi markets are highly volatile and unpredictable
- Smart Contract Risk: Protocols may have bugs or vulnerabilities
- Impermanent Loss: Market movements can cause losses
- Software Bugs: Code may contain errors or unexpected behavior
- Network Risk: Blockchain congestion can cause failed transactions
- RPC Failures: External services may become unavailable
- Gas Price Volatility: Transaction costs can vary significantly
- Regulatory Risk: Ensure compliance with local trading regulations
- Tax Obligations: Trading profits may be subject to taxation
- KYC/AML: Some jurisdictions require identity verification
- Professional Advice: Consult legal and financial professionals
- Private Key Security: Loss of keys means loss of funds
- Operational Errors: Incorrect configuration can cause losses
- Monitoring Required: Automated systems need human oversight
- Emergency Procedures: Have plans for stopping bot operation
- Check Troubleshooting Section: Most issues are covered above
- Review Error Messages: Bot provides detailed error information
- Test Configuration: Use
node test.jsto verify setup - Start Small: Begin with small trade amounts in simulation mode
- Education: Understand DeFi, Uniswap, and arbitrage concepts
- Testing: Thoroughly test in simulation mode before live trading
- Monitoring: Regularly check bot performance and market conditions
- Risk Management: Never trade more than you can afford to lose
- Continuous Learning: Stay updated on market trends and technology
- Report bugs and issues with detailed logs
- Suggest improvements and new features
- Share successful configuration strategies
- Help other users in community discussions
MIT License - Use at your own risk. See LICENSE file for details.
π― Ready to Start?
- Run
node test.jsto verify setup - Enable
SIMULATION_MODE=truefor safe testing - Start with small
TRADE_AMOUNTvalues - Monitor performance and adjust parameters
- Only enable live trading when confident
Happy Trading! ππ°