Skip to content

Commit ed27fc8

Browse files
authored
chore: update documentation for ProjectX async orderbook modules, enhancing clarity and usability.
Co-authored-by: Genie <[email protected]> Enhance Docstrings for ProjectX Client Modules
2 parents a3ad4ab + f72dc1c commit ed27fc8

29 files changed

+815
-217
lines changed

src/project_x_py/client/auth.py

Lines changed: 39 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,42 @@
1-
"""Authentication and token management for ProjectX client."""
1+
"""
2+
Authentication and account management for ProjectX async clients.
3+
4+
Overview:
5+
This module implements the complete authentication lifecycle for ProjectX, including
6+
secure login using API key and username, JWT token handling, account selection, and
7+
robust error management. It automatically parses and refreshes authentication tokens,
8+
supports multiple accounts, and ensures session validity throughout async API usage.
9+
Integrated as a mixin, it enables seamless auth orchestration for all async clients.
10+
11+
Key Features:
12+
- Full async login flow with API key and user credentials
13+
- JWT token parsing, expiry extraction, and proactive refresh logic
14+
- Multi-account discovery and selection (by name or default)
15+
- Automatic authentication refresh on token expiry or invalidation
16+
- Error management with descriptive exceptions for auth failures
17+
- Utility methods for listing and validating available accounts
18+
19+
Example Usage:
20+
```python
21+
import asyncio
22+
from project_x_py import ProjectX
23+
24+
async def main():
25+
async with ProjectX.from_env() as client:
26+
await client.authenticate()
27+
print(f"Authenticated as {client.account_info.username}")
28+
accounts = await client.list_accounts()
29+
for acc in accounts:
30+
print(acc.name, acc.balance)
31+
32+
asyncio.run(main())
33+
```
34+
35+
See Also:
36+
- `project_x_py.client.base.ProjectXBase` (core client with mixins)
37+
- `project_x_py.client.http.HttpMixin` (for HTTP request integration)
38+
- `project_x_py.client.trading.TradingMixin` (trading operations requiring auth)
39+
"""
240

341
import base64
442
import datetime

src/project_x_py/client/base.py

Lines changed: 38 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,41 @@
1-
"""Base client class with lifecycle methods for ProjectX."""
1+
"""
2+
ProjectX async base client: context-managed lifecycle, mixin composition, and helpers.
3+
4+
Overview:
5+
Defines the foundational async client for ProjectX by combining all core functional
6+
mixins (auth, HTTP, cache, market data, trading) into a single context-managed class.
7+
Supports async context management for safe resource cleanup, flexible instantiation from
8+
environment or config file, and exposes helper classmethods to streamline credential and
9+
configuration handling in both development and production setups.
10+
11+
Key Features:
12+
- Composes all client-side mixins (auth, HTTP, cache, data, trading)
13+
- Async context manager for safe resource initialization and teardown
14+
- Classmethod constructors: `from_env` and `from_config_file`
15+
- Centralized client/session token and account info access
16+
- Integrated API rate limiting and configuration
17+
- Suitable as a base for advanced SDK extensibility
18+
19+
Example Usage:
20+
```python
21+
import asyncio
22+
from project_x_py import ProjectX
23+
24+
async def main():
25+
async with ProjectX.from_env() as client:
26+
await client.authenticate()
27+
print(client.get_account_info())
28+
29+
asyncio.run(main())
30+
```
31+
32+
See Also:
33+
- `project_x_py.client.auth.AuthenticationMixin`
34+
- `project_x_py.client.http.HttpMixin`
35+
- `project_x_py.client.cache.CacheMixin`
36+
- `project_x_py.client.market_data.MarketDataMixin`
37+
- `project_x_py.client.trading.TradingMixin`
38+
"""
239

340
import logging
441
import os

src/project_x_py/client/cache.py

