Skip to main content

Professional market making toolkit for Bitfinex cryptocurrency exchange

Project description

Bitfinex Maker-Kit

Modular Market Making Platform for Bitfinex

A professional, production-ready command-line interface for automated trading and market making on the Bitfinex cryptocurrency exchange. Built with modern software architecture principles including dependency injection, domain-driven design, and comprehensive testing frameworks.

GitHub Stars GitHub Forks GitHub Issues Python 3.12+ License: MIT

๐ŸŽฏ Key Features

๐Ÿ›ก๏ธ Safety-First Architecture

  • POST_ONLY Enforcement: Architecturally impossible to place market orders
  • Dry-Run Mode: Test strategies without real trading
  • Multi-Layer Validation: Domain objects, service layer, and API boundary validation
  • Risk Management: Built-in safeguards and confirmation prompts

โšก Modern Architecture

  • Dependency Injection: Clean separation of concerns with container pattern
  • Domain-Driven Design: Type-safe domain objects (OrderId, Price, Amount, Symbol)
  • Service-Oriented: Modular services (trading, cache, market data, performance monitoring)
  • Event-Driven: WebSocket integration with async event handling

๐Ÿงช Comprehensive Testing

  • Property-Based Testing: 1000+ generated test cases using Hypothesis
  • Realistic Load Testing: Integration tests against Bitfinex Paper Trading API
  • Performance Benchmarking: Automated regression detection with real network conditions
  • Security Scanning: Continuous vulnerability assessment

๐Ÿš€ Production Ready

  • Modular Commands: Extensible command system with core abstractions
  • Performance Monitoring: Real-time metrics and profiling tools
  • Configuration Management: Environment-aware configuration system
  • Quality Tooling: Streamlined workflow with Ruff, MyPy, Bandit, and pytest

๐Ÿ—๏ธ Architecture Overview

Modern Software Design

  • Safety First: Architecturally enforced POST_ONLY orders with multiple validation layers
  • Modular Design: Extensible architecture supporting multiple strategies and update methods
  • Domain-Driven: Rich domain objects with business logic encapsulation
  • Service-Oriented: Clean dependency injection with focused service responsibilities

Core Architecture Components

๐ŸŽฏ Command Layer (commands/)

  • Individual Commands: test, wallet, list, cancel, put, market-make, fill-spread, update
  • Core Abstractions: core/ with base commands, executors, and result handling
  • Extensible Design: Plugin-style command architecture

๐Ÿ›๏ธ Service Layer (services/)

  • Container: Dependency injection system managing service lifecycle
  • Trading Services: Sync/async trading facades with monitoring
  • Cache Service: Intelligent caching with namespace isolation
  • Performance Monitor: Real-time metrics collection and analysis
  • Market Data Service: Real-time price feeds and historical data

๐ŸŽจ Domain Layer (domain/)

  • Value Objects: OrderId, Price, Amount, Symbol with validation
  • Business Logic: Type-safe operations and domain rules
  • Immutable Design: Functional programming principles

โš™๏ธ Core Layer (core/)

  • API Client: Clean Bitfinex API wrapper with POST_ONLY enforcement
  • Trading Facade: Unified interface coordinating focused components
  • Order Management: Sophisticated order lifecycle management
  • Validation: Multi-layer validation system

๐Ÿ› ๏ธ Installation

Production Installation

# Install with pipx (recommended)
pipx install bitfinex-maker-kit

# Configure API credentials
echo 'BITFINEX_API_KEY=your_api_key_here' > .env
echo 'BITFINEX_API_SECRET=your_api_secret_here' >> .env

Development Installation

Recommended: One-Command Setup (solves externally-managed-environment errors)

# Clone repository
git clone https://github.com/0xferit/bitfinex-maker-kit.git
cd bitfinex-maker-kit

# One-command setup (creates venv + installs everything)
make setup

# Activate virtual environment (if not already active)
source venv/bin/activate  # On Windows: venv\Scripts\activate

# Verify installation
make quality          # Run all quality checks
pytest               # Run tests

Alternative: Using pipx (for tool installation)

# Install as isolated application
pipx install git+https://github.com/0xferit/bitfinex-maker-kit.git

