# ProjectX Python SDK
[](https://python.org)
[](LICENSE)
[](https://github.com/psf/black)
[](#performance-optimizations)
[](#async-architecture)
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.1.11 - Stable Production Release
**Latest Version**: v3.1.11 - Fixed ManagedTrade market price fetching for risk-managed trades. See [CHANGELOG.md](CHANGELOG.md) for full release history.
### 📦 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
- **58+ Technical Indicators**: Full TA-Lib compatibility with Polars optimization including new pattern indicators
- **Level 2 OrderBook**: Depth analysis, iceberg detection, market microstructure
- **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, and Waddah Attar Explosion indicators
- **Enterprise Error Handling**: Production-ready error handling with decorators and structured logging
- **Comprehensive Testing**: High test coverage with async-safe testing patterns
## 📦 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}\")
await suite.disconnect()
if __name__ == \"__main__\":
asyncio.run(main())
```
### Trading Suite (NEW in v3.0+)
The easiest way to get started with a complete trading setup:
```python
import asyncio
from project_x_py import TradingSuite, EventType
async def main():
suite = await TradingSuite.create(
\"MNQ\",
timeframes=[\"5min\", \"15min\", \"1hr\"],
features=[\"orderbook\", \"risk_manager\"]
)
# Register event handlers
async def on_new_bar(event):
# Access bar data directly from event
print(f\"New {event.data['timeframe']} bar: {event.data['data']['close']}\")
async def on_trade(event):
print(f\"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)
# Access components
data = await suite.data.get_data(\"5min\")
orderbook = suite.orderbook # Available since feature enabled
order_manager = suite.orders
position_manager = suite.positions
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
print(f\"Price: ${tick_data['price']}\")
async def main():
suite = await TradingSuite.create(\"MNQ\")
# Register tick callback
await suite.data.add_callback(\"tick\", on_tick)
current_price = await suite.data.get_current_price()
response = await suite.orders.place_bracket_order(
contract_id=suite.instrument_id,
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()
if __name__ == \"__main__\":
asyncio.run(main())
```
## ⚡ 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"
}
```
### 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 (when enabled):
```python
# Enable risk manager in features
suite = await TradingSuite.create("MNQ", features=["risk_manager"])
# 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
)
```
### Technical Indicators
All 58+ 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
### 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 RealtimeDataManager
data_manager = RealtimeDataManager(
instrument="NQ",
max_bars_per_timeframe=1000,
tick_buffer_size=1000
)
```
## 🔍 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://documenter.getpostman.com/view/24500417/2s9YRCXrKF)
- [GitHub Repository](https://github.com/yourusername/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/29/d1/d8e0d2db62f976c5bc835b7a37074ebe04991d166753be0b080aa624bdf0/project_x_py-3.1.12.tar.gz",
"platform": null,
"description": "# ProjectX Python SDK\n\n[](https://python.org)\n[](LICENSE)\n[](https://github.com/psf/black)\n[](#performance-optimizations)\n[](#async-architecture)\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.1.11 - Stable Production Release\n\n**Latest Version**: v3.1.11 - Fixed ManagedTrade market price fetching for risk-managed trades. See [CHANGELOG.md](CHANGELOG.md) for full release history.\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- **58+ Technical Indicators**: Full TA-Lib compatibility with Polars optimization including new pattern indicators\n- **Level 2 OrderBook**: Depth analysis, iceberg detection, market microstructure\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, and Waddah Attar Explosion indicators\n- **Enterprise Error Handling**: Production-ready error handling with decorators and structured logging\n- **Comprehensive Testing**: High test coverage with async-safe testing patterns\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 await suite.disconnect()\n\nif __name__ == \\\"__main__\\\":\n asyncio.run(main())\n```\n\n### Trading Suite (NEW in v3.0+)\n\nThe easiest way to get started with a complete trading setup:\n\n```python\nimport asyncio\nfrom project_x_py import TradingSuite, EventType\n\nasync def main():\n suite = await TradingSuite.create(\n \\\"MNQ\\\",\n timeframes=[\\\"5min\\\", \\\"15min\\\", \\\"1hr\\\"],\n features=[\\\"orderbook\\\", \\\"risk_manager\\\"]\n )\n \n # Register event handlers\n async def on_new_bar(event):\n # Access bar data directly from event\n print(f\\\"New {event.data['timeframe']} bar: {event.data['data']['close']}\\\")\n \n async def on_trade(event):\n print(f\\\"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 # Access components\n data = await suite.data.get_data(\\\"5min\\\")\n orderbook = suite.orderbook # Available since feature enabled\n order_manager = suite.orders\n position_manager = suite.positions\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 print(f\\\"Price: ${tick_data['price']}\\\")\n\nasync def main():\n suite = await TradingSuite.create(\\\"MNQ\\\")\n \n # Register tick callback\n await suite.data.add_callback(\\\"tick\\\", on_tick)\n \n current_price = await suite.data.get_current_price()\n \n response = await suite.orders.place_bracket_order(\n contract_id=suite.instrument_id,\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\nif __name__ == \\\"__main__\\\":\n asyncio.run(main())\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### 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 (when enabled):\n```python\n# Enable risk manager in features\nsuite = await TradingSuite.create(\"MNQ\", features=[\"risk_manager\"])\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### Technical Indicators\n\nAll 58+ 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### 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 RealtimeDataManager\ndata_manager = RealtimeDataManager(\n instrument=\"NQ\",\n max_bars_per_timeframe=1000,\n tick_buffer_size=1000\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://documenter.getpostman.com/view/24500417/2s9YRCXrKF)\n- [GitHub Repository](https://github.com/yourusername/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.",
"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.1.12",
"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://project-x-py.readthedocs.io/en/latest/",
"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": "5c99f46f4fa81557b8d8de43cbd13d158dcafb6d1977c2b9d68179c9154806ef",
"md5": "01c610f73d459e10a39f253b93c62a0b",
"sha256": "5d6ca8f0bc2266bfb7156f4b00cc12b46d3b69cd3aae18949c39cb5d3c90736c"
},
"downloads": -1,
"filename": "project_x_py-3.1.12-py3-none-any.whl",
"has_sig": false,
"md5_digest": "01c610f73d459e10a39f253b93c62a0b",
"packagetype": "bdist_wheel",
"python_version": "py3",
"requires_python": ">=3.12",
"size": 353084,
"upload_time": "2025-08-15T00:26:23",
"upload_time_iso_8601": "2025-08-15T00:26:23.697841Z",
"url": "https://files.pythonhosted.org/packages/5c/99/f46f4fa81557b8d8de43cbd13d158dcafb6d1977c2b9d68179c9154806ef/project_x_py-3.1.12-py3-none-any.whl",
"yanked": false,
"yanked_reason": null
},
{
"comment_text": null,
"digests": {
"blake2b_256": "29d1d8e0d2db62f976c5bc835b7a37074ebe04991d166753be0b080aa624bdf0",
"md5": "a9b62e4c4dc577619fd43138f58298f1",
"sha256": "dc49dea5f10e0d0148f02788bff93085f0830ff3121819b38bbf4d20ba56131a"
},
"downloads": -1,
"filename": "project_x_py-3.1.12.tar.gz",
"has_sig": false,
"md5_digest": "a9b62e4c4dc577619fd43138f58298f1",
"packagetype": "sdist",
"python_version": "source",
"requires_python": ">=3.12",
"size": 393264,
"upload_time": "2025-08-15T00:26:25",
"upload_time_iso_8601": "2025-08-15T00:26:25.489765Z",
"url": "https://files.pythonhosted.org/packages/29/d1/d8e0d2db62f976c5bc835b7a37074ebe04991d166753be0b080aa624bdf0/project_x_py-3.1.12.tar.gz",
"yanked": false,
"yanked_reason": null
}
],
"upload_time": "2025-08-15 00:26:25",
"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"
}