Lines changed: 31 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,34 @@
1-
"""Caching functionality for ProjectX client."""
1+
"""
2+
In-memory caching for instrument and market data with TTL and performance tracking.
3+
4+
Overview:
5+
Provides efficient, per-symbol in-memory caching for instrument metadata and historical
6+
market data. Uses time-based TTL (time-to-live) for automatic expiry and memory cleanup,
7+
reducing API load and improving performance for frequently accessed symbols. Includes
8+
cache hit counters and periodic cleanup for resource optimization within async clients.
9+
10+
Key Features:
11+
- Fast cache for instrument lookups (symbol → instrument)
12+
- Market data caching for historical bar queries (string key → Polars DataFrame)
13+
- Configurable TTL (default 5 minutes) to automatically expire stale data
14+
- Performance metrics: cache hit count and cleanup timing
15+
- Async cache cleanup and garbage collection for large workloads
16+
- Manual cache clearing utilities
17+
18+
Example Usage:
19+
```python
20+
# Used internally by ProjectX; typical use is transparent:
21+
instrument = await client.get_instrument("MNQ")
22+
# On repeated calls, instrument is served from cache if not expired.
23+
cached = client.get_cached_instrument("MNQ")
24+
client.clear_all_caches()
25+
```
26+
27+
See Also:
28+
- `project_x_py.client.market_data.MarketDataMixin`
29+
- `project_x_py.client.base.ProjectXBase`
30+
- `project_x_py.client.http.HttpMixin`
31+
"""
232

333
import gc
434
import logging

src/project_x_py/client/http.py

Lines changed: 36 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,39 @@
1-
"""HTTP client and request handling for ProjectX client."""
1+
"""
2+
Async HTTP/2 client, rate-limiting, and robust error handling for ProjectX SDK.
3+
4+
Overview:
5+
Implements the async HTTP/2 client logic for ProjectX API access, including connection
6+
pooling, automatic retry on transient errors, and adaptive rate limiting. All API calls
7+
are decorated for rate control and network resilience, with detailed error mapping for
8+
4xx and 5xx responses. Integrates with authentication for seamless token refresh and
9+
propagates network/runtime errors as SDK-specific exceptions.
10+
11+
Key Features:
12+
- HTTP/2 async client with connection pooling (via httpx)
13+
- Decorators for automatic rate limiting and network retry logic
14+
- Error mapping: raises precise exceptions for 4xx/5xx responses
15+
- Automatic JWT token refresh on 401/expired session
16+
- API call logging, health status, and statistics
17+
- Centralized request/response handling for all mixins
18+
19+
Example Usage:
20+
```python
21+
import asyncio
22+
from project_x_py import ProjectX
23+
24+
async def main():
25+
async with ProjectX.from_env() as client:
26+
status = await client.get_health_status()
27+
print(status["api_status"], status["client_stats"]["api_calls"])
28+
29+
asyncio.run(main())
30+
```
31+
32+
See Also:
33+
- `project_x_py.client.base.ProjectXBase`
34+
- `project_x_py.client.auth.AuthenticationMixin`
35+
- `project_x_py.client.cache.CacheMixin`
36+
"""
237

338
import time
439
from typing import TYPE_CHECKING, Any

src/project_x_py/client/market_data.py

Lines changed: 37 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,40 @@
1-
"""Market data operations for ProjectX client."""
1+
"""
2+
Async instrument search, selection, and historical bar data for ProjectX clients.
3+
4+
Overview:
5+
Provides async methods for instrument discovery, smart contract selection, and retrieval
6+
of historical OHLCV bar data, with Polars DataFrame output for high-performance analysis.
7+
Integrates in-memory caching for both instrument and bar queries, minimizing redundant
8+
API calls and ensuring data consistency. Designed to support trading and analytics flows
9+
requiring timely and accurate market data.
10+
11+
Key Features:
12+
- Symbol/name instrument search with live/active filtering
13+
- Sophisticated contract selection logic (front month, micro, etc.)
14+
- Historical bar data retrieval (OHLCV) with timezone handling
15+
- Transparent, per-query caching for both instrument and bars
16+
- Data returned as Polars DataFrame (timestamp, open, high, low, close, volume)
17+
- Utilities for cache management and periodic cleanup
18+
19+
Example Usage:
20+
```python
21+
import asyncio
22+
from project_x_py import ProjectX
23+
24+
async def main():
25+
async with ProjectX.from_env() as client:
26+
instrument = await client.get_instrument("ES")
27+
bars = await client.get_bars("ES", days=3, interval=15)
28+
print(bars.head())
29+
30+
asyncio.run(main())
31+
```
32+
33+
See Also:
34+
- `project_x_py.client.cache.CacheMixin`
35+
- `project_x_py.client.base.ProjectXBase`
36+
- `project_x_py.client.trading.TradingMixin`
37+
"""
238