# For development
git clone https://github.com/0xferit/bitfinex-maker-kit.git
cd bitfinex-maker-kit
pipx install -e .

Manual Installation (if virtual environment setup fails)

# Option 1: Force install (not recommended)
pip install -e ".[dev]" --break-system-packages

# Option 2: User install
pip install -e ".[dev]" --user

# Option 3: Traditional virtual environment
python3 -m venv .venv
source .venv/bin/activate
pip install -e ".[dev]"
pre-commit install

๐Ÿ’ก Troubleshooting "externally-managed-environment" Error:

  • Modern Python/macOS: Use virtual environment (recommended above)
  • System Python: Use pipx for isolated installation
  • Docker: Use the provided Dockerfile for containerized development

๐Ÿš€ Quick Start

Basic Usage

# Test API connection
maker-kit test

# View wallet balances
maker-kit wallet

# List active orders
maker-kit list

# Get help
maker-kit --help

Market Making

# Create symmetric market making orders
maker-kit market-make --symbol tBTCUSD --levels 5 --spread 1.0 --size 0.1

# Start automated market making
maker-kit market-make --symbol tBTCUSD --levels 5

# Fill spread gaps
maker-kit fill-spread --symbol tETHUSD --levels 10

Advanced Features

# Dry-run mode (recommended for testing)
maker-kit market-make --symbol tBTCUSD --levels 3 --dry-run

# Custom order placement
maker-kit put --symbol tBTCUSD --amount 0.01 --price 50000.0 --side buy

# Batch order cancellation
maker-kit cancel --symbol tBTCUSD --side buy

# Cancel all orders for a symbol
maker-kit cancel --all --symbol tBTCUSD

๐Ÿงฉ Strategies Layer (strategies/, update_strategies/)

  • Order Generation: Flexible order generation strategies
  • Update Strategies: Multiple approaches (WebSocket, cancel-recreate, batch)
  • Strategy Factory: Dynamic strategy selection based on market conditions

๐ŸŒ WebSocket Layer (websocket/)

  • Connection Manager: Robust WebSocket connection handling
  • Event Handler: Real-time order updates and market data
  • Async Event Loop: Non-blocking event processing

๐Ÿ–ฅ๏ธ UI Layer (ui/)

  • Market Maker Console: Interactive trading interface
  • Performance Dashboard: Real-time metrics visualization
  • Profiler Integration: Memory and performance monitoring

โš™๏ธ Configuration Layer (config/)

  • Environment Management: Development, staging, production configs
  • Trading Configuration: Dynamic configuration with validation
  • Feature Flags: Environment-specific feature control

๐Ÿ“‹ Available Commands

Command Description Architecture Features
test Test API connection Service container validation, credential testing
wallet Show wallet balances Real-time balance with caching and formatting
list List active orders Advanced filtering, display helpers, pagination
cancel Cancel orders Bulk operations, criteria matching, dry-run support, --all flag
put Place single order Domain validation, order builder pattern
market-make Create staircase orders Strategy-based generation, symmetric placement
fill-spread Fill bid-ask gaps Market data analysis, intelligent spacing
update Update existing orders Multiple update strategies, WebSocket optimization

๐Ÿงช Testing & Quality Assurance

Comprehensive Test Architecture

Test Categories

  • Unit Tests (tests/unit/): Isolated component testing with mocks
  • Integration Tests (tests/integration/): Service interaction validation
  • Property Tests (tests/property/): Hypothesis-based fuzzing and edge cases
  • Load Tests (tests/load/): Stress testing and traffic pattern simulation
  • Performance Tests (tests/performance/): Benchmark suite with regression detection
  • Benchmarks (tests/benchmarks/): Comprehensive performance analysis

Test Infrastructure

  • Fixtures (tests/fixtures/): Reusable test data (API responses, market data, trading scenarios)
  • Mocks (tests/mocks/): Service mocks (API, client, trading service, WebSocket)
  • Utilities (tests/utilities/): Test helpers and profiling tools

Specialized Testing

  • POST_ONLY Enforcement: Architectural safety validation
  • Python Version Compliance: Version requirement testing
  • Wrapper Architecture: API boundary validation

Running Tests

# Run all tests with coverage
pytest --cov=bitfinex_maker_kit --cov-report=html

