Skip to content

Commit f2b97a7

Browse files
committed
update documentation
1 parent ed27fc8 commit f2b97a7

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

72 files changed

+4639
-238
lines changed

src/project_x_py/__init__.py

Lines changed: 84 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -1,24 +1,96 @@
11
"""
22
ProjectX Python SDK for Trading Applications
33
4-
A comprehensive Python SDK for the ProjectX Trading Platform Gateway API, providing developers
5-
with tools to build sophisticated trading strategies and applications. This library offers
6-
comprehensive access to:
7-
8-
- Market data retrieval and real-time streaming
9-
- Account management and authentication
10-
- Order placement, modification, and cancellation
11-
- Position management and portfolio analytics
12-
- Trade history and execution analysis
13-
- Advanced technical indicators and market analysis
14-
- Level 2 orderbook depth and market microstructure
4+
Author: @TexasCoding
5+
Date: 2025-08-02
6+
7+
Overview:
8+
A comprehensive Python SDK for the ProjectX Trading Platform Gateway API, providing
9+
developers with tools to build sophisticated trading strategies and applications.
10+
This library offers comprehensive access to real-time market data, order management,
11+
position tracking, and advanced analytics for algorithmic trading.
12+
13+
Key Features:
14+
- Real-time market data streaming and historical data access
15+
- Comprehensive order management (market, limit, stop, bracket orders)
16+
- Position tracking and portfolio analytics
17+
- Level 2 orderbook depth and market microstructure analysis
18+
- Advanced technical indicators and pattern recognition
19+
- Risk management and position sizing tools
20+
- Multi-timeframe data management and analysis
21+
- WebSocket-based real-time updates and event handling
22+
23+
Core Components:
24+
- ProjectX: Main client for API interactions and authentication
25+
- OrderManager: Order placement, modification, and tracking
26+
- PositionManager: Position monitoring, analytics, and risk management
27+
- OrderBook: Level 2 market depth analysis and order flow
28+
- RealtimeDataManager: Multi-timeframe real-time data processing
29+
- ProjectXRealtimeClient: WebSocket-based real-time connections
30+
31+
Trading Capabilities:
32+
- Market data retrieval and real-time streaming
33+
- Account management and authentication
34+
- Order placement, modification, and cancellation
35+
- Position management and portfolio analytics
36+
- Trade history and execution analysis
37+
- Advanced technical indicators and market analysis
38+
- Level 2 orderbook depth and market microstructure
39+
- Risk management and position sizing
40+
41+
Example Usage:
42+
```python
43+
from project_x_py import ProjectX, OrderManager, PositionManager
44+
45+
# Basic client setup
46+
async with ProjectX.from_env() as client:
47+
await client.authenticate()
48+
49+
# Get market data
50+
bars = await client.get_bars("MGC", days=5)
51+
instrument = await client.get_instrument("MGC")
52+
53+
# Place orders
54+
order_manager = OrderManager(client)
55+
response = await order_manager.place_market_order(
56+
contract_id=instrument.id,
57+
side=0, # Buy
58+
size=1,
59+
)
60+
61+
# Track positions
62+
position_manager = PositionManager(client)
63+
positions = await position_manager.get_all_positions()
64+
65+
# Create complete trading suite
66+
suite = await create_trading_suite(
67+
instrument="MGC", project_x=client, timeframes=["1min", "5min", "15min"]
68+
)
69+
```
70+
71+
Architecture Benefits:
72+
- Async-first design for high-performance trading applications
73+
- Comprehensive error handling and retry logic
74+
- Rate limiting and connection management
75+
- Real-time data processing with WebSocket integration
76+
- Modular design for flexible trading system development
77+
- Type-safe operations with comprehensive validation
1578
1679
**Important**: This is a development toolkit/SDK, not a trading strategy itself.
1780
It provides the infrastructure to help developers create their own trading applications
1881
that integrate with the ProjectX platform.
1982
83+
Version: 2.0.5
2084
Author: TexasCoding
21-
Date: January 2025
85+
86+
See Also:
87+
- `client`: Main client for API interactions
88+
- `order_manager`: Order management and tracking
89+
- `position_manager`: Position monitoring and analytics
90+
- `orderbook`: Level 2 market depth analysis
91+
- `realtime_data_manager`: Real-time data processing
92+
- `indicators`: Technical analysis and indicators
93+
- `utils`: Utility functions and calculations
2294
"""
2395

2496
from typing import Any

