Skip to content

Commit 6bc0103

Browse files
committed
update
1 parent f84d753 commit 6bc0103

File tree

2 files changed

+234
-53
lines changed

2 files changed

+234
-53
lines changed

.cursorrules

Lines changed: 77 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,12 @@
11
# ProjectX Python SDK - Cursor AI Rules
22

33
## Project Overview
4-
This is a Python SDK/client library for the ProjectX Trading Platform (https://www.projectx.com/) Gateway API. It provides developers with tools to build sophisticated trading strategies and applications by offering comprehensive access to real-time market data, order management, and market analysis. The SDK uses Polars for data processing and emphasizes performance, accuracy, and real-time capabilities.
4+
This is an **async-first Python SDK** (v2.0.4) for the ProjectX Trading Platform (https://www.projectx.com/) Gateway API. It provides developers with tools to build sophisticated trading strategies and applications by offering comprehensive async access to real-time market data, order management, and market analysis. The SDK uses Polars for data processing and emphasizes performance, accuracy, and real-time capabilities.
55

66
**Important**: This is NOT a trading strategy itself - it's a development toolkit that enables the creation of trading strategies that integrate with the ProjectX platform.
77

8+
**Architecture**: As of v2.0.0, this SDK is fully asynchronous with no synchronous APIs. All operations use async/await patterns for optimal performance and concurrency.
9+
810
## ProjectX API Integration Rules
911

1012
### Configurable Platform Endpoints
@@ -41,11 +43,20 @@ This is a Python SDK/client library for the ProjectX Trading Platform (https://w
4143

4244
## Code Style & Formatting Rules
4345

46+
### Async Patterns (v2.0.0+)
47+
- **ALWAYS** use `async def` for methods that perform I/O operations
48+
- **ALWAYS** use `await` when calling async methods
49+
- **ALWAYS** use `async with` for context managers
50+
- **NEVER** create synchronous wrappers around async methods
51+
- **ALWAYS** propagate async patterns through the entire call stack
52+
- **PREFER** `asyncio.gather()` for concurrent operations
53+
4454
### Type Hints
4555
- **ALWAYS** use modern Python 3.10+ union syntax: `int | None` instead of `Optional[int]`
4656
- **ALWAYS** use `X | Y` in isinstance calls instead of `(X, Y)` tuples
4757
- **ALWAYS** include comprehensive type hints for all method parameters and return values
4858
- **PREFER** `dict[str, Any]` over `Dict[str, Any]`
59+
- **ALWAYS** use proper async type hints: `Coroutine`, `AsyncIterator`, etc.
4960

5061
### Error Handling
5162
- **ALWAYS** wrap ProjectX API calls in try-catch blocks
@@ -76,12 +87,15 @@ This is a Python SDK/client library for the ProjectX Trading Platform (https://w
7687

7788
## Testing & Validation Rules
7889

79-
### Test Methods
90+
### Async Test Methods
91+
- **ALWAYS** use `@pytest.mark.asyncio` for async test methods
92+
- **ALWAYS** use `async def test_*` for testing async functionality
8093
- **ALWAYS** include comprehensive test methods for new features
8194
- **ALWAYS** test both success and failure scenarios
8295
- **ALWAYS** validate prerequisites before running tests
8396
- **ALWAYS** return structured test results with `validation`, `performance_metrics`, and `recommendations`
8497
- **PREFER** internal test methods over external test files for component validation
98+
- **ALWAYS** use `aioresponses` for mocking async HTTP calls
8599

86100
### Validation Patterns
87101
- **ALWAYS** implement `_validate_*_payload()` methods for API data
@@ -96,6 +110,8 @@ This is a Python SDK/client library for the ProjectX Trading Platform (https://w
96110
- **ALWAYS** implement time filtering for all analysis methods
97111
- **ALWAYS** return comprehensive analysis with metadata
98112
- **PREFER** confidence scores and statistical validation over simple thresholds
113+
- **SUPPORT** pattern recognition indicators (FVG, Order Block, WAE)
114+
- **ENSURE** all indicators work with async data pipelines
99115

100116
### Data Consistency
101117
- **ALWAYS** ensure consistent time windows across related analysis methods
@@ -119,17 +135,30 @@ This is a Python SDK/client library for the ProjectX Trading Platform (https://w
119135

120136
## Architecture Rules
121137

138+
### Package Structure (v2.0.4+)
139+
- **ORGANIZED** as multi-file packages for better maintainability:
140+
- `client/`: Auth, HTTP, caching, rate limiting modules
141+
- `order_manager/`: Core, bracket orders, position orders, tracking
142+
- `position_manager/`: Core, risk, analytics, monitoring
143+
- `realtime_data_manager/`: Core, callbacks, data processing
144+
- `orderbook/`: Base, analytics, detection, profile
145+
- `utils/`: Market utils, formatting, calculations
146+
- `indicators/`: Momentum, overlap, volatility, volume, patterns
147+
122148
### Dependency Management
123149
- **ALWAYS** use `uv` as the package manager
124150
- **NEVER** require backwards compatibility (new project)
125151
- **PREFER** modern Python features and syntax
126152
- **ALWAYS** specify exact versions for critical dependencies
153+
- **REQUIRE** Python 3.12+ for async performance
127154

128155
### Real-time Integration
129-
- **ALWAYS** implement callback patterns for real-time updates
130-
- **ALWAYS** handle connection failures gracefully
131-
- **ALWAYS** implement proper cleanup for resources
156+
- **ALWAYS** implement async callback patterns for real-time updates
157+
- **ALWAYS** handle connection failures gracefully with exponential backoff
158+
- **ALWAYS** implement proper cleanup with `async with` contexts
132159
- **PREFER** event-driven architecture over polling
160+
- **ALWAYS** use WebSocket for real-time data feeds
161+
- **ENSURE** single WebSocket connection shared across managers
133162

134163
### Thread Safety
135164
- **ALWAYS** use appropriate locking mechanisms
@@ -174,28 +203,61 @@ This is a Python SDK/client library for the ProjectX Trading Platform (https://w
174203

175204
## Example Patterns
176205

177-
### Payload Validation
206+
### Async Context Manager Usage
207+
```python
208+
async def main():
209+
async with ProjectX.from_env() as client:
210+
await client.authenticate()
211+
212+
# Use the client
213+
bars = await client.get_bars("MNQ", days=5)
214+
positions = await client.get_positions()
215+
```
216+
217+
### Async Payload Validation
178218
```python
179-
def _validate_quote_payload(self, quote_data: dict) -> bool:
219+
async def _validate_quote_payload(self, quote_data: dict) -> bool:
180220
required_fields = ["symbol", "lastPrice", "bestBid", "bestAsk", "timestamp"]
181221
return all(field in quote_data for field in required_fields)
182222
```
183223

184-
### Time Filtering
224+
### Concurrent Operations
225+
```python
226+
async def fetch_multiple_instruments(symbols: list[str]):
227+
async with ProjectX.from_env() as client:
228+
await client.authenticate()
229+
230+
# Fetch all instruments concurrently
231+
tasks = [client.get_instrument(symbol) for symbol in symbols]
232+
results = await asyncio.gather(*tasks, return_exceptions=True)
233+
234+
return {
235+
symbol: result
236+
for symbol, result in zip(symbols, results)
237+
if not isinstance(result, Exception)
238+
}
239+
```
240+
241+
### Time Filtering with Async
185242
```python
186-
def get_analysis(self, time_window_minutes: int | None = None) -> dict[str, Any]:
187-
trades_to_analyze = self.recent_trades
243+
async def get_analysis(self, time_window_minutes: int | None = None) -> dict[str, Any]:
244+
trades_to_analyze = await self.get_recent_trades()
188245
if time_window_minutes is not None:
189246
cutoff_time = datetime.now(self.timezone) - timedelta(minutes=time_window_minutes)
190247
trades_to_analyze = trades_to_analyze.filter(pl.col("timestamp") >= cutoff_time)
248+
return await self._analyze_trades(trades_to_analyze)
191249
```
192250

193-
### Test Method Structure
251+
### Async Test Method Structure
194252
```python
195-
def test_feature(self, test_params: dict[str, Any] | None = None) -> dict[str, Any]:
196-
# Validate prerequisites
197-
# Run tests with error handling
198-
# Return structured results with validation, performance, recommendations
253+
@pytest.mark.asyncio
254+
async def test_feature(test_params: dict[str, Any] | None = None) -> dict[str, Any]:
255+
async with ProjectX.from_env() as client:
256+
await client.authenticate()
257+
258+
# Validate prerequisites
259+
# Run tests with error handling
260+
# Return structured results
199261
```
200262

201263
These rules ensure consistent ProjectX integration, maintain code quality, and provide clear guidance for future development.

0 commit comments

Comments
 (0)