# Run specific test categories
pytest tests/unit/           # Unit tests
pytest tests/integration/    # Integration tests  
pytest tests/property/       # Property-based tests
pytest tests/load/           # Load and stress tests
pytest tests/performance/    # Performance benchmarks

# Run with markers
pytest -m unit          # Unit tests only
pytest -m integration   # Integration tests
pytest -m property      # Property-based tests
pytest -m load          # Load tests
pytest -m benchmark     # Performance benchmarks

# Run specific architectural tests
pytest tests/test_post_only_enforcement.py     # Safety validation
pytest tests/test_wrapper_architecture.py      # Architecture validation
pytest tests/test_python_version_requirement.py # Version compliance

Code Quality - Simple Workflow

Three commands for everything:

# Quick setup
make install          # Install all dev dependencies

# Main workflow  
make quality          # Run all quality checks (recommended)
make test            # Run tests with coverage

# Individual checks (if needed)
make format          # Auto-format code
make lint            # Run linter with auto-fix
make type-check      # Run type checking
make security        # Run security scan

Alternative: Direct commands

# All-in-one linter and formatter (replaces black, isort, flake8)
ruff check . --fix    # Lint with auto-fix
ruff format .         # Format code

# Type checking and security
mypy bitfinex_maker_kit/       # Type checking
bandit -r bitfinex_maker_kit/  # Security scan

Quick validation (30 seconds):

./scripts/check.sh    # Fast pre-commit check

๐Ÿ“Š Performance Monitoring & Observability

Built-in Performance Infrastructure

Performance Monitor Service (services/performance_monitor.py)

  • Real-Time Metrics: P50, P95, P99 percentiles for API operations
  • Cache Analytics: Hit ratios, miss patterns, namespace efficiency
  • Memory Profiling: Leak detection with heap snapshots
  • Error Tracking: Success/failure rates with categorization

Profiler Utilities (utilities/profiler.py)

  • Execution Profiling: Function-level performance analysis
  • Memory Monitoring: Detailed memory usage tracking
  • Bottleneck Detection: Automated performance regression alerts
  • Resource Utilization: CPU, memory, and I/O monitoring

Performance Dashboard (utilities/performance_dashboard.py)

  • Real-Time Visualization: Live metrics display
  • Historical Analysis: Performance trend tracking
  • Alert System: Automated threshold-based notifications
  • Export Capabilities: JSON, CSV data export

Market Data Caching (utilities/market_data_cache.py)

  • Intelligent Caching: 90%+ API call reduction
  • Cache Warming: Proactive data prefetching
  • Namespace Isolation: Multi-symbol cache management
  • TTL Management: Automatic cache invalidation

Using Performance Tools

# Enable performance monitoring in commands
maker-kit market-make --enable-monitoring

# View performance metrics (via dashboard integration)
# Dashboard accessible through market-make UI console

# Load testing and benchmarks
pytest tests/performance/ --benchmark-json=results.json
pytest tests/load/ -v  # Stress testing

๐Ÿ”’ Security Features

Built-in Security

  • POST_ONLY Orders: Market orders architecturally impossible
  • API Key Protection: Secure credential management
  • Input Validation: Comprehensive parameter validation
  • Rate Limiting: API abuse prevention
  • Audit Logging: Complete operation tracking

Security Scanning

  • Dependency Scanning: Automated vulnerability detection
  • Code Analysis: Static security analysis with Bandit
  • Secret Detection: Credential leak prevention
  • License Compliance: MIT license for maximum flexibility

๐Ÿณ Docker Deployment

Docker Usage

# Build image
docker build -t maker-kit .

# Run container
docker run -d \
  --name maker-kit \
  -e BITFINEX_API_KEY=your_key \
  -e BITFINEX_API_SECRET=your_secret \
  maker-kit

# View logs
docker logs maker-kit

Docker Compose

version: '3.8'
services:
  maker-kit:
    build: .
    environment:
      - BITFINEX_API_KEY=${BITFINEX_API_KEY}
      - BITFINEX_API_SECRET=${BITFINEX_API_SECRET}
    volumes:
      - ./logs:/app/logs
    restart: unless-stopped

๐Ÿ“ˆ Performance Benchmarks

