pam ▸ ARBITRAGE_README.md
updated 2026-03-15

Crypto Arbitrage System

Overview

The Crypto Arbitrage System is a new module added to Unicorn.Land that identifies and executes arbitrage opportunities between Kalshi and Polymarket for crypto price prediction markets. The system monitors 5 major cryptocurrencies (BTC, ETH, SOL, XRP, DOGE) and automatically finds price discrepancies that can be exploited for profit.

Architecture

Core Components

  1. CryptoArbitrageScanner (arbitrage/crypto_scanner.py) - Scans both Kalshi and Polymarket for crypto price prediction markets - Matches equivalent markets across platforms - Filters opportunities based on spread and volume requirements

  2. SpreadAnalyzer (arbitrage/spread_analyzer.py) - Calculates spread percentages between platforms - Analyzes risk metrics and expected value - Determines optimal trading direction

  3. KellyOptimizer (arbitrage/kelly_optimizer.py) - Calculates optimal position sizes using Kelly Criterion - Manages portfolio allocation across multiple opportunities - Validates position sizes against risk limits

  4. ArbitrageExecutor (arbitrage/arbitrage_executor.py) - Executes trades on both platforms - Handles dry-run and live trading modes - Manages order placement and execution tracking

  5. PolymarketAPI (arbitrage/polymarket_api.py) - Integrates with Polymarket API - Fetches market data and prices - Handles rate limiting and error management

Database Schema

The system extends the existing SQLite database with two new tables:

-- Arbitrage opportunities found
CREATE TABLE arbitrage_opportunities (
    id INTEGER PRIMARY KEY AUTOINCREMENT,
    kalshi_market_id TEXT,
    polymarket_market_id TEXT,
    crypto_symbol TEXT,
    spread_percentage REAL,
    kalshi_price REAL,
    polymarket_price REAL,
    expected_profit REAL,
    risk_score REAL,
    volume_kalshi REAL,
    volume_polymarket REAL,
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
    status TEXT DEFAULT 'pending'
);

-- Arbitrage trades executed
CREATE TABLE arbitrage_trades (
    id INTEGER PRIMARY KEY AUTOINCREMENT,
    opportunity_id INTEGER,
    kalshi_position_size REAL,
    polymarket_position_size REAL,
    total_investment REAL,
    expected_return REAL,
    status TEXT,
    executed_at TIMESTAMP,
    FOREIGN KEY (opportunity_id) REFERENCES arbitrage_opportunities(id)
);

Configuration

config.yaml

Add the following section to your config.yaml:

arbitrage:
  enabled: true
  crypto_allocation:
    BTC: 0.40  # 40% allocation
    ETH: 0.25  # 25% allocation
    SOL: 0.20  # 20% allocation
    XRP: 0.10  # 10% allocation
    DOGE: 0.05 # 5% allocation
  risk_management:
    min_spread: 0.05              # 5% minimum spread
    max_position_size: 0.08       # 8% of bankroll per opportunity
    kelly_fraction: 0.25          # Conservative Kelly Criterion
    auto_execute_threshold: 0.20  # Auto-execute if spread > 20%
  scanning:
    interval_minutes: 5           # Scan every 5 minutes
    max_opportunities_per_scan: 10
  platforms:
    kalshi:
      enabled: true
    polymarket:
      enabled: true
      base_url: "https://api.polymarket.com"

Environment Variables

Add these to your .env file:

# Polymarket API credentials
POLYMARKET_API_KEY=your_polymarket_key
POLYMARKET_SECRET=your_polymarket_secret

# Arbitrage settings
ARBITRAGE_ENABLED=true
ARBITRAGE_MIN_SPREAD=0.05
ARBITRAGE_AUTO_EXECUTE_THRESHOLD=0.20

Usage

Command Line Interface

The system integrates with the existing CLI:

# Scan for arbitrage opportunities
python main.py arbitrage scan

# Check arbitrage system status
python main.py arbitrage status

# Execute stored opportunities
python main.py arbitrage execute

# Execute with auto-execute for high spreads
python main.py arbitrage execute --auto-execute 0.15

# Monitor and auto-execute continuously
python main.py arbitrage monitor

Scheduler Integration

The arbitrage system automatically integrates with the existing scheduler:

# Start scheduler (includes arbitrage scanning)
python main.py scheduler

The scheduler will: - Run RSS signal generation every 15 minutes (existing) - Run arbitrage scanning every 5 minutes (new) - Auto-execute high-spread opportunities (>20%) - Send Telegram notifications for high-value opportunities

System Status

Check overall system status including arbitrage:

python main.py status

This will show: - Database statistics (including arbitrage opportunities/trades) - Live trading status - Risk management metrics - Arbitrage system configuration

Risk Management

Position Sizing

The system uses Kelly Criterion for position sizing:

Spread Thresholds

Risk Metrics

For each opportunity, the system calculates: - Risk Score: Based on spread and volume - Liquidity Risk: Low/Medium/High based on volume - Execution Risk: Based on spread size - Expected Value: Potential profit from arbitrage

Telegram Integration

The system sends Telegram notifications for:

  1. High-value opportunities (>$10 expected value)
  2. Auto-executed trades (spreads >20%)
  3. System status updates

Example notification:

🦄 Crypto Arbitrage Opportunities Found

1. BTC YES
Spread: 15.2%
Expected Value: $12.50
Expires: 3 days

2. ETH NO
Spread: 12.8%
Expected Value: $8.75
Expires: 2 days

Use /arbitrage execute to execute these opportunities

Testing

Run the test script to verify system components:

python test_arbitrage.py

This will test: - Database initialization - Scanner initialization - Spread analysis with dummy data - Kelly position sizing - Executor initialization

Monitoring

Database Queries

Monitor arbitrage activity:

-- Recent opportunities
SELECT crypto_symbol, spread_percentage, expected_profit, created_at 
FROM arbitrage_opportunities 
ORDER BY created_at DESC 
LIMIT 10;

-- Recent trades
SELECT total_investment, expected_return, status, executed_at 
FROM arbitrage_trades 
ORDER BY executed_at DESC 
LIMIT 10;

Logs

The system logs all activity with the unicorn.arbitrage logger:

# Filter arbitrage logs
grep "arbitrage" logs/app.log

Troubleshooting

Common Issues

  1. No opportunities found - Check if both platforms are enabled in config - Verify API credentials are set - Check minimum spread threshold

  2. API errors - Verify Polymarket API credentials - Check rate limiting settings - Ensure network connectivity

  3. Database errors - Run database initialization: python main.py status - Check file permissions on data/unicorn.db

Debug Mode

Enable debug logging by setting:

LOG_LEVEL=DEBUG

Security Considerations

  1. API Keys: Store securely in environment variables
  2. Dry Run: Always test with dry-run mode first
  3. Position Limits: Conservative Kelly fraction (25%)
  4. Volume Limits: Minimum volume requirements prevent illiquid trades

Future Enhancements

  1. Additional Platforms: Support for more prediction markets
  2. Advanced Matching: ML-based market matching
  3. Portfolio Optimization: Multi-opportunity portfolio management
  4. Real-time Monitoring: Web dashboard for live monitoring
  5. Backtesting: Historical arbitrage opportunity analysis

Support

For issues or questions: 1. Check the logs for error messages 2. Run the test script to verify components 3. Review configuration settings 4. Check API documentation for platform-specific issues