Skip to content

Latest commit

 

History

History
219 lines (161 loc) · 7.07 KB

File metadata and controls

219 lines (161 loc) · 7.07 KB

Backpack Exchange Arbitrage Trading Bot

An automated spot-futures arbitrage trading system for Backpack Exchange, designed to capture price differences between spot and perpetual futures markets while optimizing for transaction costs.

📊 Strategy Overview

Core Arbitrage Mechanism

The bot identifies and executes arbitrage opportunities between spot and perpetual futures markets:

  1. Price Monitoring: Real-time tracking of spot and futures prices via WebSocket
  2. Spread Detection: Calculate price differences and identify profitable opportunities
  3. Risk Assessment: Evaluate liquidity, confidence score, and risk parameters
  4. Execution: Place simultaneous trades to capture the spread
  5. Position Management: Monitor and close positions when profitable

Dynamic Order Type Selection

Small Spreads (< 0.40%): TAKER Strategy

  • Uses market orders for immediate execution
  • Prioritizes speed to capture fleeting opportunities
  • Total fees: ~0.28% round-trip (spot taker 0.09% + futures taker 0.05% × 2)
  • Execution threshold: 0.20% minimum expected return

Large Spreads (≥ 0.40%): MAKER Strategy

  • Uses limit orders with favorable pricing to earn maker rebates
  • Optimizes for lower fees when spread allows time for execution
  • Total fees: ~0.18% round-trip (spot maker 0.07% + futures maker 0.02% × 2)
  • Timeout: 15 seconds with fallback to market orders
  • Execution threshold: Variable based on spread size

🔧 Configuration

Environment Variables

Copy .env.example to .env and configure:

# API Credentials
BACKPACK_API_KEY=your_base64_api_key_here
BACKPACK_PRIVATE_KEY=your_base64_private_key_here

# Risk Management (optimized for $1000 account)
MAX_POSITION_SIZE=200          # Maximum USD per position (20%)
MAX_TOTAL_EXPOSURE=400         # Maximum total USD exposure (40%)
MAX_DAILY_LOSS=30              # Maximum daily loss in USD (3%)
MIN_ACCOUNT_BALANCE=700        # Minimum account balance to maintain (70%)

# Strategy Parameters
MIN_SPREAD_THRESHOLD=0.15      # Minimum spread to detect opportunities
MIN_EXECUTION_THRESHOLD=0.20   # Minimum expected return to execute
LARGE_SPREAD_THRESHOLD=0.40    # Threshold for using maker orders
POSITION_SIZE_USD=150          # Default position size (15% of balance)

# Order Execution
USE_MAKER_FOR_LARGE_SPREADS=true    # Dynamic order type selection
ORDER_TIMEOUT_SECONDS=15            # Timeout for limit orders
FALLBACK_TO_TAKER=true              # Fallback to market orders

# Confidence Scoring
CONFIDENCE_THRESHOLD=0.6       # Minimum confidence to execute

Trading Pairs

Currently monitors these spot-futures pairs:

  • SOL_USDC / SOL_USDC_PERP
  • BTC_USDC / BTC_USDC_PERP
  • ETH_USDC / ETH_USDC_PERP
  • SUI_USDC / SUI_USDC_PERP
  • JUP_USDC / JUP_USDC_PERP

📈 Risk Management

Position Sizing

Liquidity-Based Sizing: Position sizes calculated relative to order book depth:

  • Excellent liquidity (10x buffer): Available size > required size × 10
  • Good liquidity (3x buffer): Available size > required size × 3
  • Adequate liquidity (1x buffer): Available size > required size × 1

Confidence Scoring

Multi-factor confidence assessment:

  • Base confidence: 0.5
  • Liquidity bonus: +0.1 to +0.3 based on order book depth
  • Spread quality bonus:
    • 0.2%-1.0% spreads: +0.2
    • 0.15%-0.2% spreads: +0.1

Account Health Monitoring

  • Real-time balance and collateral tracking
  • Automatic position limits based on account equity
  • Daily loss limits to prevent catastrophic losses
  • Minimum balance maintenance requirements

🚀 Installation & Usage

Prerequisites

  • Python 3.12+
  • UV package manager
  • Backpack Exchange API credentials

Setup

# Clone repository
git clone <repository-url>
cd bparb

# Install dependencies
uv sync

# Configure environment
cp .env.example .env
# Edit .env with your API credentials and preferences

# Run the bot
uv run main.py

Monitoring

The bot provides comprehensive logging:

# View live logs
tail -f arbitrage.log

# Monitor specific components
grep "Found opportunity" arbitrage.log
grep "Placing.*orders" arbitrage.log
grep "Strategy stats" arbitrage.log

📊 Performance Metrics

Expected Returns

Conservative Estimates (after fees):

  • Small spreads (0.20-0.40%): Net profit 0.02-0.12%
  • Medium spreads (0.40-0.80%): Net profit 0.22-0.62%
  • Large spreads (0.80%+): Net profit 0.62%+

Risk-Adjusted Targets:

  • Win rate: 70-85% (high confidence threshold)
  • Average holding time: 30 seconds - 8 hours (funding dependent)
  • Daily opportunities: 5-20 depending on market volatility

Fee Structure Analysis

Scenario Entry Fee Exit Fee Total Fee Min Profitable Spread
Small Spread (Taker) 0.14% 0.14% 0.28% 0.30%
Large Spread (Maker) 0.09% 0.09% 0.18% 0.20%

⚠️ Risk Warnings

Market Risks

  • Price Volatility: Crypto markets can move rapidly, potentially eliminating spreads
  • Liquidity Risk: Low liquidity may result in slippage or partial fills
  • Execution Risk: Network latency or exchange issues may affect execution timing

Operational Risks

  • API Limits: Rate limiting may restrict trading frequency
  • Funding Costs: Perpetual futures have funding payments every 8 hours
  • Account Management: Insufficient margin may prevent position opening

Recommended Practices

  • Start with small position sizes to test the system
  • Monitor positions actively, especially during high volatility
  • Maintain adequate account balance above minimum requirements
  • Regular strategy performance review and parameter adjustment

🔧 Architecture

Core Components

src/
├── api/           # Backpack Exchange API client
│   ├── client.py  # REST API and authentication
│   └── websocket.py # Real-time data streaming
├── data/          # Market data collection and processing
│   └── market_data.py # Price feeds and order book management
├── strategy/      # Trading strategy implementation
│   └── arbitrage.py # Spot-futures arbitrage logic
└── risk/          # Risk management and position sizing
    └── manager.py # Account health and limits

Data Flow

  1. WebSocket Connection → Real-time market data
  2. Market Data Processor → Price normalization and spread calculation
  3. Strategy Engine → Opportunity identification and filtering
  4. Risk Manager → Position sizing and account health checks
  5. Order Execution → Dynamic order type selection and placement
  6. Position Monitor → P&L tracking and exit conditions

📝 License

This project is for educational and research purposes. Use at your own risk in live trading environments.

🤝 Contributing

  1. Fork the repository
  2. Create a feature branch
  3. Implement changes with appropriate tests
  4. Submit a pull request with detailed description

📞 Support

For issues and questions:

  • Create an issue in the repository
  • Review logs for troubleshooting information
  • Check Backpack Exchange API documentation for updates