Typical Performance Metrics

  • Order Placement: 100+ orders/second
  • API Response Time: <50ms P95
  • Cache Hit Ratio: >90%
  • Memory Usage: <100MB steady state
  • Error Rate: <0.1% under normal conditions

Load Testing Results

  • Constant Load: 1000+ operations sustained
  • Burst Load: 5000+ operations peak
  • Stress Test: 99%+ uptime under extreme load
  • Memory Efficiency: No memory leaks detected

๐Ÿค Contributing

Development Setup

# Install development dependencies
pip install -e ".[dev,test,security]"

# Install pre-commit hooks
pre-commit install

# Run full test suite
tox

Code Standards

  • Python 3.12+ required
  • Type hints mandatory
  • 100% test coverage for new features
  • Security review for all changes
  • Performance benchmarks for optimizations

Pull Request Process

  1. Fork the repository
  2. Create feature branch: git checkout -b feature/amazing-feature
  3. Make changes with tests and documentation
  4. Run quality checks: tox
  5. Submit pull request with detailed description

๐Ÿ“– Codebase Structure

Directory Organization

bitfinex_maker_kit/
โ”œโ”€โ”€ __init__.py              # Package entry point and exports
โ”œโ”€โ”€ cli.py                   # Main CLI interface using focused components
โ”œโ”€โ”€ bitfinex_client.py       # Legacy wrapper (delegating to core/)
โ”œโ”€โ”€ cli/                     # CLI-specific components
โ”‚   โ”œโ”€โ”€ argument_parser.py   # Command-line argument parsing
โ”‚   โ””โ”€โ”€ command_router.py    # Command routing logic
โ”œโ”€โ”€ commands/                # Individual command implementations
โ”‚   โ”œโ”€โ”€ core/                # Command abstractions and patterns
โ”‚   โ”‚   โ”œโ”€โ”€ base_command.py         # Base command interface
โ”‚   โ”‚   โ”œโ”€โ”€ command_executor.py     # Command execution framework
โ”‚   โ”‚   โ”œโ”€โ”€ command_result.py       # Result handling
โ”‚   โ”‚   โ””โ”€โ”€ [specialized_commands]  # Command implementations
โ”‚   โ””โ”€โ”€ [individual_commands].py    # Main CLI commands
โ”œโ”€โ”€ core/                    # Core business logic
โ”‚   โ”œโ”€โ”€ api_client.py        # Clean Bitfinex API wrapper
โ”‚   โ”œโ”€โ”€ trading_facade.py    # Unified trading interface
โ”‚   โ”œโ”€โ”€ order_manager.py     # Order lifecycle management
โ”‚   โ””โ”€โ”€ order_validator.py   # Multi-layer validation
โ”œโ”€โ”€ domain/                  # Domain objects and business rules
โ”‚   โ”œโ”€โ”€ order_id.py          # Order identification value object
โ”‚   โ”œโ”€โ”€ price.py             # Price value object with validation
โ”‚   โ”œโ”€โ”€ amount.py            # Amount value object with validation
โ”‚   โ””โ”€โ”€ symbol.py            # Trading pair symbol validation
โ”œโ”€โ”€ services/                # Service layer with dependency injection
โ”‚   โ”œโ”€โ”€ container.py         # Dependency injection container
โ”‚   โ”œโ”€โ”€ trading_service.py   # Core trading operations
โ”‚   โ”œโ”€โ”€ cache_service.py     # Intelligent caching system
โ”‚   โ””โ”€โ”€ performance_monitor.py # Real-time metrics collection
โ”œโ”€โ”€ strategies/              # Trading strategy implementations
โ”‚   โ””โ”€โ”€ order_generator.py   # Flexible order generation
โ”œโ”€โ”€ update_strategies/       # Order update approaches
โ”‚   โ”œโ”€โ”€ base.py              # Update strategy interface
โ”‚   โ”œโ”€โ”€ websocket_strategy.py    # Real-time WebSocket updates
โ”‚   โ””โ”€โ”€ cancel_recreate_strategy.py # Cancel-recreate fallback
โ”œโ”€โ”€ websocket/               # WebSocket integration
โ”‚   โ”œโ”€โ”€ connection_manager.py    # Connection lifecycle
โ”‚   โ””โ”€โ”€ event_handler.py     # Real-time event processing
โ”œโ”€โ”€ ui/                      # User interface components
โ”‚   โ””โ”€โ”€ market_maker_console.py  # Interactive trading console
โ”œโ”€โ”€ config/                  # Configuration management
โ”‚   โ”œโ”€โ”€ environment.py       # Environment-aware configuration
โ”‚   โ””โ”€โ”€ trading_config.py    # Trading-specific settings
โ””โ”€โ”€ utilities/               # Shared utilities and helpers
    โ”œโ”€โ”€ [various_utilities].py   # Helper functions and utilities
    โ”œโ”€โ”€ performance_dashboard.py # Performance visualization
    โ””โ”€โ”€ profiler.py          # Performance profiling tools