src/project_x_py/client/__init__.py

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,9 @@
11
"""
22
Async ProjectX Python SDK - Core Async Client Module
33
4+
Author: @TexasCoding
5+
Date: 2025-08-02
6+
47
This module contains the async version of the ProjectX client class for the ProjectX Python SDK.
58
It provides a comprehensive asynchronous interface for interacting with the ProjectX Trading Platform
69
Gateway API, enabling developers to build high-performance trading applications.

src/project_x_py/client/auth.py

Lines changed: 49 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,9 @@
11
"""
22
Authentication and account management for ProjectX async clients.
33
4+
Author: @TexasCoding
5+
Date: 2025-08-02
6+
47
Overview:
58
This module implements the complete authentication lifecycle for ProjectX, including
69
secure login using API key and username, JWT token handling, account selection, and
@@ -21,6 +24,7 @@
2124
import asyncio
2225
from project_x_py import ProjectX
2326
27+
2428
async def main():
2529
async with ProjectX.from_env() as client:
2630
await client.authenticate()
@@ -29,6 +33,7 @@ async def main():
2933
for acc in accounts:
3034
print(acc.name, acc.balance)
3135
36+
3237
asyncio.run(main())
3338
```
3439
@@ -75,12 +80,35 @@ def __init__(self) -> None:
7580
self.account_info: Account | None = None
7681

7782
async def _refresh_authentication(self: "ProjectXClientProtocol") -> None:
78-
"""Refresh authentication if token is expired or about to expire."""
83+
"""
84+
Refresh authentication if token is expired or about to expire.
85+
86+
This method checks if the current authentication token needs refreshing
87+
based on its expiration time and initiates a full re-authentication
88+
if necessary. It's used internally to maintain session validity during
89+
long-running operations without requiring explicit user intervention.
90+
91+
The refresh logic is controlled by the _should_refresh_token method,
92+
which implements the token expiration policy (currently refreshing
93+
when a token is within 5 minutes of expiration).
94+
"""
7995
if self._should_refresh_token():
8096
await self.authenticate()
8197

8298
def _should_refresh_token(self: "ProjectXClientProtocol") -> bool:
83-
"""Check if token should be refreshed."""
99+
"""
100+
Check if the authentication token should be refreshed.
101+
102+
This method determines whether the current JWT token needs to be refreshed
103+
based on its expiration time. It implements the token refresh policy by
104+
checking:
105+
106+
1. If no token expiry exists (not authenticated or expiry unknown)
107+
2. If the token is within 5 minutes of expiration (configurable buffer)
108+
109+
Returns:
110+
bool: True if token refresh is needed, False otherwise
111+
"""
84112
if not self.token_expiry:
85113
return True
86114

@@ -191,7 +219,25 @@ async def authenticate(self: "ProjectXClientProtocol") -> None:
191219
)
192220

193221
async def _ensure_authenticated(self: "ProjectXClientProtocol") -> None:
194-
"""Ensure client is authenticated before making API calls."""
222+
"""
223+
Ensure client is authenticated before making API calls.
224+
225+
This method checks the authentication state and token validity before
226+
allowing API operations to proceed. If the client is not authenticated
227+
or if the authentication token is expired/about to expire, it will
228+
automatically trigger the full authentication flow.
229+
230+
The method performs two key checks:
231+
1. Whether the client has successfully authenticated (_authenticated flag)
232+
2. Whether the token needs refreshing (via _should_refresh_token)
233+
234+
This provides a seamless authentication experience by handling token
235+
expiration transparently without requiring explicit refresh calls.
236+
237+
Note:
238+
This method is called internally by API methods and doesn't need
239+
to be called directly in normal usage.
240+
"""
195241
if not self._authenticated or self._should_refresh_token():
196242
await self.authenticate()
197243

src/project_x_py/client/base.py

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,9 @@
11
"""
22
ProjectX async base client: context-managed lifecycle, mixin composition, and helpers.
33
4+
Author: @TexasCoding
5+
Date: 2025-08-02
6+
47
Overview:
58
Defines the foundational async client for ProjectX by combining all core functional
69
mixins (auth, HTTP, cache, market data, trading) into a single context-managed class.
@@ -21,11 +24,13 @@
2124
import asyncio
2225
from project_x_py import ProjectX
2326
27+
2428
async def main():
2529
async with ProjectX.from_env() as client:
2630
await client.authenticate()
2731
print(client.get_account_info())
2832
33+
2934
asyncio.run(main())
3035
```
3136

src/project_x_py/client/cache.py