339
import datetime
440
import re

src/project_x_py/client/trading.py

Lines changed: 37 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,40 @@
1-
"""Trading operations for ProjectX client."""
1+
"""
2+
Async trading queries: positions and trade history for ProjectX accounts.
3+
4+
Overview:
5+
Supplies async methods for querying open positions and executed trades for the currently
6+
authenticated account. Integrates tightly with the authentication/session lifecycle and
7+
other mixins, enabling streamlined access to P&L, trade analysis, and reporting data.
8+
All queries require a valid session and leverage ProjectX's unified API request logic.
9+
10+
Key Features:
11+
- Query current open positions for the selected account
12+
- Search historical trades with flexible date range and contract filters
13+
- Async error handling and robust integration with authentication
14+
- Typed results as Position and Trade model objects for analysis/reporting
15+
- Designed for use in trading bots, dashboards, and research scripts
16+
17+
Example Usage:
18+
```python
19+
import asyncio
20+
from project_x_py import ProjectX
21+
22+
async def main():
23+
async with ProjectX.from_env() as client:
24+
await client.authenticate()
25+
positions = await client.get_positions()
26+
trades = await client.search_trades(limit=10)
27+
print([p.symbol for p in positions])
28+
print([t.contractId for t in trades])
29+
30+
asyncio.run(main())
31+
```
32+
33+
See Also:
34+
- `project_x_py.client.auth.AuthenticationMixin`
35+
- `project_x_py.client.base.ProjectXBase`
36+
- `project_x_py.client.market_data.MarketDataMixin`
37+
"""
238

339
import datetime
440
import logging

src/project_x_py/indicators/__init__.py

Lines changed: 32 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -4,19 +4,41 @@
44
Author: TexasCoding
55
Date: June 2025
66
7-
A comprehensive technical analysis library similar to TA-Lib, built on Polars DataFrames.
8-
Provides both class-based and function-based interfaces for technical indicators.
9-
10-
Example usage:
7+
Overview:
8+
ProjectX Indicators provides a comprehensive, extensible technical analysis library
9+
similar to TA-Lib, built on Polars DataFrames. It offers both class-based and
10+
function-based interfaces for over 60 technical indicators, with seamless integration
11+
for vectorized backtesting and strategy development in ProjectX and beyond.
12+
13+
Key Features:
14+
- Wide range of indicators: trend/overlap, momentum, volatility, volume, and patterns
15+
- Class-based and TA-Lib-style function interface for flexible usage
16+
- All indicators operate on Polars DataFrames for speed and modern analytics
17+
- Utilities for indicator discovery, grouping, and docstring access
18+
- Clean API and naming convention for easy scripting and research
19+
20+
Example Usage:
21+
```python
1122
# Class-based interface
12-
>>> from project_x_py.indicators import RSI, SMA
13-
>>> rsi = RSI()
14-
>>> data_with_rsi = rsi.calculate(ohlcv_data, period=14)
23+
from project_x_py.indicators import RSI, SMA
24+
rsi = RSI()
25+
data_with_rsi = rsi.calculate(ohlcv_data, period=14)
1526
1627
# Function-based interface (TA-Lib style)
17-
>>> from project_x_py.indicators import calculate_rsi, calculate_sma
18-
>>> data_with_rsi = calculate_rsi(ohlcv_data, period=14)
19-
>>> data_with_sma = calculate_sma(ohlcv_data, period=20)
28+
from project_x_py.indicators import calculate_rsi, calculate_sma
29+
data_with_rsi = calculate_rsi(ohlcv_data, period=14)
30+
data_with_sma = calculate_sma(ohlcv_data, period=20)
31+
```
32+
33+
See Also:
34+
- `project_x_py.indicators.base` (abstract base classes/utilities)
35+
- `project_x_py.indicators.momentum`
36+
- `project_x_py.indicators.overlap`
37+
- `project_x_py.indicators.volume`
38+
- `project_x_py.indicators.volatility`
39+
- `project_x_py.indicators.order_block`
40+
- `project_x_py.indicators.fvg`
41+
- `project_x_py.indicators.waddah_attar`
2042
"""
2143

2244
import polars as pl

src/project_x_py/indicators/base.py

Lines changed: 29 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,35 @@
44
Author: TexasCoding
55
Date: June 2025
66
7-
Base classes and common functionality for technical indicators.
7+
Overview:
8+
Provides abstract base classes and shared validation/utilities for all ProjectX
9+
indicator modules. Encapsulates error handling, cache logic, and call semantics
10+
for consistent and efficient indicator development. All custom indicators should
11+
inherit from these classes for uniformity and extensibility.
12+
13+
Key Features:
14+
- `BaseIndicator` with parameter validation, data checks, and result caching
15+
- Specialized subclasses: OverlapIndicator, MomentumIndicator, VolatilityIndicator,
16+
VolumeIndicator
17+
- Utility functions for safe division, rolling sums, and EMA alpha calculation
18+
- Standardized exception (`IndicatorError`) for all indicator errors
19+
20+
Example Usage:
21+
```python
22+
from project_x_py.indicators.base import BaseIndicator
23+
24+
class MyCustomIndicator(BaseIndicator):
25+
def calculate(self, data, period=10):
26+
self.validate_data(data, ["close"])
27+
self.validate_period(period)
28+
# ... custom calculation ...
29+
```
30+
31+
See Also:
32+
- `project_x_py.indicators.momentum.MomentumIndicator`
33+
- `project_x_py.indicators.overlap.OverlapIndicator`
34+
- `project_x_py.indicators.volatility.VolatilityIndicator`
35+
- `project_x_py.indicators.volume.VolumeIndicator`
836
"""
937