Key Design Patterns

  • Dependency Injection: Clean service boundaries with container pattern
  • Command Pattern: Extensible command system with undo capabilities
  • Strategy Pattern: Pluggable algorithms for order generation and updates
  • Facade Pattern: Simplified interfaces over complex subsystems
  • Domain-Driven Design: Rich domain objects with business logic

โš ๏ธ Risk Disclaimer

IMPORTANT: Trading cryptocurrency involves substantial risk of loss and is not suitable for every investor. The volatile nature of cryptocurrency markets may result in significant financial losses. You should carefully consider whether trading is suitable for you in light of your circumstances, knowledge, and financial resources.

  • Test First: Always use --dry-run mode before live trading
  • Start Small: Begin with minimal position sizes
  • Monitor Closely: Actively supervise automated strategies
  • Risk Management: Never trade more than you can afford to lose

๐Ÿ“„ License

This project is licensed under the MIT License - see the LICENSE file for details.

Third-Party Dependencies

All dependencies use compatible permissive licenses (MIT, BSD, Apache-2.0). See THIRD_PARTY_LICENSES.md for complete license attributions.

๐Ÿ™ Acknowledgments

  • Bitfinex API Team for comprehensive API documentation
  • Open Source Community for testing frameworks and tools
  • Security Researchers for vulnerability disclosure
  • Trading Community for feature requests and feedback

Ready for Enterprise Trading! ๐Ÿš€

Start with maker-kit test to verify your setup, then explore the comprehensive feature set designed for professional market making.

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

bitfinex_maker_kit-4.2.50.tar.gz (154.5 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

bitfinex_maker_kit-4.2.50-py3-none-any.whl (177.6 kB view details)

Uploaded Python 3

File details

Details for the file bitfinex_maker_kit-4.2.50.tar.gz.

File metadata

  • Download URL: bitfinex_maker_kit-4.2.50.tar.gz
  • Upload date:
  • Size: 154.5 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? Yes
  • Uploaded via: twine/6.1.0 CPython/3.12.9

File hashes

Hashes for bitfinex_maker_kit-4.2.50.tar.gz
Algorithm Hash digest
SHA256 fffe011dec46237236833fe2b2ec3718d00d0a70609ecabd6b0525e10ba55688
MD5 4bdb450e38a387712d680354f0fbbaad
BLAKE2b-256 4a1f4e0ed6e6ef93b5c81190b2858bc2534015ecd0af1ab1f4b5223d1de5613b

See more details on using hashes here.

Provenance

The following attestation bundles were made for bitfinex_maker_kit-4.2.50.tar.gz:

Publisher: publish.yml on 0xferit/bitfinex-maker-kit

Attestations: Values shown here reflect the state when the release was signed and may no longer be current.

File details

Details for the file bitfinex_maker_kit-4.2.50-py3-none-any.whl.

File metadata

File hashes

Hashes for bitfinex_maker_kit-4.2.50-py3-none-any.whl
Algorithm Hash digest
SHA256 0f0095316948c23468b11fe784257724956c85ff5052e631b8df2306073f8f74
MD5 2d754311b44a43a42f23ecb6f7f4fca9
BLAKE2b-256 b0d61e728b8783498a14e02db6c068f9f08d4edb46c5670702f20116e010a823

See more details on using hashes here.

Provenance

The following attestation bundles were made for bitfinex_maker_kit-4.2.50-py3-none-any.whl:

Publisher: publish.yml on 0xferit/bitfinex-maker-kit

Attestations: Values shown here reflect the state when the release was signed and may no longer be current.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page