quant-async


Namequant-async JSON
Version 0.2.1 PyPI version JSON
download
home_pageNone
SummaryInteractive Brokers Async Trading Framework for Python 3.12+
upload_time2025-08-04 11:24:08
maintainerNone
docs_urlNone
authorNone
requires_python>=3.12
licenseNone
keywords trading interactive-brokers async finance algorithmic-trading
VCS
bugtrack_url
requirements No requirements were recorded.
Travis-CI No Travis.
coveralls test coverage
            # Quant Async

![Python version](https://img.shields.io/badge/python-3.12+-blue.svg?style=flat)
![PyPi version](https://img.shields.io/pypi/v/quant_async.svg?maxAge=60)
![PyPi status](https://img.shields.io/pypi/status/quant_async.svg?maxAge=60)
![Coverage](https://img.shields.io/badge/coverage-37%25-red)

**An Interactive Brokers Async Trading Framework for Python 3.12+**

Quant Async is a high-performance, production-ready framework for algorithmic trading with Interactive Brokers. It provides real-time market data streaming, persistent data storage, and a clean async API for building sophisticated trading strategies.

## ๐Ÿ—๏ธ Architecture Overview

```
โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”    ZeroMQ     โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”
โ”‚   Algorithm 1   โ”‚โ—„โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”ค                 โ”‚
โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜               โ”‚                 โ”‚
โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”    Pub/Sub    โ”‚     Blotter     โ”‚    IB API    โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”
โ”‚   Algorithm 2   โ”‚โ—„โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”ค  (Data Stream)  โ”‚โ—„โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”ค Interactive     โ”‚
โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜               โ”‚                 โ”‚              โ”‚ Brokers         โ”‚
โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”               โ”‚                 โ”‚              โ”‚ TWS/Gateway     โ”‚
โ”‚   Algorithm N   โ”‚โ—„โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”ค                 โ”‚              โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜
โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜               โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜
                                           โ”‚
                                    PostgreSQL
                                  โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”
                                  โ”‚  Market Data    โ”‚
                                  โ”‚   Database      โ”‚
                                  โ”‚                 โ”‚
                                  โ”‚ โ€ข Ticks         โ”‚
                                  โ”‚ โ€ข Bars          โ”‚  
                                  โ”‚ โ€ข Quotes        โ”‚
                                  โ”‚ โ€ข Greeks        โ”‚
                                  โ”‚ โ€ข Trades        โ”‚
                                  โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜
```

### Core Components

- **Blotter**: Continuous market data collector and broadcaster
- **Algo**: Base class for trading algorithms with real-time data consumption  
- **Broker**: Interactive Brokers connection and order management
- **Database**: PostgreSQL storage with asyncpg for historical data and backtesting
- **Streaming**: ZeroMQ pub/sub for real-time data distribution
- **Dashboard**: FastAPI web interface for monitoring and control

## ๐Ÿš€ Features

- โœ… **Continuous Data Collection**: 24/7 market data capture independent of strategy execution
- โœ… **Real-time Streaming**: ZeroMQ pub/sub architecture supports multiple concurrent algorithms
- โœ… **Database Persistence**: All tick, bar, quote, and Greek data stored in PostgreSQL
- โœ… **Hot Symbol Management**: CSV-based symbol management with live reload
- โœ… **Async Architecture**: Built on asyncio for high-performance concurrent operations
- โœ… **Production Ready**: Comprehensive error handling, logging, and monitoring
- โœ… **Web Dashboard**: FastAPI interface for system monitoring and control
- โœ… **Historical Analysis**: Efficient data retrieval for backtesting and research

## ๐Ÿ“‹ Requirements

- **Python**: 3.12+
- **Interactive Brokers**: TWS or IB Gateway
- **PostgreSQL**: 12+ (for data persistence)
- **Operating System**: macOS, Linux

## ๐Ÿ› ๏ธ Installation

### 1. Clone Repository

```bash
git clone https://github.com/kelvingao/quant_async.git
cd quant_async
```

### 2. Install Dependencies

Using `uv` (recommended):
```bash
uv sync
uv sync --group dev  # Include development dependencies
```

Using `pip`:
```bash
pip install -e .
pip install -e .[dev]  # Include development dependencies
```

### 3. Configure Environment

```bash
cp .env.example .env
# Edit .env with your specific configuration
```

### 4. Setup PostgreSQL Database

```bash
# Connect to PostgreSQL as superuser
psql -U postgres

# Create database and user
CREATE DATABASE quant_async;
CREATE USER quant_async WITH PASSWORD 'quant_async';
GRANT ALL PRIVILEGES ON DATABASE quant_async TO quant_async;

# Connect to the new database  
\c quant_async

# Grant schema permissions
GRANT CREATE ON SCHEMA public TO quant_async;
```

### 5. Run Database Migrations

```bash
uv run alembic upgrade head
```

### 6. Setup Interactive Brokers

#### TWS (Trader Workstation)
1. Download and install TWS from Interactive Brokers
2. Enable API access: `Configure โ†’ API โ†’ Enable ActiveX and Socket Clients`
3. Set API port (7497 for live, 7496 for paper trading)
4. Disable "Read-Only API"

#### IB Gateway (Recommended for Production)
1. Download IB Gateway
2. Configure API settings (port 4001 for live, 4002 for paper)
3. Enable API access and disable read-only mode

## ๐Ÿƒโ€โ™‚๏ธ Quick Start

### 1. Configure Symbols

Edit `examples/symbols.csv` to specify instruments to monitor:

```csv
symbol,sec_type,exchange,currency,expiry,strike,opt_type
NVDA,STK,SMART,USD,,,
AAPL,STK,SMART,USD,,,
ES,FUT,CME,USD,20250919,,
EURUSD,CASH,IDEALPRO,USD,,,
```

### 2. Start the Blotter

```bash
# Start continuous market data collection
uv run python examples/blotter.py

# With custom configuration
uv run python examples/blotter.py --ibport=4002 --dbname=quant_async_paper
```

### 3. Start the Dashboard

```bash
# Launch web interface (http://localhost:5002)
uv run python examples/dashboard.py
```

### 4. Run an Algorithm

```bash
# Run example trading strategy
uv run python examples/strategy.py
```

## ๐Ÿ“Š Usage Examples

### Basic Blotter Usage

```python
import asyncio
from quant_async import Blotter, util

class MyBlotter(Blotter):
    pass

if __name__ == "__main__":
    util.logToConsole("INFO")
    
    blotter = MyBlotter(
        symbols="symbols.csv",
        ibhost="localhost", 
        ibport=4001,
        dbname="quant_async"
    )
    
    asyncio.run(blotter.run())
```

### Algorithm Development

```python
from quant_async import Algo

class MovingAverageStrategy(Algo):
    
    def __init__(self):
        super().__init__(
            instruments=[("AAPL", "STK", "SMART", "USD")],
            ibclient=998
        )
        self.sma_short = 10
        self.sma_long = 20
    
    def on_start(self):
        print("Strategy starting...")
    
    def on_quote(self, instrument):
        # Process real-time quotes
        quote_data = self.quotes[instrument.symbol]
        print(f"Quote for {instrument.symbol}: {quote_data}")
    
    def on_tick(self, instrument):
        # Process tick data
        print(f"Tick for {instrument.symbol}")
    
    def on_bar(self, instrument):
        # Process bar data for strategy logic
        print(f"Bar for {instrument.symbol}")

if __name__ == "__main__":
    strategy = MovingAverageStrategy()
    asyncio.run(strategy.run())
```

### Multiple Algorithm Example

```python
# Run multiple strategies consuming the same data stream
from quant_async import Algo
import asyncio

class MomentumStrategy(Algo):
    def __init__(self):
        super().__init__(
            instruments=[("NVDA", "STK", "SMART", "USD")],
            ibclient=999
        )
    
    def on_quote(self, instrument):
        # Momentum strategy logic
        pass

class MeanReversionStrategy(Algo):
    def __init__(self):
        super().__init__(
            instruments=[("AAPL", "STK", "SMART", "USD")],
            ibclient=1000
        )
    
    def on_quote(self, instrument):
        # Mean reversion strategy logic  
        pass

async def run_multiple_strategies():
    momentum = MomentumStrategy()
    mean_reversion = MeanReversionStrategy()
    
    # Run both strategies concurrently
    await asyncio.gather(
        momentum.run(),
        mean_reversion.run()
    )

if __name__ == "__main__":
    asyncio.run(run_multiple_strategies())
```

## ๐Ÿ”ง Configuration

### Environment Variables

The framework supports configuration via environment variables. Copy `.env.example` to `.env` and customize:

```bash
# Interactive Brokers
IB_HOST=localhost
IB_PORT=4001
IB_CLIENT_ID=996

# Database
DB_HOST=localhost
DB_PORT=5432
DB_NAME=quant_async
DB_USER=quant_async
DB_PASS=quant_async

# ZeroMQ
ZMQ_PORT=12345

# Logging
LOG_LEVEL=INFO
```

### Command Line Arguments

All components support command-line configuration:

```bash
# Blotter options
python examples/blotter.py \
    --ibhost localhost \
    --ibport 4001 \
    --ibclient 996 \
    --dbhost localhost \
    --dbname quant_async \
    --zmqport 12345 \
    --symbols symbols.csv

# Algorithm options  
python examples/strategy.py \
    --ibhost localhost \
    --ibport 4001 \
    --ibclient 998 \
    --blotter auto-detect
```

## ๐Ÿ—„๏ธ Database Schema

The framework uses PostgreSQL with the following tables:

- **symbols**: Instrument definitions and metadata
- **bars**: OHLCV bar data with volume
- **ticks**: Real-time tick data (bid/ask/last)
- **greeks**: Options Greeks (delta, gamma, theta, vega)
- **trades**: Executed trade records

### Database Queries

```python
# Historical data retrieval
from quant_async import Blotter

blotter = Blotter(dbskip=False)
await blotter.postgres_connect()

# Get historical bars
bars = await blotter.history(
    symbols=["AAPL_STK"], 
    start="2024-01-01",
    end="2024-12-31",
    resolution="1D"
)

# Get tick data
ticks = await blotter.history(
    symbols=["EURUSD_CASH"],
    start="2024-08-01", 
    resolution="1T"  # 1 tick resolution
)
```

## ๐Ÿ“Š Monitoring & Dashboard

### Web Dashboard

Access the web interface at `http://localhost:5002`:

- Real-time market data display
- System health monitoring  
- Connection status indicators
- Performance metrics
- Historical data charts

### Health Checks

```bash
# Check system status
curl http://localhost:8080/health

# Get metrics
curl http://localhost:8080/metrics
```

### Logging

The framework uses structured logging:

```python
import logging
from quant_async import util

# Configure logging
util.logToConsole("INFO")

# Custom logger configuration
logging.basicConfig(
    level=logging.INFO,
    format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
    handlers=[
        logging.FileHandler('trading.log'),
        logging.StreamHandler()
    ]
)
```

## ๐Ÿงช Testing

The project includes comprehensive unit tests and integration tests.

### Unit Tests

Run unit tests (no external dependencies required):

```bash
# Run all unit tests (excludes integration tests)
uv run pytest tests/ -m "not integration" -v

# Run specific test modules
uv run pytest tests/test_blotter.py -v
uv run pytest tests/test_streaming.py -v
uv run pytest tests/test_database.py -v

# Run with coverage and update badge
./scripts/update_coverage.sh

# Or run coverage manually
uv run pytest tests/ -m "not integration" --cov=src/quant_async --cov-report=html --cov-report=json

# Update coverage badge in README
python scripts/generate_coverage_badge.py
```

### Integration Tests

Integration tests require a real PostgreSQL database. Set up the test environment:

```bash
# 1. Copy environment template
cp .env.example .env

# 2. Create test database (as postgres user)
sudo -u postgres psql -f setup_integration_tests.sql

# 3. Configure .env file with test database settings:
# TEST_DB_HOST=localhost
# TEST_DB_PORT=5432
# TEST_DB_USER=quant_async
# TEST_DB_PASS=quant_async
# TEST_DB_NAME=quant_async_test

# 4. Run integration tests
uv run pytest tests/ -m integration -v

# 5. Run all tests (unit + integration)
uv run pytest tests/ -v
```

**Integration Test Markers:**
- `@pytest.mark.integration` - Requires real PostgreSQL database
- Tests are automatically skipped if database is not available

## ๐Ÿšจ Troubleshooting

### Common Issues

#### IB Connection Failed
```
Error: Cannot connect to Interactive Brokers
```
**Solutions:**
- Verify TWS/Gateway is running
- Check API settings are enabled
- Confirm correct port (7497/4001 live, 7496/4002 paper)
- Ensure client ID is unique
- Check firewall settings

#### Database Connection Error  
```
Error: Cannot connect to PostgreSQL
```
**Solutions:**
- Verify PostgreSQL is running
- Check database credentials in .env
- Ensure database exists and user has permissions
- Test connection: `psql -U quant_async -d quant_async -h localhost`

#### ZeroMQ Port Conflict
```
Error: Address already in use
```
**Solutions:**
- Change ZMQ_PORT in .env
- Kill existing process: `lsof -ti:12345 | xargs kill -9`
- Use different port for each Blotter instance

#### Symbol File Issues
```
Error: Symbol file not found or invalid
```
**Solutions:**
- Verify symbols.csv exists and is readable
- Check CSV format matches expected columns
- Ensure file permissions (0o666)
- Review example symbols.csv for format

### Debug Mode

Enable verbose logging for troubleshooting:

```python
from quant_async import util
util.logToConsole("DEBUG")
```

### Performance Tuning

For high-frequency trading:

```python
# Optimize database connections
blotter = Blotter(
    dbhost="localhost",
    # Increase connection pool size
    # Configure in get_postgres_connection()
)

# Reduce ZeroMQ latency
# Use dedicated network interface
# Increase system buffer sizes
```

## ๐Ÿค Contributing

1. Fork the repository
2. Create a feature branch: `git checkout -b feature/new-feature`
3. Make changes and add tests
4. Run tests: `uv run pytest tests/`
5. Run linting: `uv run ruff check src/ tests/`
6. Commit changes: `git commit -m 'Add new feature'`
7. Push to branch: `git push origin feature/new-feature`
8. Submit a Pull Request

## ๐Ÿ“„ License

This project is licensed under the MIT License - see the [LICENSE](LICENSE) file for details.

            

Raw data

            {
    "_id": null,
    "home_page": null,
    "name": "quant-async",
    "maintainer": null,
    "docs_url": null,
    "requires_python": ">=3.12",
    "maintainer_email": "Kelvin Gao <89156201@qq.com>",
    "keywords": "trading, interactive-brokers, async, finance, algorithmic-trading",
    "author": null,
    "author_email": "Kelvin Gao <89156201@qq.com>",
    "download_url": "https://files.pythonhosted.org/packages/3a/ac/c4c73c4ce919ff5f4c3a5a0c742e395b7037740cad54b654b0281f02452b/quant_async-0.2.1.tar.gz",
    "platform": null,
    "description": "# Quant Async\n\n![Python version](https://img.shields.io/badge/python-3.12+-blue.svg?style=flat)\n![PyPi version](https://img.shields.io/pypi/v/quant_async.svg?maxAge=60)\n![PyPi status](https://img.shields.io/pypi/status/quant_async.svg?maxAge=60)\n![Coverage](https://img.shields.io/badge/coverage-37%25-red)\n\n**An Interactive Brokers Async Trading Framework for Python 3.12+**\n\nQuant Async is a high-performance, production-ready framework for algorithmic trading with Interactive Brokers. It provides real-time market data streaming, persistent data storage, and a clean async API for building sophisticated trading strategies.\n\n## \ud83c\udfd7\ufe0f Architecture Overview\n\n```\n\u250c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2510    ZeroMQ     \u250c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2510\n\u2502   Algorithm 1   \u2502\u25c4\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2524                 \u2502\n\u2514\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2518               \u2502                 \u2502\n\u250c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2510    Pub/Sub    \u2502     Blotter     \u2502    IB API    \u250c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2510\n\u2502   Algorithm 2   \u2502\u25c4\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2524  (Data Stream)  \u2502\u25c4\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2524 Interactive     \u2502\n\u2514\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2518               \u2502                 \u2502              \u2502 Brokers         \u2502\n\u250c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2510               \u2502                 \u2502              \u2502 TWS/Gateway     \u2502\n\u2502   Algorithm N   \u2502\u25c4\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2524                 \u2502              \u2514\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2518\n\u2514\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2518               \u2514\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2518\n                                           \u2502\n                                    PostgreSQL\n                                  \u250c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2510\n                                  \u2502  Market Data    \u2502\n                                  \u2502   Database      \u2502\n                                  \u2502                 \u2502\n                                  \u2502 \u2022 Ticks         \u2502\n                                  \u2502 \u2022 Bars          \u2502  \n                                  \u2502 \u2022 Quotes        \u2502\n                                  \u2502 \u2022 Greeks        \u2502\n                                  \u2502 \u2022 Trades        \u2502\n                                  \u2514\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2518\n```\n\n### Core Components\n\n- **Blotter**: Continuous market data collector and broadcaster\n- **Algo**: Base class for trading algorithms with real-time data consumption  \n- **Broker**: Interactive Brokers connection and order management\n- **Database**: PostgreSQL storage with asyncpg for historical data and backtesting\n- **Streaming**: ZeroMQ pub/sub for real-time data distribution\n- **Dashboard**: FastAPI web interface for monitoring and control\n\n## \ud83d\ude80 Features\n\n- \u2705 **Continuous Data Collection**: 24/7 market data capture independent of strategy execution\n- \u2705 **Real-time Streaming**: ZeroMQ pub/sub architecture supports multiple concurrent algorithms\n- \u2705 **Database Persistence**: All tick, bar, quote, and Greek data stored in PostgreSQL\n- \u2705 **Hot Symbol Management**: CSV-based symbol management with live reload\n- \u2705 **Async Architecture**: Built on asyncio for high-performance concurrent operations\n- \u2705 **Production Ready**: Comprehensive error handling, logging, and monitoring\n- \u2705 **Web Dashboard**: FastAPI interface for system monitoring and control\n- \u2705 **Historical Analysis**: Efficient data retrieval for backtesting and research\n\n## \ud83d\udccb Requirements\n\n- **Python**: 3.12+\n- **Interactive Brokers**: TWS or IB Gateway\n- **PostgreSQL**: 12+ (for data persistence)\n- **Operating System**: macOS, Linux\n\n## \ud83d\udee0\ufe0f Installation\n\n### 1. Clone Repository\n\n```bash\ngit clone https://github.com/kelvingao/quant_async.git\ncd quant_async\n```\n\n### 2. Install Dependencies\n\nUsing `uv` (recommended):\n```bash\nuv sync\nuv sync --group dev  # Include development dependencies\n```\n\nUsing `pip`:\n```bash\npip install -e .\npip install -e .[dev]  # Include development dependencies\n```\n\n### 3. Configure Environment\n\n```bash\ncp .env.example .env\n# Edit .env with your specific configuration\n```\n\n### 4. Setup PostgreSQL Database\n\n```bash\n# Connect to PostgreSQL as superuser\npsql -U postgres\n\n# Create database and user\nCREATE DATABASE quant_async;\nCREATE USER quant_async WITH PASSWORD 'quant_async';\nGRANT ALL PRIVILEGES ON DATABASE quant_async TO quant_async;\n\n# Connect to the new database  \n\\c quant_async\n\n# Grant schema permissions\nGRANT CREATE ON SCHEMA public TO quant_async;\n```\n\n### 5. Run Database Migrations\n\n```bash\nuv run alembic upgrade head\n```\n\n### 6. Setup Interactive Brokers\n\n#### TWS (Trader Workstation)\n1. Download and install TWS from Interactive Brokers\n2. Enable API access: `Configure \u2192 API \u2192 Enable ActiveX and Socket Clients`\n3. Set API port (7497 for live, 7496 for paper trading)\n4. Disable \"Read-Only API\"\n\n#### IB Gateway (Recommended for Production)\n1. Download IB Gateway\n2. Configure API settings (port 4001 for live, 4002 for paper)\n3. Enable API access and disable read-only mode\n\n## \ud83c\udfc3\u200d\u2642\ufe0f Quick Start\n\n### 1. Configure Symbols\n\nEdit `examples/symbols.csv` to specify instruments to monitor:\n\n```csv\nsymbol,sec_type,exchange,currency,expiry,strike,opt_type\nNVDA,STK,SMART,USD,,,\nAAPL,STK,SMART,USD,,,\nES,FUT,CME,USD,20250919,,\nEURUSD,CASH,IDEALPRO,USD,,,\n```\n\n### 2. Start the Blotter\n\n```bash\n# Start continuous market data collection\nuv run python examples/blotter.py\n\n# With custom configuration\nuv run python examples/blotter.py --ibport=4002 --dbname=quant_async_paper\n```\n\n### 3. Start the Dashboard\n\n```bash\n# Launch web interface (http://localhost:5002)\nuv run python examples/dashboard.py\n```\n\n### 4. Run an Algorithm\n\n```bash\n# Run example trading strategy\nuv run python examples/strategy.py\n```\n\n## \ud83d\udcca Usage Examples\n\n### Basic Blotter Usage\n\n```python\nimport asyncio\nfrom quant_async import Blotter, util\n\nclass MyBlotter(Blotter):\n    pass\n\nif __name__ == \"__main__\":\n    util.logToConsole(\"INFO\")\n    \n    blotter = MyBlotter(\n        symbols=\"symbols.csv\",\n        ibhost=\"localhost\", \n        ibport=4001,\n        dbname=\"quant_async\"\n    )\n    \n    asyncio.run(blotter.run())\n```\n\n### Algorithm Development\n\n```python\nfrom quant_async import Algo\n\nclass MovingAverageStrategy(Algo):\n    \n    def __init__(self):\n        super().__init__(\n            instruments=[(\"AAPL\", \"STK\", \"SMART\", \"USD\")],\n            ibclient=998\n        )\n        self.sma_short = 10\n        self.sma_long = 20\n    \n    def on_start(self):\n        print(\"Strategy starting...\")\n    \n    def on_quote(self, instrument):\n        # Process real-time quotes\n        quote_data = self.quotes[instrument.symbol]\n        print(f\"Quote for {instrument.symbol}: {quote_data}\")\n    \n    def on_tick(self, instrument):\n        # Process tick data\n        print(f\"Tick for {instrument.symbol}\")\n    \n    def on_bar(self, instrument):\n        # Process bar data for strategy logic\n        print(f\"Bar for {instrument.symbol}\")\n\nif __name__ == \"__main__\":\n    strategy = MovingAverageStrategy()\n    asyncio.run(strategy.run())\n```\n\n### Multiple Algorithm Example\n\n```python\n# Run multiple strategies consuming the same data stream\nfrom quant_async import Algo\nimport asyncio\n\nclass MomentumStrategy(Algo):\n    def __init__(self):\n        super().__init__(\n            instruments=[(\"NVDA\", \"STK\", \"SMART\", \"USD\")],\n            ibclient=999\n        )\n    \n    def on_quote(self, instrument):\n        # Momentum strategy logic\n        pass\n\nclass MeanReversionStrategy(Algo):\n    def __init__(self):\n        super().__init__(\n            instruments=[(\"AAPL\", \"STK\", \"SMART\", \"USD\")],\n            ibclient=1000\n        )\n    \n    def on_quote(self, instrument):\n        # Mean reversion strategy logic  \n        pass\n\nasync def run_multiple_strategies():\n    momentum = MomentumStrategy()\n    mean_reversion = MeanReversionStrategy()\n    \n    # Run both strategies concurrently\n    await asyncio.gather(\n        momentum.run(),\n        mean_reversion.run()\n    )\n\nif __name__ == \"__main__\":\n    asyncio.run(run_multiple_strategies())\n```\n\n## \ud83d\udd27 Configuration\n\n### Environment Variables\n\nThe framework supports configuration via environment variables. Copy `.env.example` to `.env` and customize:\n\n```bash\n# Interactive Brokers\nIB_HOST=localhost\nIB_PORT=4001\nIB_CLIENT_ID=996\n\n# Database\nDB_HOST=localhost\nDB_PORT=5432\nDB_NAME=quant_async\nDB_USER=quant_async\nDB_PASS=quant_async\n\n# ZeroMQ\nZMQ_PORT=12345\n\n# Logging\nLOG_LEVEL=INFO\n```\n\n### Command Line Arguments\n\nAll components support command-line configuration:\n\n```bash\n# Blotter options\npython examples/blotter.py \\\n    --ibhost localhost \\\n    --ibport 4001 \\\n    --ibclient 996 \\\n    --dbhost localhost \\\n    --dbname quant_async \\\n    --zmqport 12345 \\\n    --symbols symbols.csv\n\n# Algorithm options  \npython examples/strategy.py \\\n    --ibhost localhost \\\n    --ibport 4001 \\\n    --ibclient 998 \\\n    --blotter auto-detect\n```\n\n## \ud83d\uddc4\ufe0f Database Schema\n\nThe framework uses PostgreSQL with the following tables:\n\n- **symbols**: Instrument definitions and metadata\n- **bars**: OHLCV bar data with volume\n- **ticks**: Real-time tick data (bid/ask/last)\n- **greeks**: Options Greeks (delta, gamma, theta, vega)\n- **trades**: Executed trade records\n\n### Database Queries\n\n```python\n# Historical data retrieval\nfrom quant_async import Blotter\n\nblotter = Blotter(dbskip=False)\nawait blotter.postgres_connect()\n\n# Get historical bars\nbars = await blotter.history(\n    symbols=[\"AAPL_STK\"], \n    start=\"2024-01-01\",\n    end=\"2024-12-31\",\n    resolution=\"1D\"\n)\n\n# Get tick data\nticks = await blotter.history(\n    symbols=[\"EURUSD_CASH\"],\n    start=\"2024-08-01\", \n    resolution=\"1T\"  # 1 tick resolution\n)\n```\n\n## \ud83d\udcca Monitoring & Dashboard\n\n### Web Dashboard\n\nAccess the web interface at `http://localhost:5002`:\n\n- Real-time market data display\n- System health monitoring  \n- Connection status indicators\n- Performance metrics\n- Historical data charts\n\n### Health Checks\n\n```bash\n# Check system status\ncurl http://localhost:8080/health\n\n# Get metrics\ncurl http://localhost:8080/metrics\n```\n\n### Logging\n\nThe framework uses structured logging:\n\n```python\nimport logging\nfrom quant_async import util\n\n# Configure logging\nutil.logToConsole(\"INFO\")\n\n# Custom logger configuration\nlogging.basicConfig(\n    level=logging.INFO,\n    format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',\n    handlers=[\n        logging.FileHandler('trading.log'),\n        logging.StreamHandler()\n    ]\n)\n```\n\n## \ud83e\uddea Testing\n\nThe project includes comprehensive unit tests and integration tests.\n\n### Unit Tests\n\nRun unit tests (no external dependencies required):\n\n```bash\n# Run all unit tests (excludes integration tests)\nuv run pytest tests/ -m \"not integration\" -v\n\n# Run specific test modules\nuv run pytest tests/test_blotter.py -v\nuv run pytest tests/test_streaming.py -v\nuv run pytest tests/test_database.py -v\n\n# Run with coverage and update badge\n./scripts/update_coverage.sh\n\n# Or run coverage manually\nuv run pytest tests/ -m \"not integration\" --cov=src/quant_async --cov-report=html --cov-report=json\n\n# Update coverage badge in README\npython scripts/generate_coverage_badge.py\n```\n\n### Integration Tests\n\nIntegration tests require a real PostgreSQL database. Set up the test environment:\n\n```bash\n# 1. Copy environment template\ncp .env.example .env\n\n# 2. Create test database (as postgres user)\nsudo -u postgres psql -f setup_integration_tests.sql\n\n# 3. Configure .env file with test database settings:\n# TEST_DB_HOST=localhost\n# TEST_DB_PORT=5432\n# TEST_DB_USER=quant_async\n# TEST_DB_PASS=quant_async\n# TEST_DB_NAME=quant_async_test\n\n# 4. Run integration tests\nuv run pytest tests/ -m integration -v\n\n# 5. Run all tests (unit + integration)\nuv run pytest tests/ -v\n```\n\n**Integration Test Markers:**\n- `@pytest.mark.integration` - Requires real PostgreSQL database\n- Tests are automatically skipped if database is not available\n\n## \ud83d\udea8 Troubleshooting\n\n### Common Issues\n\n#### IB Connection Failed\n```\nError: Cannot connect to Interactive Brokers\n```\n**Solutions:**\n- Verify TWS/Gateway is running\n- Check API settings are enabled\n- Confirm correct port (7497/4001 live, 7496/4002 paper)\n- Ensure client ID is unique\n- Check firewall settings\n\n#### Database Connection Error  \n```\nError: Cannot connect to PostgreSQL\n```\n**Solutions:**\n- Verify PostgreSQL is running\n- Check database credentials in .env\n- Ensure database exists and user has permissions\n- Test connection: `psql -U quant_async -d quant_async -h localhost`\n\n#### ZeroMQ Port Conflict\n```\nError: Address already in use\n```\n**Solutions:**\n- Change ZMQ_PORT in .env\n- Kill existing process: `lsof -ti:12345 | xargs kill -9`\n- Use different port for each Blotter instance\n\n#### Symbol File Issues\n```\nError: Symbol file not found or invalid\n```\n**Solutions:**\n- Verify symbols.csv exists and is readable\n- Check CSV format matches expected columns\n- Ensure file permissions (0o666)\n- Review example symbols.csv for format\n\n### Debug Mode\n\nEnable verbose logging for troubleshooting:\n\n```python\nfrom quant_async import util\nutil.logToConsole(\"DEBUG\")\n```\n\n### Performance Tuning\n\nFor high-frequency trading:\n\n```python\n# Optimize database connections\nblotter = Blotter(\n    dbhost=\"localhost\",\n    # Increase connection pool size\n    # Configure in get_postgres_connection()\n)\n\n# Reduce ZeroMQ latency\n# Use dedicated network interface\n# Increase system buffer sizes\n```\n\n## \ud83e\udd1d Contributing\n\n1. Fork the repository\n2. Create a feature branch: `git checkout -b feature/new-feature`\n3. Make changes and add tests\n4. Run tests: `uv run pytest tests/`\n5. Run linting: `uv run ruff check src/ tests/`\n6. Commit changes: `git commit -m 'Add new feature'`\n7. Push to branch: `git push origin feature/new-feature`\n8. Submit a Pull Request\n\n## \ud83d\udcc4 License\n\nThis project is licensed under the MIT License - see the [LICENSE](LICENSE) file for details.\n",
    "bugtrack_url": null,
    "license": null,
    "summary": "Interactive Brokers Async Trading Framework for Python 3.12+",
    "version": "0.2.1",
    "project_urls": {
        "Documentation": "https://github.com/kelvingao/quant_async#readme",
        "Homepage": "https://github.com/kelvingao/quant_async",
        "Issues": "https://github.com/kelvingao/quant_async/issues",
        "Repository": "https://github.com/kelvingao/quant_async.git"
    },
    "split_keywords": [
        "trading",
        " interactive-brokers",
        " async",
        " finance",
        " algorithmic-trading"
    ],
    "urls": [
        {
            "comment_text": null,
            "digests": {
                "blake2b_256": "75a3949dfb67ec737fc559846c013343acb7221f3e7bf5ad2c7fdd660366c2b1",
                "md5": "5b571b7dd045ead89babc1b13a35819f",
                "sha256": "adb56f4177d835c5a2c5ffb49e2e216829e1108a3f122ad733eb44ef1c513668"
            },
            "downloads": -1,
            "filename": "quant_async-0.2.1-py3-none-any.whl",
            "has_sig": false,
            "md5_digest": "5b571b7dd045ead89babc1b13a35819f",
            "packagetype": "bdist_wheel",
            "python_version": "py3",
            "requires_python": ">=3.12",
            "size": 61366,
            "upload_time": "2025-08-04T11:24:06",
            "upload_time_iso_8601": "2025-08-04T11:24:06.266099Z",
            "url": "https://files.pythonhosted.org/packages/75/a3/949dfb67ec737fc559846c013343acb7221f3e7bf5ad2c7fdd660366c2b1/quant_async-0.2.1-py3-none-any.whl",
            "yanked": false,
            "yanked_reason": null
        },
        {
            "comment_text": null,
            "digests": {
                "blake2b_256": "3aacc4c73c4ce919ff5f4c3a5a0c742e395b7037740cad54b654b0281f02452b",
                "md5": "4aa9170f240a37e1df1aaf062e5906b9",
                "sha256": "c754767ae7429cd4c38a3217ccfc14d858a044124a24730490e6f589411241f6"
            },
            "downloads": -1,
            "filename": "quant_async-0.2.1.tar.gz",
            "has_sig": false,
            "md5_digest": "4aa9170f240a37e1df1aaf062e5906b9",
            "packagetype": "sdist",
            "python_version": "source",
            "requires_python": ">=3.12",
            "size": 74789,
            "upload_time": "2025-08-04T11:24:08",
            "upload_time_iso_8601": "2025-08-04T11:24:08.585759Z",
            "url": "https://files.pythonhosted.org/packages/3a/ac/c4c73c4ce919ff5f4c3a5a0c742e395b7037740cad54b654b0281f02452b/quant_async-0.2.1.tar.gz",
            "yanked": false,
            "yanked_reason": null
        }
    ],
    "upload_time": "2025-08-04 11:24:08",
    "github": true,
    "gitlab": false,
    "bitbucket": false,
    "codeberg": false,
    "github_user": "kelvingao",
    "github_project": "quant_async#readme",
    "travis_ci": false,
    "coveralls": true,
    "github_actions": true,
    "lcname": "quant-async"
}
        
Elapsed time: 0.90184s