diff --git a/src/project_x_py/client/auth.py b/src/project_x_py/client/auth.py index f152d28..ac72d74 100644 --- a/src/project_x_py/client/auth.py +++ b/src/project_x_py/client/auth.py @@ -1,4 +1,42 @@ -"""Authentication and token management for ProjectX client.""" +""" +Authentication and account management for ProjectX async clients. + +Overview: + This module implements the complete authentication lifecycle for ProjectX, including + secure login using API key and username, JWT token handling, account selection, and + robust error management. It automatically parses and refreshes authentication tokens, + supports multiple accounts, and ensures session validity throughout async API usage. + Integrated as a mixin, it enables seamless auth orchestration for all async clients. + +Key Features: + - Full async login flow with API key and user credentials + - JWT token parsing, expiry extraction, and proactive refresh logic + - Multi-account discovery and selection (by name or default) + - Automatic authentication refresh on token expiry or invalidation + - Error management with descriptive exceptions for auth failures + - Utility methods for listing and validating available accounts + +Example Usage: + ```python + import asyncio + from project_x_py import ProjectX + + async def main(): + async with ProjectX.from_env() as client: + await client.authenticate() + print(f"Authenticated as {client.account_info.username}") + accounts = await client.list_accounts() + for acc in accounts: + print(acc.name, acc.balance) + + asyncio.run(main()) + ``` + +See Also: + - `project_x_py.client.base.ProjectXBase` (core client with mixins) + - `project_x_py.client.http.HttpMixin` (for HTTP request integration) + - `project_x_py.client.trading.TradingMixin` (trading operations requiring auth) +""" import base64 import datetime diff --git a/src/project_x_py/client/base.py b/src/project_x_py/client/base.py index 84b09cc..d384694 100644 --- a/src/project_x_py/client/base.py +++ b/src/project_x_py/client/base.py @@ -1,4 +1,41 @@ -"""Base client class with lifecycle methods for ProjectX.""" +""" +ProjectX async base client: context-managed lifecycle, mixin composition, and helpers. + +Overview: + Defines the foundational async client for ProjectX by combining all core functional + mixins (auth, HTTP, cache, market data, trading) into a single context-managed class. + Supports async context management for safe resource cleanup, flexible instantiation from + environment or config file, and exposes helper classmethods to streamline credential and + configuration handling in both development and production setups. + +Key Features: + - Composes all client-side mixins (auth, HTTP, cache, data, trading) + - Async context manager for safe resource initialization and teardown + - Classmethod constructors: `from_env` and `from_config_file` + - Centralized client/session token and account info access + - Integrated API rate limiting and configuration + - Suitable as a base for advanced SDK extensibility + +Example Usage: + ```python + import asyncio + from project_x_py import ProjectX + + async def main(): + async with ProjectX.from_env() as client: + await client.authenticate() + print(client.get_account_info()) + + asyncio.run(main()) + ``` + +See Also: + - `project_x_py.client.auth.AuthenticationMixin` + - `project_x_py.client.http.HttpMixin` + - `project_x_py.client.cache.CacheMixin` + - `project_x_py.client.market_data.MarketDataMixin` + - `project_x_py.client.trading.TradingMixin` +""" import logging import os diff --git a/src/project_x_py/client/cache.py b/src/project_x_py/client/cache.py index 14a1058..cd9e181 100644 --- a/src/project_x_py/client/cache.py +++ b/src/project_x_py/client/cache.py @@ -1,4 +1,34 @@ -"""Caching functionality for ProjectX client.""" +""" +In-memory caching for instrument and market data with TTL and performance tracking. + +Overview: + Provides efficient, per-symbol in-memory caching for instrument metadata and historical + market data. Uses time-based TTL (time-to-live) for automatic expiry and memory cleanup, + reducing API load and improving performance for frequently accessed symbols. Includes + cache hit counters and periodic cleanup for resource optimization within async clients. + +Key Features: + - Fast cache for instrument lookups (symbol → instrument) + - Market data caching for historical bar queries (string key → Polars DataFrame) + - Configurable TTL (default 5 minutes) to automatically expire stale data + - Performance metrics: cache hit count and cleanup timing + - Async cache cleanup and garbage collection for large workloads + - Manual cache clearing utilities + +Example Usage: + ```python + # Used internally by ProjectX; typical use is transparent: + instrument = await client.get_instrument("MNQ") + # On repeated calls, instrument is served from cache if not expired. + cached = client.get_cached_instrument("MNQ") + client.clear_all_caches() + ``` + +See Also: + - `project_x_py.client.market_data.MarketDataMixin` + - `project_x_py.client.base.ProjectXBase` + - `project_x_py.client.http.HttpMixin` +""" import gc import logging diff --git a/src/project_x_py/client/http.py b/src/project_x_py/client/http.py index de3797b..9a1e307 100644 --- a/src/project_x_py/client/http.py +++ b/src/project_x_py/client/http.py @@ -1,4 +1,39 @@ -"""HTTP client and request handling for ProjectX client.""" +""" +Async HTTP/2 client, rate-limiting, and robust error handling for ProjectX SDK. + +Overview: + Implements the async HTTP/2 client logic for ProjectX API access, including connection + pooling, automatic retry on transient errors, and adaptive rate limiting. All API calls + are decorated for rate control and network resilience, with detailed error mapping for + 4xx and 5xx responses. Integrates with authentication for seamless token refresh and + propagates network/runtime errors as SDK-specific exceptions. + +Key Features: + - HTTP/2 async client with connection pooling (via httpx) + - Decorators for automatic rate limiting and network retry logic + - Error mapping: raises precise exceptions for 4xx/5xx responses + - Automatic JWT token refresh on 401/expired session + - API call logging, health status, and statistics + - Centralized request/response handling for all mixins + +Example Usage: + ```python + import asyncio + from project_x_py import ProjectX + + async def main(): + async with ProjectX.from_env() as client: + status = await client.get_health_status() + print(status["api_status"], status["client_stats"]["api_calls"]) + + asyncio.run(main()) + ``` + +See Also: + - `project_x_py.client.base.ProjectXBase` + - `project_x_py.client.auth.AuthenticationMixin` + - `project_x_py.client.cache.CacheMixin` +""" import time from typing import TYPE_CHECKING, Any diff --git a/src/project_x_py/client/market_data.py b/src/project_x_py/client/market_data.py index f19bcf9..4c8a34a 100644 --- a/src/project_x_py/client/market_data.py +++ b/src/project_x_py/client/market_data.py @@ -1,4 +1,40 @@ -"""Market data operations for ProjectX client.""" +""" +Async instrument search, selection, and historical bar data for ProjectX clients. + +Overview: + Provides async methods for instrument discovery, smart contract selection, and retrieval + of historical OHLCV bar data, with Polars DataFrame output for high-performance analysis. + Integrates in-memory caching for both instrument and bar queries, minimizing redundant + API calls and ensuring data consistency. Designed to support trading and analytics flows + requiring timely and accurate market data. + +Key Features: + - Symbol/name instrument search with live/active filtering + - Sophisticated contract selection logic (front month, micro, etc.) + - Historical bar data retrieval (OHLCV) with timezone handling + - Transparent, per-query caching for both instrument and bars + - Data returned as Polars DataFrame (timestamp, open, high, low, close, volume) + - Utilities for cache management and periodic cleanup + +Example Usage: + ```python + import asyncio + from project_x_py import ProjectX + + async def main(): + async with ProjectX.from_env() as client: + instrument = await client.get_instrument("ES") + bars = await client.get_bars("ES", days=3, interval=15) + print(bars.head()) + + asyncio.run(main()) + ``` + +See Also: + - `project_x_py.client.cache.CacheMixin` + - `project_x_py.client.base.ProjectXBase` + - `project_x_py.client.trading.TradingMixin` +""" import datetime import re diff --git a/src/project_x_py/client/trading.py b/src/project_x_py/client/trading.py index 07fbc8b..59ecbe6 100644 --- a/src/project_x_py/client/trading.py +++ b/src/project_x_py/client/trading.py @@ -1,4 +1,40 @@ -"""Trading operations for ProjectX client.""" +""" +Async trading queries: positions and trade history for ProjectX accounts. + +Overview: + Supplies async methods for querying open positions and executed trades for the currently + authenticated account. Integrates tightly with the authentication/session lifecycle and + other mixins, enabling streamlined access to P&L, trade analysis, and reporting data. + All queries require a valid session and leverage ProjectX's unified API request logic. + +Key Features: + - Query current open positions for the selected account + - Search historical trades with flexible date range and contract filters + - Async error handling and robust integration with authentication + - Typed results as Position and Trade model objects for analysis/reporting + - Designed for use in trading bots, dashboards, and research scripts + +Example Usage: + ```python + import asyncio + from project_x_py import ProjectX + + async def main(): + async with ProjectX.from_env() as client: + await client.authenticate() + positions = await client.get_positions() + trades = await client.search_trades(limit=10) + print([p.symbol for p in positions]) + print([t.contractId for t in trades]) + + asyncio.run(main()) + ``` + +See Also: + - `project_x_py.client.auth.AuthenticationMixin` + - `project_x_py.client.base.ProjectXBase` + - `project_x_py.client.market_data.MarketDataMixin` +""" import datetime import logging diff --git a/src/project_x_py/indicators/__init__.py b/src/project_x_py/indicators/__init__.py index af8c7af..a3aa4d3 100644 --- a/src/project_x_py/indicators/__init__.py +++ b/src/project_x_py/indicators/__init__.py @@ -4,19 +4,41 @@ Author: TexasCoding Date: June 2025 -A comprehensive technical analysis library similar to TA-Lib, built on Polars DataFrames. -Provides both class-based and function-based interfaces for technical indicators. - -Example usage: +Overview: + ProjectX Indicators provides a comprehensive, extensible technical analysis library + similar to TA-Lib, built on Polars DataFrames. It offers both class-based and + function-based interfaces for over 60 technical indicators, with seamless integration + for vectorized backtesting and strategy development in ProjectX and beyond. + +Key Features: + - Wide range of indicators: trend/overlap, momentum, volatility, volume, and patterns + - Class-based and TA-Lib-style function interface for flexible usage + - All indicators operate on Polars DataFrames for speed and modern analytics + - Utilities for indicator discovery, grouping, and docstring access + - Clean API and naming convention for easy scripting and research + +Example Usage: + ```python # Class-based interface - >>> from project_x_py.indicators import RSI, SMA - >>> rsi = RSI() - >>> data_with_rsi = rsi.calculate(ohlcv_data, period=14) + from project_x_py.indicators import RSI, SMA + rsi = RSI() + data_with_rsi = rsi.calculate(ohlcv_data, period=14) # Function-based interface (TA-Lib style) - >>> from project_x_py.indicators import calculate_rsi, calculate_sma - >>> data_with_rsi = calculate_rsi(ohlcv_data, period=14) - >>> data_with_sma = calculate_sma(ohlcv_data, period=20) + from project_x_py.indicators import calculate_rsi, calculate_sma + data_with_rsi = calculate_rsi(ohlcv_data, period=14) + data_with_sma = calculate_sma(ohlcv_data, period=20) + ``` + +See Also: + - `project_x_py.indicators.base` (abstract base classes/utilities) + - `project_x_py.indicators.momentum` + - `project_x_py.indicators.overlap` + - `project_x_py.indicators.volume` + - `project_x_py.indicators.volatility` + - `project_x_py.indicators.order_block` + - `project_x_py.indicators.fvg` + - `project_x_py.indicators.waddah_attar` """ import polars as pl diff --git a/src/project_x_py/indicators/base.py b/src/project_x_py/indicators/base.py index a9c223d..0f7024c 100644 --- a/src/project_x_py/indicators/base.py +++ b/src/project_x_py/indicators/base.py @@ -4,7 +4,35 @@ Author: TexasCoding Date: June 2025 -Base classes and common functionality for technical indicators. +Overview: + Provides abstract base classes and shared validation/utilities for all ProjectX + indicator modules. Encapsulates error handling, cache logic, and call semantics + for consistent and efficient indicator development. All custom indicators should + inherit from these classes for uniformity and extensibility. + +Key Features: + - `BaseIndicator` with parameter validation, data checks, and result caching + - Specialized subclasses: OverlapIndicator, MomentumIndicator, VolatilityIndicator, + VolumeIndicator + - Utility functions for safe division, rolling sums, and EMA alpha calculation + - Standardized exception (`IndicatorError`) for all indicator errors + +Example Usage: + ```python + from project_x_py.indicators.base import BaseIndicator + + class MyCustomIndicator(BaseIndicator): + def calculate(self, data, period=10): + self.validate_data(data, ["close"]) + self.validate_period(period) + # ... custom calculation ... + ``` + +See Also: + - `project_x_py.indicators.momentum.MomentumIndicator` + - `project_x_py.indicators.overlap.OverlapIndicator` + - `project_x_py.indicators.volatility.VolatilityIndicator` + - `project_x_py.indicators.volume.VolumeIndicator` """ import hashlib diff --git a/src/project_x_py/indicators/fvg.py b/src/project_x_py/indicators/fvg.py index 784107c..6d712e9 100644 --- a/src/project_x_py/indicators/fvg.py +++ b/src/project_x_py/indicators/fvg.py @@ -4,8 +4,28 @@ Author: TexasCoding Date: August 2025 -Fair Value Gap indicator identifies imbalance areas in price action where there is little -to no trading activity, which can act as support/resistance zones. +Overview: + Implements the Fair Value Gap (FVG) indicator for identifying price imbalances + and potential support/resistance zones. Detects gaps in price action with + optional mitigation logic, helping traders spot areas likely to be revisited. + +Key Features: + - Identifies bullish/bearish fair value gaps from OHLC data + - Supports configurable gap size, mitigation threshold, and custom columns + - Returns gap boundary, size, and mitigation status for each bar + - Callable as a class or via TA-Lib-style convenience function + +Example Usage: + ```python + from project_x_py.indicators import FVG + fvg = FVG() + data_with_fvg = fvg.calculate(ohlcv_data, min_gap_size=0.001) + gaps = data_with_fvg.filter(pl.col("fvg_bullish")) + ``` + +See Also: + - `project_x_py.indicators.order_block` + - `project_x_py.indicators.base.BaseIndicator` """ from typing import Any diff --git a/src/project_x_py/indicators/momentum.py b/src/project_x_py/indicators/momentum.py index fc56f7c..79e0907 100644 --- a/src/project_x_py/indicators/momentum.py +++ b/src/project_x_py/indicators/momentum.py @@ -4,8 +4,29 @@ Author: TexasCoding Date: June 2025 -Momentum indicators measure the rate of change in price movements, -helping identify overbought/oversold conditions and trend strength. +Overview: + Provides a suite of momentum indicators for ProjectX, covering oscillators and + trend-following calculations. Includes both class-based and TA-Lib-style + function interfaces for RSI, MACD, Stochastic, CCI, and many more, all operating + on Polars DataFrames. + +Key Features: + - Relative Strength Index (RSI), MACD, Stochastic, Williams %R, CCI, ROC, MOM, and more + - Directional movement, Aroon, Ultimate Oscillator, and Chande Momentum Oscillator + - All indicators vectorized for performance and chained analysis + - Flexible configuration: periods, smoothing, columns, and more + - Convenient function interface for script-style use + +Example Usage: + ```python + from project_x_py.indicators import calculate_rsi + data_with_rsi = calculate_rsi(ohlcv_data, period=14) + ``` + +See Also: + - `project_x_py.indicators.base.MomentumIndicator` + - `project_x_py.indicators.overlap` + - `project_x_py.indicators.volume` """ from typing import Any diff --git a/src/project_x_py/indicators/order_block.py b/src/project_x_py/indicators/order_block.py index 44ad52c..48a982e 100644 --- a/src/project_x_py/indicators/order_block.py +++ b/src/project_x_py/indicators/order_block.py @@ -4,8 +4,28 @@ Author: TexasCoding Date: August 2025 -Order Block indicator identifies institutional order areas based on price action patterns. -These are supply and demand zones where large market participants likely have pending orders. +Overview: + Implements the Order Block indicator, which detects likely institutional supply/demand + zones from price action and volume. Useful for identifying areas where large orders + may cluster, acting as future support or resistance. + +Key Features: + - Detects bullish and bearish order blocks based on candle/volume logic + - Configurable volume threshold, mitigation, and lookback + - Outputs block boundaries, strength, and mitigation status per bar + - Class and function interfaces for flexible use + +Example Usage: + ```python + from project_x_py.indicators import OrderBlock + ob = OrderBlock() + data_with_ob = ob.calculate(ohlcv_data, min_volume_percentile=70) + ``` + +See Also: + - `project_x_py.indicators.fvg` + - `project_x_py.indicators.base.BaseIndicator` + - `project_x_py.indicators.volume` """ from typing import Any diff --git a/src/project_x_py/indicators/overlap.py b/src/project_x_py/indicators/overlap.py index 7ff99e5..ba02211 100644 --- a/src/project_x_py/indicators/overlap.py +++ b/src/project_x_py/indicators/overlap.py @@ -4,8 +4,29 @@ Author: TexasCoding Date: June 2025 -Overlap study indicators are often displaced by default and superimposed -over the main price chart. +Overview: + Contains all trend-following (overlap) indicators for ProjectX, including + moving averages, Bollinger Bands, and adaptive smoothing. Each indicator + provides a class interface and function-style convenience wrapper, and + all outputs are Polars DataFrames for easy chaining. + +Key Features: + - SMA, EMA, DEMA, TEMA, WMA, TRIMA, KAMA, and other moving averages + - Bollinger Bands, Parabolic SAR, Hilbert Transform, and more + - Selectable MA type for generic moving average computations + - Rolling, exponential, and adaptive implementations + - All indicators are vectorized and support chaining + +Example Usage: + ```python + from project_x_py.indicators import calculate_sma + data_with_sma = calculate_sma(ohlcv_data, period=20) + ``` + +See Also: + - `project_x_py.indicators.base.OverlapIndicator` + - `project_x_py.indicators.momentum` + - `project_x_py.indicators.volatility` """ from typing import Any diff --git a/src/project_x_py/indicators/volatility.py b/src/project_x_py/indicators/volatility.py index 8c6156f..964980d 100644 --- a/src/project_x_py/indicators/volatility.py +++ b/src/project_x_py/indicators/volatility.py @@ -4,8 +4,28 @@ Author: TexasCoding Date: June 2025 -Volatility indicators measure the rate of price fluctuations, -helping traders understand market volatility and potential breakouts. +Overview: + Implements volatility-focused indicators for ProjectX, quantifying price range, + standard deviation, and directional movement. Designed for gauging market + turbulence, breakout potential, and risk in systematic strategies. + +Key Features: + - Average True Range (ATR), ADX, NATR, TRANGE, STDDEV, Ultimate Oscillator + - Wilder's smoothing, EMA, and rolling window variants + - All indicators operate on Polars DataFrames + - TA-Lib-style convenience functions for scripting/backtesting + - Can be chained with other indicator modules + +Example Usage: + ```python + from project_x_py.indicators import calculate_atr + data_with_atr = calculate_atr(ohlcv_data, period=14) + ``` + +See Also: + - `project_x_py.indicators.base.VolatilityIndicator` + - `project_x_py.indicators.overlap` + - `project_x_py.indicators.momentum` """ from typing import Any diff --git a/src/project_x_py/indicators/volume.py b/src/project_x_py/indicators/volume.py index 44289c1..fd3fccb 100644 --- a/src/project_x_py/indicators/volume.py +++ b/src/project_x_py/indicators/volume.py @@ -4,8 +4,27 @@ Author: TexasCoding Date: June 2025 -Volume indicators analyze trading volume to confirm price movements -and identify potential trend reversals or continuations. +Overview: + Implements volume-based indicators for ProjectX, allowing traders to confirm + trends, spot reversals, and analyze money flow. Includes both cumulative + and oscillator-style volume indicators operating on Polars DataFrames. + +Key Features: + - OBV, VWAP, Accumulation/Distribution (AD), AD Oscillator (ADOSC) + - Rolling, cumulative, and EMA-based volume analytics + - TA-Lib-style function interface for direct scripting + - Compatible with all other indicator modules + +Example Usage: + ```python + from project_x_py.indicators import calculate_vwap + data_with_vwap = calculate_vwap(ohlcv_data, period=20) + ``` + +See Also: + - `project_x_py.indicators.base.VolumeIndicator` + - `project_x_py.indicators.momentum` + - `project_x_py.indicators.overlap` """ from typing import Any diff --git a/src/project_x_py/indicators/waddah_attar.py b/src/project_x_py/indicators/waddah_attar.py index bffe2f8..f4e3736 100644 --- a/src/project_x_py/indicators/waddah_attar.py +++ b/src/project_x_py/indicators/waddah_attar.py @@ -4,8 +4,29 @@ Author: TexasCoding Date: August 2025 -Waddah Attar Explosion indicator is a volatility-based indicator that combines -MACD and Bollinger Bands to identify strong trends and potential breakouts. +Overview: + Implements the Waddah Attar Explosion (WAE) indicator for detecting strong + trends and breakout conditions. Combines MACD, Bollinger Bands, and ATR-based + dead zone logic to filter for high-momentum moves with volatility context. + +Key Features: + - Computes explosion line, trend, and dead zone from price/volatility data + - Configurable MACD/Bollinger/ATR parameters for fine-tuning + - Flags bullish/bearish breakouts above dead zone threshold + - Callable as a class or with TA-Lib-style convenience function + +Example Usage: + ```python + from project_x_py.indicators import WAE + wae = WAE() + data_with_wae = wae.calculate(ohlcv_data) + signals = data_with_wae.filter(pl.col("wae_explosion_above_dz")) + ``` + +See Also: + - `project_x_py.indicators.volatility` + - `project_x_py.indicators.base.BaseIndicator` + - `project_x_py.indicators.momentum` """ from typing import Any diff --git a/src/project_x_py/order_manager/__init__.py b/src/project_x_py/order_manager/__init__.py index 9448530..82e09fc 100644 --- a/src/project_x_py/order_manager/__init__.py +++ b/src/project_x_py/order_manager/__init__.py @@ -1,12 +1,36 @@ """ -Order Manager Module for ProjectX Trading Platform. - -This module provides comprehensive order management functionality including: -- Order placement (market, limit, stop, trailing stop) -- Order modification and cancellation -- Bracket order strategies -- Position-based order management -- Real-time order tracking and monitoring +Async order management for ProjectX trading. + +Overview: + This package provides the async OrderManager system for ProjectX, offering robust, + extensible order placement, modification, cancellation, tracking, and advanced + bracket/position management. Integrates with both API and real-time clients for + seamless trading workflows. + +Key Features: + - Unified async order placement (market, limit, stop, trailing, bracket) + - Modification/cancellation with tick-size alignment + - Position-based order and risk management + - Real-time tracking, event-driven callbacks, and statistics + - Modular design for strategy and bot development + +Example Usage: + ```python + from project_x_py import ProjectX + from project_x_py.order_manager import OrderManager + + async with ProjectX.from_env() as client: + om = OrderManager(client) + await om.place_market_order("MNQ", 0, 1) # Buy 1 contract at market + ``` + +See Also: + - `order_manager.core.OrderManager` + - `order_manager.bracket_orders` + - `order_manager.order_types` + - `order_manager.position_orders` + - `order_manager.tracking` + - `order_manager.utils` """ from project_x_py.order_manager.core import OrderManager diff --git a/src/project_x_py/order_manager/bracket_orders.py b/src/project_x_py/order_manager/bracket_orders.py index 265316f..d06dad9 100644 --- a/src/project_x_py/order_manager/bracket_orders.py +++ b/src/project_x_py/order_manager/bracket_orders.py @@ -1,4 +1,31 @@ -"""Bracket order functionality for complex order strategies.""" +""" +Async bracket order strategies for ProjectX. + +Overview: + Provides mixin logic for placing and managing bracket orders—sophisticated, three-legged + order strategies consisting of entry, stop loss, and take profit orders. Ensures risk + controls are established atomically and linked to positions for robust trade automation. + +Key Features: + - Place async bracket orders (entry, stop, target) as a single operation + - Price/side validation and position link management + - Automatic risk management: stops and targets managed with entry + - Integrates with core OrderManager and position tracking + +Example Usage: + ```python + # Assuming om is an instance of OrderManager + await om.place_bracket_order( + contract_id="MGC", side=0, size=1, + entry_price=2050.0, stop_loss_price=2040.0, take_profit_price=2070.0 + ) + ``` + +See Also: + - `order_manager.core.OrderManager` + - `order_manager.position_orders` + - `order_manager.order_types` +""" import logging from typing import TYPE_CHECKING diff --git a/src/project_x_py/order_manager/core.py b/src/project_x_py/order_manager/core.py index b7f9db2..8be0de1 100644 --- a/src/project_x_py/order_manager/core.py +++ b/src/project_x_py/order_manager/core.py @@ -1,8 +1,34 @@ """ -Core OrderManager class for comprehensive order operations. - -This module provides the main OrderManager class that handles all order-related -operations including placement, modification, cancellation, and tracking. +Async OrderManager core for ProjectX trading. + +Overview: + Contains the main OrderManager class, orchestrating all async order operations + (placement, modification, cancellation, tracking) and integrating mixins for + bracket, position, and order type strategies. Provides thread-safe, eventful, + and real-time capable order workflows for automated and manual trading. + +Key Features: + - Unified async API for order lifecycle (market, limit, stop, trailing, OCO) + - Bracket and position-based order strategies + - Real-time tracking, event-driven callbacks, and statistics + - Price alignment, concurrent safety, and health metrics + - Extensible for custom bots and strategy engines + +Example Usage: + ```python + from project_x_py import ProjectX + from project_x_py.order_manager import OrderManager + + async with ProjectX.from_env() as client: + om = OrderManager(client) + await om.place_limit_order("ES", 0, 1, 5000.0) + ``` + +See Also: + - `order_manager.bracket_orders` + - `order_manager.position_orders` + - `order_manager.order_types` + - `order_manager.tracking` """ import asyncio diff --git a/src/project_x_py/order_manager/order_types.py b/src/project_x_py/order_manager/order_types.py index bf235e8..eb28d8a 100644 --- a/src/project_x_py/order_manager/order_types.py +++ b/src/project_x_py/order_manager/order_types.py @@ -1,4 +1,29 @@ -"""Order placement methods for different order types.""" +""" +Async order type placement mixin for ProjectX. + +Overview: + Implements mixin methods for placing specific order types (market, limit, + stop, trailing stop) in the async OrderManager system. Encapsulates order-type + validation, parameter handling, and delegates to the unified underlying API. + +Key Features: + - Async placement of market, limit, stop, and trailing stop orders + - Standardized argument validation and contract handling + - Integrates with bracket and position order mixins + - Returns model-typed responses for downstream logic + +Example Usage: + ```python + # Assuming om is an instance of OrderManager + await om.place_limit_order("MES", 1, 2, 5000.0) + await om.place_market_order("MGC", 0, 1) + ``` + +See Also: + - `order_manager.core.OrderManager` + - `order_manager.bracket_orders` + - `order_manager.position_orders` +""" import logging from typing import TYPE_CHECKING diff --git a/src/project_x_py/order_manager/position_orders.py b/src/project_x_py/order_manager/position_orders.py index bb3d0bc..2f51339 100644 --- a/src/project_x_py/order_manager/position_orders.py +++ b/src/project_x_py/order_manager/position_orders.py @@ -1,4 +1,29 @@ -"""Position-related order management functionality.""" +""" +Async position-based order management for ProjectX. + +Overview: + Provides mixin logic for managing orders at the position level: closing open positions, + adding stop losses/take profits, and synchronizing/canceling related orders as position + size changes. Enables robust, risk-aware trading automations. + +Key Features: + - Async close, stop loss, and take profit for open positions + - Automatic order/position tracking and synchronization + - Bulk cancellation and modification of position-related orders + - Integrates with order callbacks and bracket strategies + +Example Usage: + ```python + # Assuming om is an instance of OrderManager + await om.close_position("MNQ") + await om.add_stop_loss("MNQ", stop_price=2030.0) + ``` + +See Also: + - `order_manager.core.OrderManager` + - `order_manager.bracket_orders` + - `order_manager.order_types` +""" import logging from typing import TYPE_CHECKING, Any diff --git a/src/project_x_py/order_manager/tracking.py b/src/project_x_py/order_manager/tracking.py index ac5be75..8560ffb 100644 --- a/src/project_x_py/order_manager/tracking.py +++ b/src/project_x_py/order_manager/tracking.py @@ -1,4 +1,30 @@ -"""Order tracking and real-time monitoring functionality.""" +""" +Async order tracking and real-time monitoring for ProjectX. + +Overview: + Implements mixin logic for tracking order status, maintaining local state and cache, + and handling real-time updates from websocket events. Supports callback registration + for fills/cancels, cache queries, and system health validation. + +Key Features: + - Real-time tracking via websocket/callbacks and local cache + - Order-to-position relationship mapping + - Async event/callback system for fills, cancels, rejections + - Cache clearing, health/status reporting, and metrics + - Integrates with OrderManager main class + +Example Usage: + ```python + # Assuming om is an instance of OrderManager + await om.initialize(realtime_client) + tracked = await om.get_tracked_order_status("12345") + ``` + +See Also: + - `order_manager.core.OrderManager` + - `order_manager.position_orders` + - `order_manager.utils` +""" import asyncio import logging diff --git a/src/project_x_py/order_manager/utils.py b/src/project_x_py/order_manager/utils.py index 6b7a16f..f39e36c 100644 --- a/src/project_x_py/order_manager/utils.py +++ b/src/project_x_py/order_manager/utils.py @@ -1,4 +1,28 @@ -"""Utility functions for order management.""" +""" +Order management utility functions for ProjectX. + +Overview: + Provides async/sync helpers for price alignment to instrument tick size, contract + resolution, and other utility operations used throughout the async OrderManager system. + +Key Features: + - Aligns prices to valid instrument tick size (async and sync) + - Resolves contract IDs to instrument metadata + - Precision rounding and validation helpers + +Example Usage: + ```python + # Aligning a price to tick size + aligned = align_price_to_tick(2052.17, 0.25) + # Resolving contract ID + details = await resolve_contract_id("MNQ", project_x_client) + ``` + +See Also: + - `order_manager.core.OrderManager` + - `order_manager.tracking` + - `order_manager.position_orders` +""" import logging from decimal import ROUND_HALF_UP, Decimal diff --git a/src/project_x_py/orderbook/__init__.py b/src/project_x_py/orderbook/__init__.py index d9418b8..0ad8c31 100644 --- a/src/project_x_py/orderbook/__init__.py +++ b/src/project_x_py/orderbook/__init__.py @@ -1,81 +1,42 @@ """ -Async Level 2 Orderbook module for ProjectX. - -This module provides comprehensive asynchronous orderbook analysis with real-time -capabilities for institutional-grade market microstructure analysis. It offers a -complete suite of tools for deep market understanding and strategy development. - -Core Functionality: -- Real-time Level 2 market depth tracking with WebSocket integration -- Advanced iceberg order detection with confidence scoring -- Order clustering analysis for institutional activity detection -- Volume profile analysis with Point of Control and Value Area -- Dynamic support/resistance level identification -- Detailed trade flow analytics and execution classification -- Memory-efficient data management with configurable cleanup policies -- Complete market microstructure metrics with imbalance detection - -Technical Features: -- Thread-safe concurrent access with asyncio locks -- Polars DataFrame-based data structures for performance -- Configurable memory management with automatic garbage collection -- Event-driven architecture with customizable callbacks -- Component-based design for maintainability and extensibility - -Example: - Basic usage with real-time data:: - - >>> from project_x_py import ProjectX, create_orderbook - >>> import asyncio - >>> - >>> async def main(): - ... # Initialize client and connect - ... client = ProjectX() - ... await client.connect() - ... - ... # Create orderbook with factory function - ... orderbook = create_orderbook( - ... instrument="MNQ", # Micro Nasdaq futures - ... project_x=client, - ... timezone_str="America/Chicago" - ... ) - ... - ... # Initialize with real-time data feed - ... await orderbook.initialize( - ... realtime_client=client.realtime_client, - ... subscribe_to_depth=True, - ... subscribe_to_quotes=True - ... ) - ... - ... # Get current orderbook snapshot - ... snapshot = await orderbook.get_orderbook_snapshot(levels=10) - ... print(f"Best Bid: {snapshot['best_bid']}") - ... print(f"Best Ask: {snapshot['best_ask']}") - ... print(f"Spread: {snapshot['spread']}") - ... print(f"Bid/Ask Imbalance: {snapshot['imbalance']}") - ... - ... # Detect iceberg orders - ... icebergs = await orderbook.detect_iceberg_orders(min_refreshes=5) - ... for iceberg in icebergs['iceberg_levels']: - ... print(f"Potential iceberg at {iceberg['price']} with " - ... f"{iceberg['confidence']:.1%} confidence") - ... - ... # Analyze market imbalance - ... imbalance = await orderbook.get_market_imbalance(levels=10) - ... print(f"Market imbalance: {imbalance['imbalance_ratio']:.2f} " - ... f"({imbalance['analysis']})") - ... - ... # Register a callback for order book updates - ... async def on_depth_update(data): - ... print(f"New depth update at {data['price']}, " - ... f"volume: {data['volume']}") - ... - ... await orderbook.add_callback("depth_update", on_depth_update) - ... - ... # Clean up resources when done - ... await orderbook.cleanup() - >>> - >>> asyncio.run(main()) +Async Level 2 orderbook toolkit for ProjectX. + +Overview: + Provides a complete async suite for Level 2 orderbook analysis, real-time market + microstructure, and market depth analytics. Integrates with ProjectX for + institutional-grade trading, strategy development, and execution research. + +Key Features: + - Real-time Level 2 market depth tracking (WebSocket) + - Iceberg/cluster detection, volume profile, and POC analytics + - Market imbalance, support/resistance, and trade flow stats + - Memory-efficient, thread-safe, event-driven architecture + - Component-based design for extensibility + +Example Usage: + ```python + from project_x_py import ProjectX, create_orderbook + import asyncio + + async def main(): + client = ProjectX() + await client.connect() + orderbook = create_orderbook("MNQ", project_x=client) + await orderbook.initialize(realtime_client=client.realtime_client) + snapshot = await orderbook.get_orderbook_snapshot(levels=10) + print(snapshot["best_bid"], snapshot["spread"]) + await orderbook.cleanup() + + asyncio.run(main()) + ``` + +See Also: + - `orderbook.base.OrderBookBase` + - `orderbook.analytics.MarketAnalytics` + - `orderbook.detection.OrderDetection` + - `orderbook.profile.VolumeProfile` + - `orderbook.memory.MemoryManager` + - `orderbook.realtime.RealtimeHandler` """ from typing import TYPE_CHECKING, Any diff --git a/src/project_x_py/orderbook/analytics.py b/src/project_x_py/orderbook/analytics.py index 99e641d..899563e 100644 --- a/src/project_x_py/orderbook/analytics.py +++ b/src/project_x_py/orderbook/analytics.py @@ -1,22 +1,29 @@ """ -Market analytics for the async orderbook. - -This module provides advanced market analytics for the async orderbook implementation, -focusing on quantitative analysis of market structure, liquidity, and order flow. -It extracts actionable insights from the raw orderbook data through a variety of -analytical methods. - -Key capabilities: -- Market imbalance analysis: Detects and quantifies buy/sell pressure -- Orderbook depth analysis: Evaluates liquidity distribution across price ranges -- Cumulative delta calculations: Tracks aggressive buying vs. selling over time -- Trade flow analytics: Analyzes market maker vs. taker behavior patterns -- Liquidity level identification: Locates significant support/resistance zones -- Comprehensive statistical analysis: Provides full orderbook metrics - -The analytics are designed to support trading strategy development, market -microstructure analysis, and real-time trading decision support by extracting -higher-level insights from the raw order book data. +Async market analytics for ProjectX orderbook. + +Overview: + Implements advanced quantitative analytics for the async orderbook, extracting + actionable insights on market structure, order flow, liquidity, and trade intensity. + Enables strategy development and microstructure research on deep market data. + +Key Features: + - Market imbalance detection and ratio analysis + - Orderbook depth and liquidity distribution metrics + - Cumulative delta and trade flow statistics + - VWAP, spread, and volume breakdowns + - Statistical summaries for trading strategy development + +Example Usage: + ```python + # Assuming orderbook is initialized and receiving data + imbalance = await orderbook.get_market_imbalance(levels=10) + print(imbalance["imbalance_ratio"], imbalance["analysis"]) + ``` + +See Also: + - `orderbook.base.OrderBookBase` + - `orderbook.detection.OrderDetection` + - `orderbook.profile.VolumeProfile` """ from datetime import datetime, timedelta diff --git a/src/project_x_py/orderbook/base.py b/src/project_x_py/orderbook/base.py index 443ba1e..feeb03b 100644 --- a/src/project_x_py/orderbook/base.py +++ b/src/project_x_py/orderbook/base.py @@ -1,24 +1,30 @@ """ -Base async orderbook functionality. - -This module contains the core orderbook data structures and foundational operations for -the async orderbook implementation. It provides the base class that maintains the primary -orderbook state, handles data consistency, and implements the core functionality upon which -higher-level analytics are built. - -Key features: -- Thread-safe orderbook data structures using asyncio locks -- Polars DataFrame-based bid and ask level storage -- Recent trade history tracking with automatic classification -- Best bid/ask price tracking with historical records -- Spread calculation and tracking -- Price level refreshment detection for iceberg analysis -- Configurable memory management -- Event-driven architecture with customizable callbacks - -The OrderBookBase class serves as the foundation for the complete OrderBook -implementation, providing the essential infrastructure while delegating specialized -functionality to dedicated component classes. +Base async orderbook functionality for ProjectX. + +Overview: + Defines the core data structures and foundational async methods for the ProjectX + orderbook system. Implements thread-safe storage, trade history, best price/spread + tracking, and callback/event infrastructure for all higher-level analytics. + +Key Features: + - Thread-safe Polars DataFrame bid/ask storage + - Recent trade history, spread, and tick size tracking + - Price level refreshment for iceberg/cluster analysis + - Async callback/event registration for orderbook events + - Configurable memory management and cleanup + +Example Usage: + ```python + # Directly using OrderBookBase for custom analytics + base = OrderBookBase("MNQ") + await base.get_best_bid_ask() + await base.add_callback("trade", lambda d: print(d)) + ``` + +See Also: + - `orderbook.analytics.MarketAnalytics` + - `orderbook.detection.OrderDetection` + - `orderbook.memory.MemoryManager` """ import asyncio diff --git a/src/project_x_py/orderbook/detection.py b/src/project_x_py/orderbook/detection.py index 0d167f9..94abd77 100644 --- a/src/project_x_py/orderbook/detection.py +++ b/src/project_x_py/orderbook/detection.py @@ -1,28 +1,28 @@ """ -Advanced detection algorithms for the async orderbook. - -This module implements sophisticated algorithms for detecting hidden market microstructure -patterns that provide deeper insights into market participant behavior. It specializes in -identifying patterns that may indicate institutional activity, hidden liquidity, and -market manipulation attempts. - -Key detection capabilities: -- Iceberg order detection: Identifies large hidden orders that only show a small portion - of their total size at any given time -- Order clustering analysis: Detects clusters of orders at similar price levels that may - indicate coordinated market participant activity -- Market microstructure metrics: Calculates advanced metrics that reveal hidden aspects - of market behavior -- Confidence scoring: Assigns confidence levels to detections to distinguish between - high and low probability signals - -The detection algorithms use historical price level data, order refresh patterns, and -trade execution analysis to infer the presence of hidden orders and market structures -that are not directly visible in the raw orderbook data. - -All detection methods are optimized for real-time performance while maintaining -accuracy, with configurable sensitivity parameters to adjust for different market -conditions and instrument characteristics. +Async detection algorithms for ProjectX orderbook. + +Overview: + Implements sophisticated detection logic for iceberg orders, clusters, and + hidden liquidity in the ProjectX async orderbook. Uses historical price + level, trade, and refresh data to infer institutional activity and market + manipulation attempts. + +Key Features: + - Iceberg order detection with confidence scoring + - Order clustering and spread concentration analysis + - Market microstructure and hidden volume metrics + - Configurable detection sensitivity and parameters + +Example Usage: + ```python + # Assuming orderbook is initialized and populated + icebergs = await orderbook.detect_iceberg_orders(min_refreshes=5) + print([i["price"] for i in icebergs["iceberg_levels"]]) + ``` + +See Also: + - `orderbook.base.OrderBookBase` + - `orderbook.analytics.MarketAnalytics` """ import logging diff --git a/src/project_x_py/orderbook/memory.py b/src/project_x_py/orderbook/memory.py index 2bbfebf..6ec0373 100644 --- a/src/project_x_py/orderbook/memory.py +++ b/src/project_x_py/orderbook/memory.py @@ -1,8 +1,29 @@ """ -Memory management for the async orderbook module. - -Handles cleanup strategies, memory statistics, and resource optimization -for high-frequency orderbook data processing. +Async memory management for ProjectX orderbook. + +Overview: + Provides memory/resource management for high-frequency orderbook data. Handles + cleanup, trimming, stats, and garbage collection for deep market data streams, + ensuring long-running session stability. + +Key Features: + - Periodic cleanup of trades, depth, and price history + - Configurable memory and history retention policies + - Memory usage/statistics reporting for diagnostics + - Async task-based cleanup with thread safety + +Example Usage: + ```python + # Assuming orderbook is initialized + await orderbook.memory_manager.start() + await orderbook.memory_manager.cleanup_old_data() + stats = await orderbook.memory_manager.get_memory_stats() + print(stats["recent_trades_count"]) + ``` + +See Also: + - `orderbook.base.OrderBookBase` + - `orderbook.analytics.MarketAnalytics` """ import asyncio diff --git a/src/project_x_py/orderbook/profile.py b/src/project_x_py/orderbook/profile.py index 2e50317..5797387 100644 --- a/src/project_x_py/orderbook/profile.py +++ b/src/project_x_py/orderbook/profile.py @@ -1,26 +1,28 @@ """ -Volume profile and support/resistance analysis for the async orderbook. - -This module implements sophisticated volume profile analysis, support/resistance level -detection, and spread analytics for market structure analysis. It focuses on identifying -key price levels and zones where significant trading activity has occurred or where -the market may find support or resistance in the future. - -Key capabilities: -- Volume profile analysis: Creates histogram-based analysis of volume distribution across - price levels, identifying high-volume nodes and areas of interest -- Point of Control (POC) identification: Locates the price level with highest traded volume -- Value Area calculation: Determines the price range containing 70% of volume around the POC -- Support and resistance level detection: Identifies price levels that have acted as - barriers to price movement based on historical price action -- Spread pattern analysis: Studies bid-ask spread behavior to identify market regime changes - and liquidity conditions -- Market structure analysis: Integrates volume and price information to understand underlying - market structure and participant behavior - -These analyses are particularly valuable for trading strategy development, trade planning, -and execution timing, as they provide insights into where market participants have been -active and where price may react in the future. +Async volume profile and support/resistance analytics for ProjectX. + +Overview: + Implements volume profile, POC, value area, support/resistance, and spread + analysis for the ProjectX async orderbook. Enables market structure research, + trade planning, and execution optimization based on historical and real-time data. + +Key Features: + - Volume profile histogram and Point of Control (POC) calculation + - Value area identification and support/resistance detection + - Spread analytics and regime change/trend detection + - Market structure mapping for trading and research + +Example Usage: + ```python + # Assuming orderbook is initialized and populated + vp = await orderbook.get_volume_profile(time_window_minutes=60) + print(vp["poc"], vp["value_area_high"], vp["value_area_low"]) + ``` + +See Also: + - `orderbook.base.OrderBookBase` + - `orderbook.analytics.MarketAnalytics` + - `orderbook.detection.OrderDetection` """ import logging diff --git a/src/project_x_py/orderbook/realtime.py b/src/project_x_py/orderbook/realtime.py index 4659662..989fb33 100644 --- a/src/project_x_py/orderbook/realtime.py +++ b/src/project_x_py/orderbook/realtime.py @@ -1,8 +1,28 @@ """ -Real-time data handling for the async orderbook. - -This module handles WebSocket callbacks, real-time data processing, -and orderbook updates from the ProjectX Gateway. +Async real-time data handling for ProjectX orderbook. + +Overview: + Manages WebSocket callbacks, real-time Level 2 data processing, and live orderbook + updates for ProjectX via the Gateway. Handles event registration, contract + subscription, and async orderbook data updates for trading and analytics. + +Key Features: + - WebSocket-based real-time data ingest and event processing + - Market depth and quote update callbacks for orderbook + - Async event/callback registration and contract management + - Orderbook reset, trade, and depth update logic + +Example Usage: + ```python + # Assuming orderbook and realtime_client are initialized + await orderbook.realtime_handler.initialize(realtime_client) + # Real-time updates are now handled automatically + ``` + +See Also: + - `orderbook.base.OrderBookBase` + - `orderbook.analytics.MarketAnalytics` + - `orderbook.detection.OrderDetection` """ from datetime import datetime