Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
40 changes: 39 additions & 1 deletion src/project_x_py/client/auth.py
Original file line number Diff line number Diff line change
@@ -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
Expand Down
39 changes: 38 additions & 1 deletion src/project_x_py/client/base.py
Original file line number Diff line number Diff line change
@@ -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
Expand Down
32 changes: 31 additions & 1 deletion src/project_x_py/client/cache.py
Original file line number Diff line number Diff line change
@@ -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
Expand Down
37 changes: 36 additions & 1 deletion src/project_x_py/client/http.py
Original file line number Diff line number Diff line change
@@ -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
Expand Down
38 changes: 37 additions & 1 deletion src/project_x_py/client/market_data.py
Original file line number Diff line number Diff line change
@@ -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
Expand Down
38 changes: 37 additions & 1 deletion src/project_x_py/client/trading.py
Original file line number Diff line number Diff line change
@@ -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
Expand Down
42 changes: 32 additions & 10 deletions src/project_x_py/indicators/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
30 changes: 29 additions & 1 deletion src/project_x_py/indicators/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
24 changes: 22 additions & 2 deletions src/project_x_py/indicators/fvg.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
25 changes: 23 additions & 2 deletions src/project_x_py/indicators/momentum.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
Loading
Loading