1038
import hashlib

src/project_x_py/indicators/fvg.py

Lines changed: 22 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -4,8 +4,28 @@
44
Author: TexasCoding
55
Date: August 2025
66
7-
Fair Value Gap indicator identifies imbalance areas in price action where there is little
8-
to no trading activity, which can act as support/resistance zones.
7+
Overview:
8+
Implements the Fair Value Gap (FVG) indicator for identifying price imbalances
9+
and potential support/resistance zones. Detects gaps in price action with
10+
optional mitigation logic, helping traders spot areas likely to be revisited.
11+
12+
Key Features:
13+
- Identifies bullish/bearish fair value gaps from OHLC data
14+
- Supports configurable gap size, mitigation threshold, and custom columns
15+
- Returns gap boundary, size, and mitigation status for each bar
16+
- Callable as a class or via TA-Lib-style convenience function
17+
18+
Example Usage:
19+
```python
20+
from project_x_py.indicators import FVG
21+
fvg = FVG()
22+
data_with_fvg = fvg.calculate(ohlcv_data, min_gap_size=0.001)
23+
gaps = data_with_fvg.filter(pl.col("fvg_bullish"))
24+
```
25+
26+
See Also:
27+
- `project_x_py.indicators.order_block`
28+
- `project_x_py.indicators.base.BaseIndicator`
929
"""
1030

1131
from typing import Any

src/project_x_py/indicators/momentum.py

Lines changed: 23 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -4,8 +4,29 @@
44
Author: TexasCoding
55
Date: June 2025
66
7-
Momentum indicators measure the rate of change in price movements,
8-
helping identify overbought/oversold conditions and trend strength.
7+
Overview:
8+
Provides a suite of momentum indicators for ProjectX, covering oscillators and
9+
trend-following calculations. Includes both class-based and TA-Lib-style
10+
function interfaces for RSI, MACD, Stochastic, CCI, and many more, all operating
11+
on Polars DataFrames.
12+
13+
Key Features:
14+
- Relative Strength Index (RSI), MACD, Stochastic, Williams %R, CCI, ROC, MOM, and more
15+
- Directional movement, Aroon, Ultimate Oscillator, and Chande Momentum Oscillator
16+
- All indicators vectorized for performance and chained analysis
17+
- Flexible configuration: periods, smoothing, columns, and more
18+
- Convenient function interface for script-style use
19+
20+
Example Usage:
21+
```python
22+
from project_x_py.indicators import calculate_rsi
23+
data_with_rsi = calculate_rsi(ohlcv_data, period=14)
24+
```
25+
26+
See Also:
27+
- `project_x_py.indicators.base.MomentumIndicator`
28+
- `project_x_py.indicators.overlap`
29+
- `project_x_py.indicators.volume`
930
"""
1031

1132
from typing import Any

0 commit comments

Comments
 (0)