Lines changed: 17 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,9 @@
11
"""
22
In-memory caching for instrument and market data with TTL and performance tracking.
33
4+
Author: @TexasCoding
5+
Date: 2025-08-02
6+
47
Overview:
58
Provides efficient, per-symbol in-memory caching for instrument metadata and historical
69
market data. Uses time-based TTL (time-to-live) for automatic expiry and memory cleanup,
@@ -67,7 +70,20 @@ def __init__(self) -> None:
6770
self.cache_hit_count = 0
6871

6972
async def _cleanup_cache(self: "ProjectXClientProtocol") -> None:
70-
"""Clean up expired cache entries."""
73+
"""
74+
Clean up expired cache entries to manage memory usage.
75+
76+
This method removes expired entries from both instrument and market data caches
77+
based on the configured TTL (time-to-live). It helps prevent unbounded memory
78+
growth during long-running sessions by:
79+
80+
1. Removing instrument cache entries that have exceeded their TTL
81+
2. Removing market data cache entries that have exceeded their TTL
82+
3. Triggering garbage collection when a significant number of entries are removed
83+
84+
The method is called periodically during normal API operations and updates
85+
the last_cache_cleanup timestamp to track when cleanup was last performed.
86+
"""
7187
current_time = time.time()
7288

7389
# Clean instrument cache

src/project_x_py/client/http.py

Lines changed: 19 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,9 @@
11
"""
22
Async HTTP/2 client, rate-limiting, and robust error handling for ProjectX SDK.
33
4+
Author: @TexasCoding
5+
Date: 2025-08-02
6+
47
Overview:
58
Implements the async HTTP/2 client logic for ProjectX API access, including connection
69
pooling, automatic retry on transient errors, and adaptive rate limiting. All API calls
@@ -21,11 +24,13 @@
2124
import asyncio
2225
from project_x_py import ProjectX
2326
27+
2428
async def main():
2529
async with ProjectX.from_env() as client:
2630
status = await client.get_health_status()
2731
print(status["api_status"], status["client_stats"]["api_calls"])
2832
33+
2934
asyncio.run(main())
3035
```
3136
@@ -119,7 +124,20 @@ async def _create_client(self: "ProjectXClientProtocol") -> httpx.AsyncClient:
119124
return client
120125

121126
async def _ensure_client(self: "ProjectXClientProtocol") -> httpx.AsyncClient:
122-
"""Ensure HTTP client is initialized."""
127+
"""
128+
Ensure HTTP client is initialized and ready for API requests.
129+
130+
This method lazily initializes the HTTP client when needed, creating a new
131+
client instance if one doesn't exist. It's used internally before making
132+
any API requests to ensure a valid client connection is available.
133+
134+
Returns:
135+
httpx.AsyncClient: The initialized HTTP client instance
136+
137+
Note:
138+
This method is called automatically by _make_request and doesn't need
139+
to be called directly in normal usage.
140+
"""
123141
if self._client is None:
124142
self._client = await self._create_client()
125143
return self._client

src/project_x_py/client/market_data.py

Lines changed: 25 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,9 @@
11
"""
22
Async instrument search, selection, and historical bar data for ProjectX clients.
33
4+
Author: @TexasCoding
5+
Date: 2025-08-02
6+
47
Overview:
58
Provides async methods for instrument discovery, smart contract selection, and retrieval
69
of historical OHLCV bar data, with Polars DataFrame output for high-performance analysis.
@@ -21,12 +24,14 @@
2124
import asyncio
2225
from project_x_py import ProjectX
2326
27+
2428
async def main():
2529
async with ProjectX.from_env() as client:
2630
instrument = await client.get_instrument("ES")
2731
bars = await client.get_bars("ES", days=3, interval=15)
2832
print(bars.head())
2933
34+
3035
asyncio.run(main())
3136
```
3237
@@ -144,17 +149,30 @@ def _select_best_contract(
144149
"""
145150
Select the best matching contract from search results.
146151
147-
This method implements smart contract selection logic for futures:
148-
- Exact matches are preferred
149-
- For futures, selects the front month contract
150-
- For micro contracts, ensures correct symbol (e.g., MNQ for micro Nasdaq)
152+
This method implements smart contract selection logic for futures and other
153+
instruments, ensuring the most appropriate contract is selected based on
154+
the search criteria. The selection algorithm follows these priorities:
155+
156+
1. Exact symbol match (case-insensitive)
157+
2. For futures contracts:
158+
- Identifies the base symbol (e.g., "ES" from "ESM23")
159+
- Groups contracts by base symbol
160+
- Selects the front month contract (chronologically closest expiration)
161+
3. For micro contracts, ensures proper matching (e.g., "MNQ" for micro Nasdaq)
162+
4. Falls back to the first result if no better match is found
163+
164+
The futures month codes follow CME convention: F(Jan), G(Feb), H(Mar), J(Apr),
165+
K(May), M(Jun), N(Jul), Q(Aug), U(Sep), V(Oct), X(Nov), Z(Dec)
151166
152167
Args:
153-
instruments: List of instrument dictionaries from search
154-
search_symbol: Original search symbol
168+
instruments: List of instrument dictionaries from search results
169+
search_symbol: Original search symbol provided by the user
155170
156171
Returns:
157-
Best matching instrument dictionary
172+
dict[str, Any]: Best matching instrument dictionary with complete contract details
173+
174+
Raises:
175+
ProjectXInstrumentError: If no instruments are found for the given symbol
158176
"""
159177
if not instruments:
160178
raise ProjectXInstrumentError(f"No instruments found for: {search_symbol}")

0 commit comments

Comments
 (0)