project-x-py


Nameproject-x-py JSON
Version 3.5.7 PyPI version JSON
download
home_pageNone
SummaryHigh-performance Python SDK for futures trading with real-time WebSocket data, technical indicators, order management, and market depth analysis
upload_time2025-09-02 03:32:58
maintainerNone
docs_urlNone
authorNone
requires_python>=3.12
licenseMIT
keywords api-client financial-data futures market-data projectx real-time-data topstepx trading
VCS
bugtrack_url
requirements No requirements were recorded.
Travis-CI No Travis.
coveralls test coverage No coveralls.
            # ProjectX Python SDK

[![CI](https://github.com/TexasCoding/project-x-py/workflows/CI/badge.svg)](https://github.com/TexasCoding/project-x-py/actions/workflows/ci.yml)
[![codecov](https://codecov.io/gh/TexasCoding/project-x-py/branch/main/graph/badge.svg)](https://codecov.io/gh/TexasCoding/project-x-py)
[![PyPI - Version](https://img.shields.io/pypi/v/project-x-py)](https://pypi.org/project/project-x-py/)
[![PyPI - Downloads](https://img.shields.io/pypi/dm/project-x-py)](https://pypi.org/project/project-x-py/)
[![Python Version](https://img.shields.io/badge/python-3.12%2B-blue.svg)](https://python.org)
[![License](https://img.shields.io/badge/license-MIT-green.svg)](LICENSE)
[![Ruff](https://img.shields.io/endpoint?url=https://raw.githubusercontent.com/astral-sh/ruff/main/assets/badge/v2.json)](https://github.com/astral-sh/ruff)
[![MyPy](https://img.shields.io/badge/mypy-checked-blue)](https://github.com/python/mypy)
[![Security: bandit](https://img.shields.io/badge/security-bandit-green.svg)](https://github.com/PyCQA/bandit)
[![Performance](https://img.shields.io/badge/performance-optimized-brightgreen.svg)](#performance-optimizations)
[![Async](https://img.shields.io/badge/async-native-brightgreen.svg)](#async-architecture)
[![Documentation](https://img.shields.io/badge/docs-GitHub%20Pages-blue)](https://texascoding.github.io/project-x-py/)

A **high-performance async Python SDK** for the [ProjectX Trading Platform](https://www.projectx.com/) Gateway API. This library enables developers to build sophisticated trading strategies and applications by providing comprehensive async access to futures trading operations, historical market data, real-time streaming, technical analysis, and advanced market microstructure tools with enterprise-grade performance optimizations.

> **Note**: This is a **client library/SDK**, not a trading strategy. It provides the tools and infrastructure to help developers create their own trading strategies that integrate with the ProjectX platform.

## 🎯 What is ProjectX?

[ProjectX](https://www.projectx.com/) is a cutting-edge web-based futures trading platform that provides:
- **TradingView Charts**: Advanced charting with hundreds of indicators
- **Risk Controls**: Auto-liquidation, profit targets, daily loss limits
- **Unfiltered Market Data**: Real-time depth of market data with millisecond updates
- **REST API**: Comprehensive API for custom integrations
- **Mobile & Web Trading**: Native browser-based trading platform

This Python SDK acts as a bridge between your trading strategies and the ProjectX platform, handling all the complex API interactions, data processing, and real-time connectivity.

## 🚀 v3.5.7 - Order Placement Serialization Fix

**Latest Version**: v3.5.7 - Fixed JSON serialization error when placing orders with Decimal prices, ensuring all price values are properly converted for API requests while maintaining internal precision.

**Key Improvements**:
- 🔄 **Event Forwarding**: Fixed multi-instrument event propagation with proper bus forwarding
- 🎯 **Smart Price Alignment**: Bracket orders now auto-align to tick sizes instead of failing
- 📊 **Enhanced Examples**: All advanced trading examples updated and tested
- 🛡️ **Improved Reliability**: 30+ test fixes ensuring production stability
- ⚡ **Real-time Fixes**: Corrected bar data access in streaming examples

See [CHANGELOG.md](CHANGELOG.md) for complete v3.5.7 fixes and previous version features.

### 📦 Production Stability Guarantee

Since v3.1.1, this project maintains:
- ✅ Backward compatibility between minor versions
- ✅ Deprecation warnings for at least 2 minor versions before removal
- ✅ Breaking changes only in major releases (4.0.0+)
- ✅ Strict semantic versioning (MAJOR.MINOR.PATCH)

### Key Features

- **TradingSuite Class**: Unified entry point for simplified SDK usage
- **One-line Initialization**: `TradingSuite.create()` handles all setup
- **Feature Flags**: Easy enabling of optional components
- **Context Manager Support**: Automatic cleanup with `async with` statements
- **Unified Event Handling**: Built-in EventBus for all components
- **Performance Optimized**: Connection pooling, caching, and WebSocket batching
- **Memory Management**: Automatic overflow to disk with transparent access

### Why Async?

- **Concurrent Operations**: Execute multiple API calls simultaneously
- **Non-blocking I/O**: Handle real-time data feeds without blocking
- **Better Resource Usage**: Single thread handles thousands of concurrent operations
- **WebSocket Native**: Perfect for real-time trading applications
- **Modern Python**: Leverages Python 3.12+ async features

### Migration to v3.0+

If you're upgrading from v2.x, key changes include TradingSuite replacing factories:

```python
# Old (v2.x)
suite = await create_initialized_trading_suite(\"MNQ\", client)

# New (v3.0+)
suite = await TradingSuite.create(\"MNQ\")
```

## ✨ Key Features

### Core Trading Operations (All Async)
- **Authentication & Account Management**: Multi-account support with async session management
- **Order Management**: Place, modify, cancel orders with real-time async updates
- **Position Tracking**: Real-time position monitoring with P&L calculations
- **Market Data**: Historical and real-time data with async streaming
- **Risk Management**: Portfolio analytics and risk metrics

### Advanced Features
- **59+ Technical Indicators**: Full TA-Lib compatibility with Polars optimization including new pattern indicators
- **Level 2 OrderBook**: Depth analysis, iceberg detection, spoofing detection with 6 pattern types
- **Real-time WebSockets**: Async streaming for quotes, trades, and account updates
- **Performance Optimized**: Connection pooling, intelligent caching, memory management
- **Pattern Recognition**: Fair Value Gaps, Order Blocks, Waddah Attar Explosion, and Lorenz Formula indicators
- **Market Manipulation Detection**: Advanced spoofing detection with confidence scoring
- **Financial Precision**: All calculations use Decimal type for exact precision
- **Enterprise Error Handling**: Production-ready error handling with decorators and structured logging
- **Comprehensive Type Safety**: Full TypedDict and Protocol definitions for IDE support and static analysis
- **Advanced Statistics & Analytics**: 100% async-first statistics system with comprehensive health monitoring and performance tracking
- **Multi-format Export**: Statistics export in JSON, Prometheus, CSV, and Datadog formats with data sanitization
- **Component-Specific Tracking**: Enhanced statistics for OrderManager, PositionManager, OrderBook, and more
- **Health Monitoring**: Intelligent 0-100 health scoring with configurable thresholds and degradation detection
- **Performance Optimization**: TTL caching, parallel collection, and circular buffers for memory efficiency
- **Comprehensive Testing**: 1,300+ tests with complete code quality compliance and extensive TDD methodology

## 📦 Installation

### Using UV (Recommended)
```bash
uv add project-x-py
```

### Using pip
```bash
pip install project-x-py
```

### Development Installation
```bash
git clone https://github.com/yourusername/project-x-py.git
cd project-x-py
uv sync  # or: pip install -e ".[dev]"
```

## 🚀 Quick Start

### Basic Usage

```python
import asyncio
from project_x_py import TradingSuite

async def main():
    suite = await TradingSuite.create(\"MNQ\")

    print(f\"Connected to account: {suite.client.account_info.name}\")

    # Get instrument info if needed
    instrument = await suite.client.get_instrument(suite.instrument_id or \"MNQ\")
    print(f\"Trading {instrument.name} - Tick size: ${instrument.tickSize}\")

    data = await suite.client.get_bars(\"MNQ\", days=5)
    print(f\"Retrieved {len(data)} bars\")

    positions = await suite.positions.get_all_positions()
    for position in positions:
        print(f\"Position: {position.size} @ ${position.averagePrice}\")

    # New v3.3.0: Get comprehensive statistics (async-first API)
    stats = await suite.get_stats()
    print(f\"System Health: {stats['health_score']:.1f}/100\")
    print(f\"Total API Calls: {stats['total_api_calls']}\")
    print(f\"Memory Usage: {stats['memory_usage_mb']:.1f} MB\")

    # Export statistics to multiple formats
    prometheus_metrics = await suite.export_stats(\"prometheus\")
    csv_data = await suite.export_stats(\"csv\")

    await suite.disconnect()

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

### Multi-Instrument Trading (NEW in v3.5.0)

Manage multiple instruments simultaneously for advanced trading strategies:

```python
import asyncio
from project_x_py import TradingSuite

async def multi_instrument_example():
    # Multi-instrument setup - trade multiple futures simultaneously
    suite = await TradingSuite.create(
        instruments=["MNQ", "ES", "MGC"],  # E-mini NASDAQ, S&P 500, Gold
        timeframes=["1min", "5min"],
        enable_orderbook=True,
        enable_risk_management=True
    )

    print(f"Managing {len(suite)} instruments: {list(suite.keys())}")

    # Access specific instruments via dictionary-like interface
    mnq_context = suite["MNQ"]
    es_context = suite["ES"]
    mgc_context = suite["MGC"]

    # Get current prices for all instruments
    for symbol, context in suite.items():
        current_price = await context.data.get_current_price()
        print(f"{symbol}: ${current_price:.2f}")

    # Execute pairs trading strategy (ES vs MNQ correlation)
    es_data = await es_context.data.get_data("5min", bars=100)
    mnq_data = await mnq_context.data.get_data("5min", bars=100)

    # Analyze spread between ES and MNQ for pairs trading
    es_price = es_data.select("close").to_series().to_list()[-1]
    mnq_price = mnq_data.select("close").to_series().to_list()[-1]
    spread = es_price * 50 - mnq_price * 20  # Contract value normalized

    print(f"ES/MNQ Spread: ${spread:.2f}")

    # Portfolio-level position management
    total_exposure = 0
    for symbol, context in suite.items():
        positions = await context.positions.get_all_positions()
        for pos in positions:
            exposure = abs(pos.size * pos.averagePrice)
            total_exposure += exposure
            print(f"{symbol} Exposure: ${exposure:,.2f}")

    print(f"Total Portfolio Exposure: ${total_exposure:,.2f}")

    await suite.disconnect()

# Backward compatibility - existing single-instrument code still works
async def backward_compatible_example():
    # This still works but shows deprecation warnings
    suite = await TradingSuite.create("MNQ")  # Single instrument (legacy)
    data = await suite.data.get_data("5min")  # Direct access (deprecated)

    # Recommended: Use explicit multi-instrument syntax
    suite = await TradingSuite.create(["MNQ"])  # List notation
    data = await suite["MNQ"].data.get_data("5min")  # Explicit access

    await suite.disconnect()

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

**Migration from v3.4.x**:
- Single instrument: `TradingSuite.create("MNQ")` → `TradingSuite.create(["MNQ"])`
- Access managers: `suite.data` → `suite["MNQ"].data`
- All existing code continues to work with deprecation warnings

📚 **Full Example**: See `examples/26_multi_instrument_trading.py` for comprehensive multi-instrument strategies.

### Session Filtering (v3.4.0 - Experimental)

Filter market data and indicators by trading session (RTH vs ETH):

```python
import asyncio
from project_x_py import TradingSuite, SessionConfig, SessionType

async def session_example():
    # RTH-only trading (9:30 AM - 4:00 PM ET)
    rth_suite = await TradingSuite.create(
        ["MNQ"],  # v3.5.0: Use list notation
        timeframes=["1min", "5min"],
        session_config=SessionConfig(session_type=SessionType.RTH)
    )

    # ETH trading (24-hour excluding maintenance breaks)
    eth_suite = await TradingSuite.create(
        ["MNQ"],  # v3.5.0: Use list notation
        timeframes=["1min", "5min"],
        session_config=SessionConfig(session_type=SessionType.ETH)
    )

    # v3.5.0: Use explicit instrument access
    rth_data = await rth_suite["MNQ"].data.get_session_data("1min")
    eth_data = await eth_suite["MNQ"].data.get_session_data("1min")

    print(f"RTH bars: {len(rth_data):,}")  # ~390 bars per day
    print(f"ETH bars: {len(eth_data):,}")  # ~1,410 bars per day (366% more)

    await rth_suite.disconnect()
    await eth_suite.disconnect()

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

⚠️ **Note**: Session filtering is experimental. Test thoroughly in paper trading before production use.

📚 **Full Example**: See `examples/sessions/16_eth_vs_rth_sessions_demo.py` for comprehensive demonstration of all session features.

### Trading Suite (Enhanced in v3.5.0)

The easiest way to get started with single or multi-instrument trading:

```python
import asyncio
from project_x_py import TradingSuite, EventType

async def main():
    # v3.5.0: Multi-instrument support
    suite = await TradingSuite.create(
        instruments=["MNQ", "ES"],  # Multiple instruments
        timeframes=["5min", "15min", "1hr"],
        enable_orderbook=True,
        enable_risk_management=True
    )

    # Register event handlers (events are instrument-specific)
    async def on_new_bar(event):
        # Event data includes instrument symbol
        symbol = event.data.get('symbol', 'Unknown')
        timeframe = event.data['timeframe']
        bar_close = event.data['data']['close']
        print(f"New {symbol} {timeframe} bar: ${bar_close}")

    async def on_trade(event):
        symbol = event.data.get('symbol', 'Unknown')
        print(f"{symbol} Trade: {event.data['size']} @ ${event.data['price']}")

    # Register the handlers
    await suite.on(EventType.NEW_BAR, on_new_bar)
    await suite.on(EventType.TRADE_TICK, on_trade)

    # v3.5.0: Access components by instrument
    for symbol, context in suite.items():
        data = await context.data.get_data("5min")
        orderbook = context.orderbook  # Available when enabled
        order_manager = context.orders
        position_manager = context.positions
        print(f"{symbol}: {len(data)} bars loaded")

    # Single instrument access (for backward compatibility)
    if len(suite) == 1:
        # Single instrument - can still access directly with deprecation warning
        single_data = await suite.data.get_data("5min")  # Shows warning

        # Recommended: Use explicit access
        symbol = list(suite.keys())[0]
        single_data = await suite[symbol].data.get_data("5min")

    await suite.disconnect()

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

### Real-time Trading Example

```python
import asyncio
from project_x_py import TradingSuite

async def on_tick(event):
    tick_data = event.data
    symbol = tick_data.get('symbol', 'Unknown')
    print(f\"{symbol} Price: ${tick_data['price']}\")

async def main():
    # v3.5.0: Use list notation for single or multiple instruments
    suite = await TradingSuite.create([\"MNQ\"])

    # Get the instrument context
    mnq = suite[\"MNQ\"]

    # Register tick callback on the specific instrument
    await mnq.data.add_callback(\"tick\", on_tick)

    current_price = await mnq.data.get_current_price()

    # Place bracket order using the instrument context
    response = await mnq.orders.place_bracket_order(
        contract_id=mnq.instrument.id,  # v3.5.0: Access via context
        side=0,  # Buy
        size=1,
        entry_price=current_price,
        stop_loss_price=current_price - 10,
        take_profit_price=current_price + 15
    )

    print(f\"Order placed: {response}\")

    await asyncio.sleep(60)
    await suite.disconnect()

# Multi-instrument real-time example
async def multi_instrument_realtime():
    suite = await TradingSuite.create([\"MNQ\", \"ES\"])

    async def on_multi_tick(event):
        tick_data = event.data
        symbol = tick_data.get('symbol', 'Unknown')
        print(f\"{symbol}: ${tick_data['price']:.2f}\")

    # Register callback for all instruments
    for symbol, context in suite.items():
        await context.data.add_callback(\"tick\", on_multi_tick)

    # Monitor both instruments
    await asyncio.sleep(30)
    await suite.disconnect()

if __name__ == \"__main__\":
    asyncio.run(main())
    # asyncio.run(multi_instrument_realtime())  # Uncomment for multi-instrument
```

## ⚡ Event Handling Best Practices

### Avoiding Deadlocks (Fixed in v3.1.6)

Prior to v3.1.6, calling `suite.data` methods from within event handlers could cause deadlocks. This has been fixed, but for best performance:

```python
# Best: Use event data directly
async def on_new_bar(event):
    # Bar data is provided in the event
    bar = event.data['data']
    print(f"Close: {bar['close']}, Volume: {bar['volume']}")

# Register the handler
await suite.on(EventType.NEW_BAR, on_new_bar)

# Also OK (v3.1.6+): Access data methods if needed
async def on_new_bar_with_context(event):
    # Safe in v3.1.6+, but slightly slower
    current_price = await suite.data.get_current_price()
    historical = await suite.data.get_data("5min", bars=20)

await suite.on(EventType.NEW_BAR, on_new_bar_with_context)
```

## 📚 Documentation

### Authentication

Set environment variables:
```bash
export PROJECT_X_API_KEY="your_api_key"
export PROJECT_X_USERNAME="your_username"
```

Or use a config file (`~/.config/projectx/config.json`):
```json
{
    "api_key": "your_api_key",
    "username": "your_username",
    "api_url": "https://api.topstepx.com/api",
    "websocket_url": "wss://api.topstepx.com",
    "timezone": "US/Central"
}
```

### Available Features

TradingSuite supports optional features that can be enabled during initialization:

| Feature | String Value | Description |
|---------|-------------|-------------|
| **OrderBook** | `"orderbook"` | Level 2 market depth, bid/ask analysis, iceberg detection |
| **Risk Manager** | `"risk_manager"` | Position sizing, risk validation, managed trades |
| **Session Filtering** | Built-in (v3.4.0) | RTH/ETH session filtering (experimental) |
| **Trade Journal** | `"trade_journal"` | Trade logging and performance tracking (future) |
| **Performance Analytics** | `"performance_analytics"` | Advanced metrics and analysis (future) |
| **Auto Reconnect** | `"auto_reconnect"` | Automatic WebSocket reconnection (future) |

**Note:** PositionManager and OrderManager are always included and don't require feature flags.

```python
# Enable specific features
suite = await TradingSuite.create(
    "MNQ",
    features=["orderbook", "risk_manager"]
)

# Access feature-specific components
if suite.orderbook:  # Only available when orderbook feature is enabled
    spread = await suite.orderbook.get_bid_ask_spread()

if suite.risk_manager:  # Only available when risk_manager feature is enabled
    sizing = await suite.risk_manager.calculate_position_size(
        entry_price=100.0,
        stop_loss=99.0
    )
```

### Component Overview

#### ProjectX Client
The underlying async client, accessible via suite.client:
```python
suite = await TradingSuite.create(\"MNQ\")
# Use suite.client for direct API operations
```

#### OrderManager
Async order management via suite.orders:
```python
await suite.orders.place_market_order(suite.instrument.id, side=0, size=1)
await suite.orders.modify_order(order_id, new_price=100.50)
await suite.orders.cancel_order(order_id)
```

#### PositionManager
Async position tracking and analytics:
```python
positions = await suite.positions.get_all_positions()
pnl = await suite.positions.get_portfolio_pnl()
await suite.positions.close_position(contract_id)
```

#### RealtimeDataManager
Async multi-timeframe data management:
```python
# Data manager is automatically initialized
data = await suite.data.get_data("15min")
current_price = await suite.data.get_current_price()
```

#### OrderBook
Async Level 2 market depth analysis (when enabled):
```python
# Enable orderbook in features when creating suite
suite = await TradingSuite.create("MNQ", features=["orderbook"])

spread = await suite.orderbook.get_bid_ask_spread()
imbalance = await suite.orderbook.get_market_imbalance()
icebergs = await suite.orderbook.detect_iceberg_orders()
```

#### RiskManager
Risk management and managed trades (requires feature flag):
```python
# Enable risk manager in features
suite = await TradingSuite.create("MNQ", features=["risk_manager"])

# Risk manager integrates with PositionManager automatically
# Use for position sizing and risk validation
sizing = await suite.risk_manager.calculate_position_size(
    entry_price=100.0,
    stop_loss=99.0,
    risk_percent=0.02  # Risk 2% of account
)

# Use managed trades for automatic risk management
async with suite.managed_trade(max_risk_percent=0.01) as trade:
    # Market price fetched automatically (v3.1.11+)
    result = await trade.enter_long(
        stop_loss=current_price - 50,
        take_profit=current_price + 100
    )
```

**Note:** RiskManager requires the `"risk_manager"` feature flag and automatically integrates with PositionManager for comprehensive risk tracking.

### Statistics & Analytics (REDESIGNED in v3.3.0)

Complete async-first statistics system with advanced monitoring and export capabilities:

```python
# Get comprehensive system statistics (async-first API)
stats = await suite.get_stats()

# Health scoring (0-100) with intelligent monitoring
print(f"System Health: {stats['health_score']:.1f}/100")

# Performance metrics with enhanced tracking
print(f"API Calls: {stats['total_api_calls']}")
print(f"Success Rate: {stats['api_success_rate']:.1%}")
print(f"Memory Usage: {stats['memory_usage_mb']:.1f} MB")

# Component-specific statistics (all async for consistency)
order_stats = await suite.orders.get_stats()
print(f"Fill Rate: {order_stats['fill_rate']:.1%}")
print(f"Average Fill Time: {order_stats['avg_fill_time_ms']:.0f}ms")

position_stats = await suite.positions.get_stats()
print(f"Win Rate: {position_stats.get('win_rate', 0):.1%}")

# Multi-format export capabilities
prometheus_metrics = await suite.export_stats("prometheus")
csv_data = await suite.export_stats("csv")
datadog_metrics = await suite.export_stats("datadog")

# Real-time health monitoring with degradation detection
health_score = await suite.get_health_score()
if health_score < 70:
    print("⚠️ System health degraded - check components")
    component_health = await suite.get_component_health()
    for name, health in component_health.items():
        if health['error_count'] > 0:
            print(f"  {name}: {health['error_count']} errors")
```

**Key Features (v3.3.0):**
- **100% Async Architecture**: All statistics methods use async/await for optimal performance
- **Multi-format Export**: JSON, Prometheus, CSV, and Datadog formats with data sanitization
- **Component-Specific Tracking**: Enhanced statistics for all managers with specialized metrics
- **Health Monitoring**: Intelligent 0-100 health scoring with configurable thresholds
- **Performance Optimization**: TTL caching, parallel collection, and circular buffers
- **Memory Efficiency**: Circular buffers and lock-free reads for frequently accessed metrics
- **Comprehensive Testing**: 45+ tests covering all aspects of the async statistics system

### Technical Indicators

All 59+ indicators work with async data pipelines:
```python
import polars as pl
from project_x_py.indicators import RSI, SMA, MACD, FVG, ORDERBLOCK, WAE

# Get data - multiple ways
data = await client.get_bars("ES", days=30)  # Last 30 days

# Or use specific time range (v3.1.5+)
from datetime import datetime
start = datetime(2025, 1, 1, 9, 30)
end = datetime(2025, 1, 10, 16, 0)
data = await client.get_bars("ES", start_time=start, end_time=end)

# Apply traditional indicators
data = data.pipe(SMA, period=20).pipe(RSI, period=14)

# Apply pattern recognition indicators
data_with_fvg = FVG(data, min_gap_size=0.001, check_mitigation=True)
data_with_ob = ORDERBLOCK(data, min_volume_percentile=70)
data_with_wae = WAE(data, sensitivity=150)

# Or use class-based interface
from project_x_py.indicators import OrderBlock, FVG, WAE
ob = OrderBlock()
data_with_ob = ob.calculate(data, use_wicks=True)
```

#### New Pattern Indicators (v2.0.2)
- **Fair Value Gap (FVG)**: Identifies price imbalance areas
- **Order Block**: Detects institutional order zones
- **Waddah Attar Explosion (WAE)**: Strong trend and breakout detection

## 🏗️ Examples

The `examples/` directory contains comprehensive async examples:

### Core Functionality
- **00_trading_suite_demo.py** - Complete TradingSuite demonstration
- **01_basic_client_connection.py** - Async authentication and basic operations
- **02_order_management.py** - Async order placement and management
- **03_position_management.py** - Async position tracking and P&L
- **04_realtime_data.py** - Real-time async data streaming

### Advanced Features
- **05_orderbook_analysis.py** - Async market depth analysis
- **06_advanced_orderbook.py** - Advanced orderbook analytics
- **06_multi_timeframe_strategy.py** - Async multi-timeframe trading
- **07_technical_indicators.py** - Using indicators with async data
- **08_order_and_position_tracking.py** - Integrated async monitoring
- **09_get_check_available_instruments.py** - Interactive async instrument search

### Multi-Instrument Trading (NEW in v3.5.0)
- **26_multi_instrument_trading.py** - Complete multi-instrument trading demo
- **Portfolio management** - Risk management across multiple instruments
- **Pairs trading** - ES vs MNQ spread analysis and correlation strategies
- **Cross-market analysis** - Commodities, indices, and currency futures

### Event System & Data Access
- **10_unified_event_system.py** - Event-driven trading with EventBus
- **11_simplified_data_access.py** - Simplified data access patterns
- **12_simplified_multi_timeframe.py** - Multi-timeframe analysis
- **12_simplified_strategy.py** - Simplified strategy using auto-initialization

### Risk Management & Order Lifecycle
- **13_enhanced_models.py** - Enhanced data models demonstration
- **15_order_lifecycle_tracking.py** - Complete order lifecycle monitoring
- **15_risk_management.py** - Risk management features
- **16_managed_trades.py** - ManagedTrade context manager usage
- **16_join_orders.py** - Advanced order joining techniques

## 🔧 Configuration

### TradingSuiteConfig Options

Use parameters in TradingSuite.create()

### Performance Tuning

Configure caching and memory limits:
```python
# In OrderBook
orderbook = OrderBook(
    instrument="ES",
    max_trades=10000,  # Trade history limit
    max_depth_entries=1000,  # Depth per side
    cache_ttl=300  # 5 minutes
)

# In ProjectXRealtimeDataManager (integrated with TradingSuite)
# Data manager is configured via DataManagerConfig
from project_x_py.realtime_data_manager.types import DataManagerConfig

config = DataManagerConfig(
    max_bars_per_timeframe=1000,
    enable_mmap_overflow=True,
    enable_dynamic_limits=True
)
```

## 🔍 Error Handling & Logging (v2.0.5+)

### Structured Error Handling

All async operations use typed exceptions with automatic retry and logging:

```python
from project_x_py.exceptions import (
    ProjectXAuthenticationError,
    ProjectXOrderError,
    ProjectXRateLimitError
)
from project_x_py.utils import configure_sdk_logging

# Configure logging for production
configure_sdk_logging(
    level=logging.INFO,
    format_json=True,  # JSON logs for production
    log_file="/var/log/projectx/trading.log"
)

try:
    async with ProjectX.from_env() as client:
        await client.authenticate()  # Automatic retry on network errors
except ProjectXAuthenticationError as e:
    # Structured error with context
    print(f"Authentication failed: {e}")
except ProjectXRateLimitError as e:
    # Automatic backoff already attempted
    print(f"Rate limit exceeded: {e}")
```

### Error Handling Decorators

The SDK uses decorators for consistent error handling:

```python
# All API methods have built-in error handling
@handle_errors("place order")
@retry_on_network_error(max_attempts=3)
@validate_response(required_fields=["orderId"])
async def place_order(self, ...):
    # Method implementation
```

## 🔧 Troubleshooting

### Common Issues

#### Authentication Issues
```python
# Error: "PROJECT_X_API_KEY environment variable is required"
# Solution: Set environment variables before running
export PROJECT_X_API_KEY="your_api_key"
export PROJECT_X_USERNAME="your_username"

# Or use config file at ~/.config/projectx/config.json
```

#### Instrument Not Found
```python
# Error: "Instrument MNQ not found"
# Solution: Verify instrument symbol is correct
# Common symbols: "MNQ", "MES", "MGC", "ES", "NQ"
```

#### Connection Timeouts
```python
# The TradingSuite handles connections automatically
# If you need custom timeout handling:
try:
    suite = await TradingSuite.create(
        "MNQ",
        timeout=30  # Custom timeout in seconds
    )
except Exception as e:
    print(f"Connection failed: {e}")
```

#### Memory Issues with Long-Running Strategies
```python
# The suite automatically manages memory, but for long-running strategies:
# 1. Use reasonable initial_days (3-7 is usually sufficient)
# 2. The data manager automatically maintains sliding windows
# 3. OrderBook has built-in memory limits
```

#### Rate Limiting
```python
# The SDK handles rate limiting automatically, but if you encounter issues:
# 1. Reduce concurrent API calls
# 2. Add delays between operations
# 3. Use batch operations where available
```

## 📌 Versioning Policy

As of v3.1.1, this project follows strict [Semantic Versioning](https://semver.org/):

- **PATCH** (x.x.N): Bug fixes only, no API changes
- **MINOR** (x.N.x): New features, backward compatible, deprecation warnings added
- **MAJOR** (N.x.x): Breaking changes allowed, deprecated features removed

### Deprecation Policy
- Features marked as deprecated will include clear migration instructions
- Deprecated features maintained for at least 2 minor versions
- Removal only occurs in major version releases

## 🤝 Contributing

We welcome contributions! Please see [CONTRIBUTING.md](CONTRIBUTING.md) for guidelines.

### Development Setup
```bash
# Clone repository
git clone https://github.com/yourusername/project-x-py.git
cd project-x-py

# Install with dev dependencies
uv sync

# Run tests
uv run pytest

# Format code
uv run ruff format .

# Lint
uv run ruff check .
```

## 📄 License

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

## 🔗 Resources

- [ProjectX Platform](https://www.projectx.com/)
- [API Documentation](https://texascoding.github.io/project-x-py/)
- [GitHub Repository](https://github.com/TexasCoding/project-x-py)
- [PyPI Package](https://pypi.org/project/project-x-py/)

## ⚠️ Disclaimer

This SDK is for educational and development purposes. Trading futures involves substantial risk of loss and is not suitable for all investors. Past performance is not indicative of future results. Always test your strategies thoroughly before using real funds.

            

Raw data

            {
    "_id": null,
    "home_page": null,
    "name": "project-x-py",
    "maintainer": null,
    "docs_url": null,
    "requires_python": ">=3.12",
    "maintainer_email": "TexasCoding <jeff10278@me.com>",
    "keywords": "api-client, financial-data, futures, market-data, projectx, real-time-data, topstepx, trading",
    "author": null,
    "author_email": "TexasCoding <jeff10278@me.com>",
    "download_url": "https://files.pythonhosted.org/packages/07/d4/00a33a927baa5edb0cb1e99872a39eedc71fa5d51c25fc033c6024b7aba3/project_x_py-3.5.7.tar.gz",
    "platform": null,
    "description": "# ProjectX Python SDK\n\n[![CI](https://github.com/TexasCoding/project-x-py/workflows/CI/badge.svg)](https://github.com/TexasCoding/project-x-py/actions/workflows/ci.yml)\n[![codecov](https://codecov.io/gh/TexasCoding/project-x-py/branch/main/graph/badge.svg)](https://codecov.io/gh/TexasCoding/project-x-py)\n[![PyPI - Version](https://img.shields.io/pypi/v/project-x-py)](https://pypi.org/project/project-x-py/)\n[![PyPI - Downloads](https://img.shields.io/pypi/dm/project-x-py)](https://pypi.org/project/project-x-py/)\n[![Python Version](https://img.shields.io/badge/python-3.12%2B-blue.svg)](https://python.org)\n[![License](https://img.shields.io/badge/license-MIT-green.svg)](LICENSE)\n[![Ruff](https://img.shields.io/endpoint?url=https://raw.githubusercontent.com/astral-sh/ruff/main/assets/badge/v2.json)](https://github.com/astral-sh/ruff)\n[![MyPy](https://img.shields.io/badge/mypy-checked-blue)](https://github.com/python/mypy)\n[![Security: bandit](https://img.shields.io/badge/security-bandit-green.svg)](https://github.com/PyCQA/bandit)\n[![Performance](https://img.shields.io/badge/performance-optimized-brightgreen.svg)](#performance-optimizations)\n[![Async](https://img.shields.io/badge/async-native-brightgreen.svg)](#async-architecture)\n[![Documentation](https://img.shields.io/badge/docs-GitHub%20Pages-blue)](https://texascoding.github.io/project-x-py/)\n\nA **high-performance async Python SDK** for the [ProjectX Trading Platform](https://www.projectx.com/) Gateway API. This library enables developers to build sophisticated trading strategies and applications by providing comprehensive async access to futures trading operations, historical market data, real-time streaming, technical analysis, and advanced market microstructure tools with enterprise-grade performance optimizations.\n\n> **Note**: This is a **client library/SDK**, not a trading strategy. It provides the tools and infrastructure to help developers create their own trading strategies that integrate with the ProjectX platform.\n\n## \ud83c\udfaf What is ProjectX?\n\n[ProjectX](https://www.projectx.com/) is a cutting-edge web-based futures trading platform that provides:\n- **TradingView Charts**: Advanced charting with hundreds of indicators\n- **Risk Controls**: Auto-liquidation, profit targets, daily loss limits\n- **Unfiltered Market Data**: Real-time depth of market data with millisecond updates\n- **REST API**: Comprehensive API for custom integrations\n- **Mobile & Web Trading**: Native browser-based trading platform\n\nThis Python SDK acts as a bridge between your trading strategies and the ProjectX platform, handling all the complex API interactions, data processing, and real-time connectivity.\n\n## \ud83d\ude80 v3.5.7 - Order Placement Serialization Fix\n\n**Latest Version**: v3.5.7 - Fixed JSON serialization error when placing orders with Decimal prices, ensuring all price values are properly converted for API requests while maintaining internal precision.\n\n**Key Improvements**:\n- \ud83d\udd04 **Event Forwarding**: Fixed multi-instrument event propagation with proper bus forwarding\n- \ud83c\udfaf **Smart Price Alignment**: Bracket orders now auto-align to tick sizes instead of failing\n- \ud83d\udcca **Enhanced Examples**: All advanced trading examples updated and tested\n- \ud83d\udee1\ufe0f **Improved Reliability**: 30+ test fixes ensuring production stability\n- \u26a1 **Real-time Fixes**: Corrected bar data access in streaming examples\n\nSee [CHANGELOG.md](CHANGELOG.md) for complete v3.5.7 fixes and previous version features.\n\n### \ud83d\udce6 Production Stability Guarantee\n\nSince v3.1.1, this project maintains:\n- \u2705 Backward compatibility between minor versions\n- \u2705 Deprecation warnings for at least 2 minor versions before removal\n- \u2705 Breaking changes only in major releases (4.0.0+)\n- \u2705 Strict semantic versioning (MAJOR.MINOR.PATCH)\n\n### Key Features\n\n- **TradingSuite Class**: Unified entry point for simplified SDK usage\n- **One-line Initialization**: `TradingSuite.create()` handles all setup\n- **Feature Flags**: Easy enabling of optional components\n- **Context Manager Support**: Automatic cleanup with `async with` statements\n- **Unified Event Handling**: Built-in EventBus for all components\n- **Performance Optimized**: Connection pooling, caching, and WebSocket batching\n- **Memory Management**: Automatic overflow to disk with transparent access\n\n### Why Async?\n\n- **Concurrent Operations**: Execute multiple API calls simultaneously\n- **Non-blocking I/O**: Handle real-time data feeds without blocking\n- **Better Resource Usage**: Single thread handles thousands of concurrent operations\n- **WebSocket Native**: Perfect for real-time trading applications\n- **Modern Python**: Leverages Python 3.12+ async features\n\n### Migration to v3.0+\n\nIf you're upgrading from v2.x, key changes include TradingSuite replacing factories:\n\n```python\n# Old (v2.x)\nsuite = await create_initialized_trading_suite(\\\"MNQ\\\", client)\n\n# New (v3.0+)\nsuite = await TradingSuite.create(\\\"MNQ\\\")\n```\n\n## \u2728 Key Features\n\n### Core Trading Operations (All Async)\n- **Authentication & Account Management**: Multi-account support with async session management\n- **Order Management**: Place, modify, cancel orders with real-time async updates\n- **Position Tracking**: Real-time position monitoring with P&L calculations\n- **Market Data**: Historical and real-time data with async streaming\n- **Risk Management**: Portfolio analytics and risk metrics\n\n### Advanced Features\n- **59+ Technical Indicators**: Full TA-Lib compatibility with Polars optimization including new pattern indicators\n- **Level 2 OrderBook**: Depth analysis, iceberg detection, spoofing detection with 6 pattern types\n- **Real-time WebSockets**: Async streaming for quotes, trades, and account updates\n- **Performance Optimized**: Connection pooling, intelligent caching, memory management\n- **Pattern Recognition**: Fair Value Gaps, Order Blocks, Waddah Attar Explosion, and Lorenz Formula indicators\n- **Market Manipulation Detection**: Advanced spoofing detection with confidence scoring\n- **Financial Precision**: All calculations use Decimal type for exact precision\n- **Enterprise Error Handling**: Production-ready error handling with decorators and structured logging\n- **Comprehensive Type Safety**: Full TypedDict and Protocol definitions for IDE support and static analysis\n- **Advanced Statistics & Analytics**: 100% async-first statistics system with comprehensive health monitoring and performance tracking\n- **Multi-format Export**: Statistics export in JSON, Prometheus, CSV, and Datadog formats with data sanitization\n- **Component-Specific Tracking**: Enhanced statistics for OrderManager, PositionManager, OrderBook, and more\n- **Health Monitoring**: Intelligent 0-100 health scoring with configurable thresholds and degradation detection\n- **Performance Optimization**: TTL caching, parallel collection, and circular buffers for memory efficiency\n- **Comprehensive Testing**: 1,300+ tests with complete code quality compliance and extensive TDD methodology\n\n## \ud83d\udce6 Installation\n\n### Using UV (Recommended)\n```bash\nuv add project-x-py\n```\n\n### Using pip\n```bash\npip install project-x-py\n```\n\n### Development Installation\n```bash\ngit clone https://github.com/yourusername/project-x-py.git\ncd project-x-py\nuv sync  # or: pip install -e \".[dev]\"\n```\n\n## \ud83d\ude80 Quick Start\n\n### Basic Usage\n\n```python\nimport asyncio\nfrom project_x_py import TradingSuite\n\nasync def main():\n    suite = await TradingSuite.create(\\\"MNQ\\\")\n\n    print(f\\\"Connected to account: {suite.client.account_info.name}\\\")\n\n    # Get instrument info if needed\n    instrument = await suite.client.get_instrument(suite.instrument_id or \\\"MNQ\\\")\n    print(f\\\"Trading {instrument.name} - Tick size: ${instrument.tickSize}\\\")\n\n    data = await suite.client.get_bars(\\\"MNQ\\\", days=5)\n    print(f\\\"Retrieved {len(data)} bars\\\")\n\n    positions = await suite.positions.get_all_positions()\n    for position in positions:\n        print(f\\\"Position: {position.size} @ ${position.averagePrice}\\\")\n\n    # New v3.3.0: Get comprehensive statistics (async-first API)\n    stats = await suite.get_stats()\n    print(f\\\"System Health: {stats['health_score']:.1f}/100\\\")\n    print(f\\\"Total API Calls: {stats['total_api_calls']}\\\")\n    print(f\\\"Memory Usage: {stats['memory_usage_mb']:.1f} MB\\\")\n\n    # Export statistics to multiple formats\n    prometheus_metrics = await suite.export_stats(\\\"prometheus\\\")\n    csv_data = await suite.export_stats(\\\"csv\\\")\n\n    await suite.disconnect()\n\nif __name__ == \\\"__main__\\\":\n    asyncio.run(main())\n```\n\n### Multi-Instrument Trading (NEW in v3.5.0)\n\nManage multiple instruments simultaneously for advanced trading strategies:\n\n```python\nimport asyncio\nfrom project_x_py import TradingSuite\n\nasync def multi_instrument_example():\n    # Multi-instrument setup - trade multiple futures simultaneously\n    suite = await TradingSuite.create(\n        instruments=[\"MNQ\", \"ES\", \"MGC\"],  # E-mini NASDAQ, S&P 500, Gold\n        timeframes=[\"1min\", \"5min\"],\n        enable_orderbook=True,\n        enable_risk_management=True\n    )\n\n    print(f\"Managing {len(suite)} instruments: {list(suite.keys())}\")\n\n    # Access specific instruments via dictionary-like interface\n    mnq_context = suite[\"MNQ\"]\n    es_context = suite[\"ES\"]\n    mgc_context = suite[\"MGC\"]\n\n    # Get current prices for all instruments\n    for symbol, context in suite.items():\n        current_price = await context.data.get_current_price()\n        print(f\"{symbol}: ${current_price:.2f}\")\n\n    # Execute pairs trading strategy (ES vs MNQ correlation)\n    es_data = await es_context.data.get_data(\"5min\", bars=100)\n    mnq_data = await mnq_context.data.get_data(\"5min\", bars=100)\n\n    # Analyze spread between ES and MNQ for pairs trading\n    es_price = es_data.select(\"close\").to_series().to_list()[-1]\n    mnq_price = mnq_data.select(\"close\").to_series().to_list()[-1]\n    spread = es_price * 50 - mnq_price * 20  # Contract value normalized\n\n    print(f\"ES/MNQ Spread: ${spread:.2f}\")\n\n    # Portfolio-level position management\n    total_exposure = 0\n    for symbol, context in suite.items():\n        positions = await context.positions.get_all_positions()\n        for pos in positions:\n            exposure = abs(pos.size * pos.averagePrice)\n            total_exposure += exposure\n            print(f\"{symbol} Exposure: ${exposure:,.2f}\")\n\n    print(f\"Total Portfolio Exposure: ${total_exposure:,.2f}\")\n\n    await suite.disconnect()\n\n# Backward compatibility - existing single-instrument code still works\nasync def backward_compatible_example():\n    # This still works but shows deprecation warnings\n    suite = await TradingSuite.create(\"MNQ\")  # Single instrument (legacy)\n    data = await suite.data.get_data(\"5min\")  # Direct access (deprecated)\n\n    # Recommended: Use explicit multi-instrument syntax\n    suite = await TradingSuite.create([\"MNQ\"])  # List notation\n    data = await suite[\"MNQ\"].data.get_data(\"5min\")  # Explicit access\n\n    await suite.disconnect()\n\nif __name__ == \"__main__\":\n    asyncio.run(multi_instrument_example())\n```\n\n**Migration from v3.4.x**:\n- Single instrument: `TradingSuite.create(\"MNQ\")` \u2192 `TradingSuite.create([\"MNQ\"])`\n- Access managers: `suite.data` \u2192 `suite[\"MNQ\"].data`\n- All existing code continues to work with deprecation warnings\n\n\ud83d\udcda **Full Example**: See `examples/26_multi_instrument_trading.py` for comprehensive multi-instrument strategies.\n\n### Session Filtering (v3.4.0 - Experimental)\n\nFilter market data and indicators by trading session (RTH vs ETH):\n\n```python\nimport asyncio\nfrom project_x_py import TradingSuite, SessionConfig, SessionType\n\nasync def session_example():\n    # RTH-only trading (9:30 AM - 4:00 PM ET)\n    rth_suite = await TradingSuite.create(\n        [\"MNQ\"],  # v3.5.0: Use list notation\n        timeframes=[\"1min\", \"5min\"],\n        session_config=SessionConfig(session_type=SessionType.RTH)\n    )\n\n    # ETH trading (24-hour excluding maintenance breaks)\n    eth_suite = await TradingSuite.create(\n        [\"MNQ\"],  # v3.5.0: Use list notation\n        timeframes=[\"1min\", \"5min\"],\n        session_config=SessionConfig(session_type=SessionType.ETH)\n    )\n\n    # v3.5.0: Use explicit instrument access\n    rth_data = await rth_suite[\"MNQ\"].data.get_session_data(\"1min\")\n    eth_data = await eth_suite[\"MNQ\"].data.get_session_data(\"1min\")\n\n    print(f\"RTH bars: {len(rth_data):,}\")  # ~390 bars per day\n    print(f\"ETH bars: {len(eth_data):,}\")  # ~1,410 bars per day (366% more)\n\n    await rth_suite.disconnect()\n    await eth_suite.disconnect()\n\nif __name__ == \"__main__\":\n    asyncio.run(session_example())\n```\n\n\u26a0\ufe0f **Note**: Session filtering is experimental. Test thoroughly in paper trading before production use.\n\n\ud83d\udcda **Full Example**: See `examples/sessions/16_eth_vs_rth_sessions_demo.py` for comprehensive demonstration of all session features.\n\n### Trading Suite (Enhanced in v3.5.0)\n\nThe easiest way to get started with single or multi-instrument trading:\n\n```python\nimport asyncio\nfrom project_x_py import TradingSuite, EventType\n\nasync def main():\n    # v3.5.0: Multi-instrument support\n    suite = await TradingSuite.create(\n        instruments=[\"MNQ\", \"ES\"],  # Multiple instruments\n        timeframes=[\"5min\", \"15min\", \"1hr\"],\n        enable_orderbook=True,\n        enable_risk_management=True\n    )\n\n    # Register event handlers (events are instrument-specific)\n    async def on_new_bar(event):\n        # Event data includes instrument symbol\n        symbol = event.data.get('symbol', 'Unknown')\n        timeframe = event.data['timeframe']\n        bar_close = event.data['data']['close']\n        print(f\"New {symbol} {timeframe} bar: ${bar_close}\")\n\n    async def on_trade(event):\n        symbol = event.data.get('symbol', 'Unknown')\n        print(f\"{symbol} Trade: {event.data['size']} @ ${event.data['price']}\")\n\n    # Register the handlers\n    await suite.on(EventType.NEW_BAR, on_new_bar)\n    await suite.on(EventType.TRADE_TICK, on_trade)\n\n    # v3.5.0: Access components by instrument\n    for symbol, context in suite.items():\n        data = await context.data.get_data(\"5min\")\n        orderbook = context.orderbook  # Available when enabled\n        order_manager = context.orders\n        position_manager = context.positions\n        print(f\"{symbol}: {len(data)} bars loaded\")\n\n    # Single instrument access (for backward compatibility)\n    if len(suite) == 1:\n        # Single instrument - can still access directly with deprecation warning\n        single_data = await suite.data.get_data(\"5min\")  # Shows warning\n\n        # Recommended: Use explicit access\n        symbol = list(suite.keys())[0]\n        single_data = await suite[symbol].data.get_data(\"5min\")\n\n    await suite.disconnect()\n\nif __name__ == \\\"__main__\\\":\n    asyncio.run(main())\n```\n\n### Real-time Trading Example\n\n```python\nimport asyncio\nfrom project_x_py import TradingSuite\n\nasync def on_tick(event):\n    tick_data = event.data\n    symbol = tick_data.get('symbol', 'Unknown')\n    print(f\\\"{symbol} Price: ${tick_data['price']}\\\")\n\nasync def main():\n    # v3.5.0: Use list notation for single or multiple instruments\n    suite = await TradingSuite.create([\\\"MNQ\\\"])\n\n    # Get the instrument context\n    mnq = suite[\\\"MNQ\\\"]\n\n    # Register tick callback on the specific instrument\n    await mnq.data.add_callback(\\\"tick\\\", on_tick)\n\n    current_price = await mnq.data.get_current_price()\n\n    # Place bracket order using the instrument context\n    response = await mnq.orders.place_bracket_order(\n        contract_id=mnq.instrument.id,  # v3.5.0: Access via context\n        side=0,  # Buy\n        size=1,\n        entry_price=current_price,\n        stop_loss_price=current_price - 10,\n        take_profit_price=current_price + 15\n    )\n\n    print(f\\\"Order placed: {response}\\\")\n\n    await asyncio.sleep(60)\n    await suite.disconnect()\n\n# Multi-instrument real-time example\nasync def multi_instrument_realtime():\n    suite = await TradingSuite.create([\\\"MNQ\\\", \\\"ES\\\"])\n\n    async def on_multi_tick(event):\n        tick_data = event.data\n        symbol = tick_data.get('symbol', 'Unknown')\n        print(f\\\"{symbol}: ${tick_data['price']:.2f}\\\")\n\n    # Register callback for all instruments\n    for symbol, context in suite.items():\n        await context.data.add_callback(\\\"tick\\\", on_multi_tick)\n\n    # Monitor both instruments\n    await asyncio.sleep(30)\n    await suite.disconnect()\n\nif __name__ == \\\"__main__\\\":\n    asyncio.run(main())\n    # asyncio.run(multi_instrument_realtime())  # Uncomment for multi-instrument\n```\n\n## \u26a1 Event Handling Best Practices\n\n### Avoiding Deadlocks (Fixed in v3.1.6)\n\nPrior to v3.1.6, calling `suite.data` methods from within event handlers could cause deadlocks. This has been fixed, but for best performance:\n\n```python\n# Best: Use event data directly\nasync def on_new_bar(event):\n    # Bar data is provided in the event\n    bar = event.data['data']\n    print(f\"Close: {bar['close']}, Volume: {bar['volume']}\")\n\n# Register the handler\nawait suite.on(EventType.NEW_BAR, on_new_bar)\n\n# Also OK (v3.1.6+): Access data methods if needed\nasync def on_new_bar_with_context(event):\n    # Safe in v3.1.6+, but slightly slower\n    current_price = await suite.data.get_current_price()\n    historical = await suite.data.get_data(\"5min\", bars=20)\n\nawait suite.on(EventType.NEW_BAR, on_new_bar_with_context)\n```\n\n## \ud83d\udcda Documentation\n\n### Authentication\n\nSet environment variables:\n```bash\nexport PROJECT_X_API_KEY=\"your_api_key\"\nexport PROJECT_X_USERNAME=\"your_username\"\n```\n\nOr use a config file (`~/.config/projectx/config.json`):\n```json\n{\n    \"api_key\": \"your_api_key\",\n    \"username\": \"your_username\",\n    \"api_url\": \"https://api.topstepx.com/api\",\n    \"websocket_url\": \"wss://api.topstepx.com\",\n    \"timezone\": \"US/Central\"\n}\n```\n\n### Available Features\n\nTradingSuite supports optional features that can be enabled during initialization:\n\n| Feature | String Value | Description |\n|---------|-------------|-------------|\n| **OrderBook** | `\"orderbook\"` | Level 2 market depth, bid/ask analysis, iceberg detection |\n| **Risk Manager** | `\"risk_manager\"` | Position sizing, risk validation, managed trades |\n| **Session Filtering** | Built-in (v3.4.0) | RTH/ETH session filtering (experimental) |\n| **Trade Journal** | `\"trade_journal\"` | Trade logging and performance tracking (future) |\n| **Performance Analytics** | `\"performance_analytics\"` | Advanced metrics and analysis (future) |\n| **Auto Reconnect** | `\"auto_reconnect\"` | Automatic WebSocket reconnection (future) |\n\n**Note:** PositionManager and OrderManager are always included and don't require feature flags.\n\n```python\n# Enable specific features\nsuite = await TradingSuite.create(\n    \"MNQ\",\n    features=[\"orderbook\", \"risk_manager\"]\n)\n\n# Access feature-specific components\nif suite.orderbook:  # Only available when orderbook feature is enabled\n    spread = await suite.orderbook.get_bid_ask_spread()\n\nif suite.risk_manager:  # Only available when risk_manager feature is enabled\n    sizing = await suite.risk_manager.calculate_position_size(\n        entry_price=100.0,\n        stop_loss=99.0\n    )\n```\n\n### Component Overview\n\n#### ProjectX Client\nThe underlying async client, accessible via suite.client:\n```python\nsuite = await TradingSuite.create(\\\"MNQ\\\")\n# Use suite.client for direct API operations\n```\n\n#### OrderManager\nAsync order management via suite.orders:\n```python\nawait suite.orders.place_market_order(suite.instrument.id, side=0, size=1)\nawait suite.orders.modify_order(order_id, new_price=100.50)\nawait suite.orders.cancel_order(order_id)\n```\n\n#### PositionManager\nAsync position tracking and analytics:\n```python\npositions = await suite.positions.get_all_positions()\npnl = await suite.positions.get_portfolio_pnl()\nawait suite.positions.close_position(contract_id)\n```\n\n#### RealtimeDataManager\nAsync multi-timeframe data management:\n```python\n# Data manager is automatically initialized\ndata = await suite.data.get_data(\"15min\")\ncurrent_price = await suite.data.get_current_price()\n```\n\n#### OrderBook\nAsync Level 2 market depth analysis (when enabled):\n```python\n# Enable orderbook in features when creating suite\nsuite = await TradingSuite.create(\"MNQ\", features=[\"orderbook\"])\n\nspread = await suite.orderbook.get_bid_ask_spread()\nimbalance = await suite.orderbook.get_market_imbalance()\nicebergs = await suite.orderbook.detect_iceberg_orders()\n```\n\n#### RiskManager\nRisk management and managed trades (requires feature flag):\n```python\n# Enable risk manager in features\nsuite = await TradingSuite.create(\"MNQ\", features=[\"risk_manager\"])\n\n# Risk manager integrates with PositionManager automatically\n# Use for position sizing and risk validation\nsizing = await suite.risk_manager.calculate_position_size(\n    entry_price=100.0,\n    stop_loss=99.0,\n    risk_percent=0.02  # Risk 2% of account\n)\n\n# Use managed trades for automatic risk management\nasync with suite.managed_trade(max_risk_percent=0.01) as trade:\n    # Market price fetched automatically (v3.1.11+)\n    result = await trade.enter_long(\n        stop_loss=current_price - 50,\n        take_profit=current_price + 100\n    )\n```\n\n**Note:** RiskManager requires the `\"risk_manager\"` feature flag and automatically integrates with PositionManager for comprehensive risk tracking.\n\n### Statistics & Analytics (REDESIGNED in v3.3.0)\n\nComplete async-first statistics system with advanced monitoring and export capabilities:\n\n```python\n# Get comprehensive system statistics (async-first API)\nstats = await suite.get_stats()\n\n# Health scoring (0-100) with intelligent monitoring\nprint(f\"System Health: {stats['health_score']:.1f}/100\")\n\n# Performance metrics with enhanced tracking\nprint(f\"API Calls: {stats['total_api_calls']}\")\nprint(f\"Success Rate: {stats['api_success_rate']:.1%}\")\nprint(f\"Memory Usage: {stats['memory_usage_mb']:.1f} MB\")\n\n# Component-specific statistics (all async for consistency)\norder_stats = await suite.orders.get_stats()\nprint(f\"Fill Rate: {order_stats['fill_rate']:.1%}\")\nprint(f\"Average Fill Time: {order_stats['avg_fill_time_ms']:.0f}ms\")\n\nposition_stats = await suite.positions.get_stats()\nprint(f\"Win Rate: {position_stats.get('win_rate', 0):.1%}\")\n\n# Multi-format export capabilities\nprometheus_metrics = await suite.export_stats(\"prometheus\")\ncsv_data = await suite.export_stats(\"csv\")\ndatadog_metrics = await suite.export_stats(\"datadog\")\n\n# Real-time health monitoring with degradation detection\nhealth_score = await suite.get_health_score()\nif health_score < 70:\n    print(\"\u26a0\ufe0f System health degraded - check components\")\n    component_health = await suite.get_component_health()\n    for name, health in component_health.items():\n        if health['error_count'] > 0:\n            print(f\"  {name}: {health['error_count']} errors\")\n```\n\n**Key Features (v3.3.0):**\n- **100% Async Architecture**: All statistics methods use async/await for optimal performance\n- **Multi-format Export**: JSON, Prometheus, CSV, and Datadog formats with data sanitization\n- **Component-Specific Tracking**: Enhanced statistics for all managers with specialized metrics\n- **Health Monitoring**: Intelligent 0-100 health scoring with configurable thresholds\n- **Performance Optimization**: TTL caching, parallel collection, and circular buffers\n- **Memory Efficiency**: Circular buffers and lock-free reads for frequently accessed metrics\n- **Comprehensive Testing**: 45+ tests covering all aspects of the async statistics system\n\n### Technical Indicators\n\nAll 59+ indicators work with async data pipelines:\n```python\nimport polars as pl\nfrom project_x_py.indicators import RSI, SMA, MACD, FVG, ORDERBLOCK, WAE\n\n# Get data - multiple ways\ndata = await client.get_bars(\"ES\", days=30)  # Last 30 days\n\n# Or use specific time range (v3.1.5+)\nfrom datetime import datetime\nstart = datetime(2025, 1, 1, 9, 30)\nend = datetime(2025, 1, 10, 16, 0)\ndata = await client.get_bars(\"ES\", start_time=start, end_time=end)\n\n# Apply traditional indicators\ndata = data.pipe(SMA, period=20).pipe(RSI, period=14)\n\n# Apply pattern recognition indicators\ndata_with_fvg = FVG(data, min_gap_size=0.001, check_mitigation=True)\ndata_with_ob = ORDERBLOCK(data, min_volume_percentile=70)\ndata_with_wae = WAE(data, sensitivity=150)\n\n# Or use class-based interface\nfrom project_x_py.indicators import OrderBlock, FVG, WAE\nob = OrderBlock()\ndata_with_ob = ob.calculate(data, use_wicks=True)\n```\n\n#### New Pattern Indicators (v2.0.2)\n- **Fair Value Gap (FVG)**: Identifies price imbalance areas\n- **Order Block**: Detects institutional order zones\n- **Waddah Attar Explosion (WAE)**: Strong trend and breakout detection\n\n## \ud83c\udfd7\ufe0f Examples\n\nThe `examples/` directory contains comprehensive async examples:\n\n### Core Functionality\n- **00_trading_suite_demo.py** - Complete TradingSuite demonstration\n- **01_basic_client_connection.py** - Async authentication and basic operations\n- **02_order_management.py** - Async order placement and management\n- **03_position_management.py** - Async position tracking and P&L\n- **04_realtime_data.py** - Real-time async data streaming\n\n### Advanced Features\n- **05_orderbook_analysis.py** - Async market depth analysis\n- **06_advanced_orderbook.py** - Advanced orderbook analytics\n- **06_multi_timeframe_strategy.py** - Async multi-timeframe trading\n- **07_technical_indicators.py** - Using indicators with async data\n- **08_order_and_position_tracking.py** - Integrated async monitoring\n- **09_get_check_available_instruments.py** - Interactive async instrument search\n\n### Multi-Instrument Trading (NEW in v3.5.0)\n- **26_multi_instrument_trading.py** - Complete multi-instrument trading demo\n- **Portfolio management** - Risk management across multiple instruments\n- **Pairs trading** - ES vs MNQ spread analysis and correlation strategies\n- **Cross-market analysis** - Commodities, indices, and currency futures\n\n### Event System & Data Access\n- **10_unified_event_system.py** - Event-driven trading with EventBus\n- **11_simplified_data_access.py** - Simplified data access patterns\n- **12_simplified_multi_timeframe.py** - Multi-timeframe analysis\n- **12_simplified_strategy.py** - Simplified strategy using auto-initialization\n\n### Risk Management & Order Lifecycle\n- **13_enhanced_models.py** - Enhanced data models demonstration\n- **15_order_lifecycle_tracking.py** - Complete order lifecycle monitoring\n- **15_risk_management.py** - Risk management features\n- **16_managed_trades.py** - ManagedTrade context manager usage\n- **16_join_orders.py** - Advanced order joining techniques\n\n## \ud83d\udd27 Configuration\n\n### TradingSuiteConfig Options\n\nUse parameters in TradingSuite.create()\n\n### Performance Tuning\n\nConfigure caching and memory limits:\n```python\n# In OrderBook\norderbook = OrderBook(\n    instrument=\"ES\",\n    max_trades=10000,  # Trade history limit\n    max_depth_entries=1000,  # Depth per side\n    cache_ttl=300  # 5 minutes\n)\n\n# In ProjectXRealtimeDataManager (integrated with TradingSuite)\n# Data manager is configured via DataManagerConfig\nfrom project_x_py.realtime_data_manager.types import DataManagerConfig\n\nconfig = DataManagerConfig(\n    max_bars_per_timeframe=1000,\n    enable_mmap_overflow=True,\n    enable_dynamic_limits=True\n)\n```\n\n## \ud83d\udd0d Error Handling & Logging (v2.0.5+)\n\n### Structured Error Handling\n\nAll async operations use typed exceptions with automatic retry and logging:\n\n```python\nfrom project_x_py.exceptions import (\n    ProjectXAuthenticationError,\n    ProjectXOrderError,\n    ProjectXRateLimitError\n)\nfrom project_x_py.utils import configure_sdk_logging\n\n# Configure logging for production\nconfigure_sdk_logging(\n    level=logging.INFO,\n    format_json=True,  # JSON logs for production\n    log_file=\"/var/log/projectx/trading.log\"\n)\n\ntry:\n    async with ProjectX.from_env() as client:\n        await client.authenticate()  # Automatic retry on network errors\nexcept ProjectXAuthenticationError as e:\n    # Structured error with context\n    print(f\"Authentication failed: {e}\")\nexcept ProjectXRateLimitError as e:\n    # Automatic backoff already attempted\n    print(f\"Rate limit exceeded: {e}\")\n```\n\n### Error Handling Decorators\n\nThe SDK uses decorators for consistent error handling:\n\n```python\n# All API methods have built-in error handling\n@handle_errors(\"place order\")\n@retry_on_network_error(max_attempts=3)\n@validate_response(required_fields=[\"orderId\"])\nasync def place_order(self, ...):\n    # Method implementation\n```\n\n## \ud83d\udd27 Troubleshooting\n\n### Common Issues\n\n#### Authentication Issues\n```python\n# Error: \"PROJECT_X_API_KEY environment variable is required\"\n# Solution: Set environment variables before running\nexport PROJECT_X_API_KEY=\"your_api_key\"\nexport PROJECT_X_USERNAME=\"your_username\"\n\n# Or use config file at ~/.config/projectx/config.json\n```\n\n#### Instrument Not Found\n```python\n# Error: \"Instrument MNQ not found\"\n# Solution: Verify instrument symbol is correct\n# Common symbols: \"MNQ\", \"MES\", \"MGC\", \"ES\", \"NQ\"\n```\n\n#### Connection Timeouts\n```python\n# The TradingSuite handles connections automatically\n# If you need custom timeout handling:\ntry:\n    suite = await TradingSuite.create(\n        \"MNQ\",\n        timeout=30  # Custom timeout in seconds\n    )\nexcept Exception as e:\n    print(f\"Connection failed: {e}\")\n```\n\n#### Memory Issues with Long-Running Strategies\n```python\n# The suite automatically manages memory, but for long-running strategies:\n# 1. Use reasonable initial_days (3-7 is usually sufficient)\n# 2. The data manager automatically maintains sliding windows\n# 3. OrderBook has built-in memory limits\n```\n\n#### Rate Limiting\n```python\n# The SDK handles rate limiting automatically, but if you encounter issues:\n# 1. Reduce concurrent API calls\n# 2. Add delays between operations\n# 3. Use batch operations where available\n```\n\n## \ud83d\udccc Versioning Policy\n\nAs of v3.1.1, this project follows strict [Semantic Versioning](https://semver.org/):\n\n- **PATCH** (x.x.N): Bug fixes only, no API changes\n- **MINOR** (x.N.x): New features, backward compatible, deprecation warnings added\n- **MAJOR** (N.x.x): Breaking changes allowed, deprecated features removed\n\n### Deprecation Policy\n- Features marked as deprecated will include clear migration instructions\n- Deprecated features maintained for at least 2 minor versions\n- Removal only occurs in major version releases\n\n## \ud83e\udd1d Contributing\n\nWe welcome contributions! Please see [CONTRIBUTING.md](CONTRIBUTING.md) for guidelines.\n\n### Development Setup\n```bash\n# Clone repository\ngit clone https://github.com/yourusername/project-x-py.git\ncd project-x-py\n\n# Install with dev dependencies\nuv sync\n\n# Run tests\nuv run pytest\n\n# Format code\nuv run ruff format .\n\n# Lint\nuv run ruff check .\n```\n\n## \ud83d\udcc4 License\n\nThis project is licensed under the MIT License - see [LICENSE](LICENSE) file for details.\n\n## \ud83d\udd17 Resources\n\n- [ProjectX Platform](https://www.projectx.com/)\n- [API Documentation](https://texascoding.github.io/project-x-py/)\n- [GitHub Repository](https://github.com/TexasCoding/project-x-py)\n- [PyPI Package](https://pypi.org/project/project-x-py/)\n\n## \u26a0\ufe0f Disclaimer\n\nThis SDK is for educational and development purposes. Trading futures involves substantial risk of loss and is not suitable for all investors. Past performance is not indicative of future results. Always test your strategies thoroughly before using real funds.\n",
    "bugtrack_url": null,
    "license": "MIT",
    "summary": "High-performance Python SDK for futures trading with real-time WebSocket data, technical indicators, order management, and market depth analysis",
    "version": "3.5.7",
    "project_urls": {
        "Bug Tracker": "https://github.com/TexasCoding/project-x-py/issues",
        "Changelog": "https://github.com/TexasCoding/project-x-py/blob/main/CHANGELOG.md",
        "Documentation": "https://texascoding.github.io/project-x-py/",
        "Homepage": "https://github.com/TexasCoding/project-x-py",
        "Repository": "https://github.com/TexasCoding/project-x-py.git"
    },
    "split_keywords": [
        "api-client",
        " financial-data",
        " futures",
        " market-data",
        " projectx",
        " real-time-data",
        " topstepx",
        " trading"
    ],
    "urls": [
        {
            "comment_text": null,
            "digests": {
                "blake2b_256": "97037bd4a9f191ac9d1968924a08ee407db2d8654420b2d09698bf5a033109ee",
                "md5": "21bdddb1f72d92dbb2c3ff031a52c1cf",
                "sha256": "7bfc008eeb95a8c77b981ab4a51fbf31c93f3cd6f05e01f5453ec3a48d0505ad"
            },
            "downloads": -1,
            "filename": "project_x_py-3.5.7-py3-none-any.whl",
            "has_sig": false,
            "md5_digest": "21bdddb1f72d92dbb2c3ff031a52c1cf",
            "packagetype": "bdist_wheel",
            "python_version": "py3",
            "requires_python": ">=3.12",
            "size": 563366,
            "upload_time": "2025-09-02T03:32:57",
            "upload_time_iso_8601": "2025-09-02T03:32:57.340061Z",
            "url": "https://files.pythonhosted.org/packages/97/03/7bd4a9f191ac9d1968924a08ee407db2d8654420b2d09698bf5a033109ee/project_x_py-3.5.7-py3-none-any.whl",
            "yanked": false,
            "yanked_reason": null
        },
        {
            "comment_text": null,
            "digests": {
                "blake2b_256": "07d400a33a927baa5edb0cb1e99872a39eedc71fa5d51c25fc033c6024b7aba3",
                "md5": "6aec6d8bb7016b8532455afa46f3a8f1",
                "sha256": "119038adf96471d6ef9a0a47f8f80f1a8ace26886d505fdc4d6e41f8d52c243a"
            },
            "downloads": -1,
            "filename": "project_x_py-3.5.7.tar.gz",
            "has_sig": false,
            "md5_digest": "6aec6d8bb7016b8532455afa46f3a8f1",
            "packagetype": "sdist",
            "python_version": "source",
            "requires_python": ">=3.12",
            "size": 1102452,
            "upload_time": "2025-09-02T03:32:58",
            "upload_time_iso_8601": "2025-09-02T03:32:58.955042Z",
            "url": "https://files.pythonhosted.org/packages/07/d4/00a33a927baa5edb0cb1e99872a39eedc71fa5d51c25fc033c6024b7aba3/project_x_py-3.5.7.tar.gz",
            "yanked": false,
            "yanked_reason": null
        }
    ],
    "upload_time": "2025-09-02 03:32:58",
    "github": true,
    "gitlab": false,
    "bitbucket": false,
    "codeberg": false,
    "github_user": "TexasCoding",
    "github_project": "project-x-py",
    "travis_ci": false,
    "coveralls": false,
    "github_actions": true,
    "lcname": "project-x-py"
}
        
Elapsed time: 1.05475s