Skip to content

Commit 37dbdcd

Browse files
authored
Merge pull request #29 from TexasCoding/work_on_examples
Work on examples
2 parents a55c983 + 494cc9d commit 37dbdcd

21 files changed

+1925
-259
lines changed

.grok/GROK.md

Lines changed: 283 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,30 @@ This is a Python SDK/client library for the ProjectX Trading Platform Gateway AP
77

88
**Note**: Focus on toolkit development, not on creating trading strategies.
99

10+
## Project Status: v2.0.4 - Async Architecture
11+
12+
**IMPORTANT**: This project has migrated to a fully asynchronous architecture as of v2.0.0. All APIs are now async-only with no backward compatibility to synchronous versions.
13+
14+
## Development Phase Guidelines
15+
16+
**IMPORTANT**: This project is in active development. When making changes:
17+
18+
1. **No Backward Compatibility**: Do not maintain old implementations for compatibility
19+
2. **Clean Code Priority**: Always refactor to the cleanest, most modern approach
20+
3. **Remove Legacy Code**: Delete old logic when implementing improvements
21+
4. **Breaking Changes Allowed**: Make breaking changes freely to improve architecture
22+
5. **Modern Patterns**: Use the latest Python patterns and best practices
23+
6. **Simplify Aggressively**: Remove complexity rather than adding compatibility layers
24+
7. **Async-First**: All new code must use async/await patterns
25+
26+
Example approach:
27+
- ❌ DON'T: Keep old method signatures with deprecation warnings
28+
- ✅ DO: Replace methods entirely with better implementations
29+
- ❌ DON'T: Add compatibility shims or adapters
30+
- ✅ DO: Update all callers to use new patterns
31+
- ❌ DON'T: Create synchronous wrappers for async methods
32+
- ✅ DO: Use async/await throughout the entire call stack
33+
1034
## Tool Usage Guidelines
1135
As Grok CLI, you have access to tools like view_file, create_file, str_replace_editor, bash, search, and todo lists. Use them efficiently for tasks.
1236

@@ -27,18 +51,272 @@ uv run [command] # Run command in virtual environment
2751
### Testing
2852
uv run pytest # Run all tests
2953
uv run pytest tests/test_client.py # Run specific test file
54+
uv run pytest -m "not slow" # Run tests excluding slow ones
55+
uv run pytest --cov=project_x_py --cov-report=html # Generate coverage report
56+
uv run pytest -k "async" # Run only async tests
57+
58+
### Async Testing Patterns
59+
```python
60+
# Test async methods with pytest-asyncio
61+
import pytest
62+
63+
@pytest.mark.asyncio
64+
async def test_async_method():
65+
async with ProjectX.from_env() as client:
66+
await client.authenticate()
67+
result = await client.get_bars("MNQ", days=1)
68+
assert result is not None
69+
```
3070

3171
### Code Quality
3272
uv run ruff check . # Lint code
3373
uv run ruff check . --fix # Auto-fix linting issues
3474
uv run ruff format . # Format code
3575
uv run mypy src/ # Type checking
3676

77+
### Building and Distribution
78+
uv build # Build wheel and source distribution
79+
uv run python -m build # Alternative build command
80+
3781
## Project Architecture
38-
Refer to CLAUDE.md for details, but when editing:
39-
- Use dependency injection in clients and managers.
40-
- Handle real-time data with WebSockets.
41-
- Ensure thread safety with locks.
82+
83+
### Core Components (v2.0.4 - Multi-file Packages)
84+
85+
**ProjectX Client (`src/project_x_py/client/`)**
86+
- Main async API client for TopStepX ProjectX Gateway
87+
- Modular architecture with specialized modules:
88+
- `auth.py`: Authentication and JWT token management
89+
- `http.py`: Async HTTP client with retry logic
90+
- `cache.py`: Intelligent caching for instruments
91+
- `market_data.py`: Market data operations
92+
- `trading.py`: Trading operations
93+
- `rate_limiter.py`: Async rate limiting
94+
- `base.py`: Base class combining all mixins
95+
96+
**Specialized Managers (All Async)**
97+
- `OrderManager` (`order_manager/`): Comprehensive async order operations
98+
- `core.py`: Main order operations
99+
- `bracket_orders.py`: OCO and bracket order logic
100+
- `position_orders.py`: Position-based order management
101+
- `tracking.py`: Order state tracking
102+
- `PositionManager` (`position_manager/`): Async position tracking and risk management
103+
- `core.py`: Position management core
104+
- `risk.py`: Risk calculations and limits
105+
- `analytics.py`: Performance analytics
106+
- `monitoring.py`: Real-time position monitoring
107+
- `ProjectXRealtimeDataManager` (`realtime_data_manager/`): Async WebSocket data
108+
- `core.py`: Main data manager
109+
- `callbacks.py`: Event callback handling
110+
- `data_processing.py`: OHLCV bar construction
111+
- `memory_management.py`: Efficient data storage
112+
- `OrderBook` (`orderbook/`): Async Level 2 market depth
113+
- `base.py`: Core orderbook functionality
114+
- `analytics.py`: Market microstructure analysis
115+
- `detection.py`: Iceberg and spoofing detection
116+
- `profile.py`: Volume profile analysis
117+
118+
**Technical Indicators (`src/project_x_py/indicators/`)**
119+
- TA-Lib compatible indicator library built on Polars
120+
- 58+ indicators including pattern recognition:
121+
- **Momentum**: RSI, MACD, Stochastic, etc.
122+
- **Overlap**: SMA, EMA, Bollinger Bands, etc.
123+
- **Volatility**: ATR, Keltner Channels, etc.
124+
- **Volume**: OBV, VWAP, Money Flow, etc.
125+
- **Pattern Recognition** (NEW):
126+
- Fair Value Gap (FVG): Price imbalance detection
127+
- Order Block: Institutional order zone identification
128+
- Waddah Attar Explosion: Volatility-based trend strength
129+
- All indicators work with Polars DataFrames for performance
130+
131+
**Configuration System**
132+
- Environment variable based configuration
133+
- JSON config file support (`~/.config/projectx/config.json`)
134+
- ProjectXConfig dataclass for type safety
135+
136+
### Architecture Patterns
137+
138+
**Async Factory Functions**: Use async `create_*` functions for component initialization:
139+
```python
140+
# Async factory pattern (v2.0.0+)
141+
async def setup_trading():
142+
async with ProjectX.from_env() as client:
143+
await client.authenticate()
144+
145+
# Create managers with async patterns
146+
realtime_client = await create_realtime_client(
147+
client.jwt_token,
148+
str(client.account_id)
149+
)
150+
151+
order_manager = create_order_manager(client, realtime_client)
152+
position_manager = create_position_manager(client, realtime_client)
153+
154+
# Or use the all-in-one factory
155+
suite = await create_trading_suite(
156+
instrument="MNQ",
157+
project_x=client,
158+
jwt_token=client.jwt_token,
159+
account_id=client.account_id
160+
)
161+
162+
return suite
163+
```
164+
165+
**Dependency Injection**: Managers receive their dependencies (ProjectX client, realtime client) rather than creating them.
166+
167+
**Real-time Integration**: Single `ProjectXRealtimeClient` instance shared across managers for WebSocket connection efficiency.
168+
169+
**Context Managers**: Always use async context managers for proper resource cleanup:
170+
```python
171+
async with ProjectX.from_env() as client:
172+
# Client automatically handles auth, cleanup
173+
pass
174+
```
175+
176+
### Data Flow
177+
178+
1. **Authentication**: ProjectX client authenticates and provides JWT tokens
179+
2. **Real-time Setup**: Create ProjectXRealtimeClient with JWT for WebSocket connections
180+
3. **Manager Initialization**: Pass clients to specialized managers via dependency injection
181+
4. **Data Processing**: Polars DataFrames used throughout for performance
182+
5. **Event Handling**: Real-time updates flow through WebSocket to respective managers
183+
184+
## Important Technical Details
185+
186+
### Indicator Functions
187+
- All indicators follow TA-Lib naming conventions (uppercase function names allowed in `indicators/__init__.py`)
188+
- Use Polars pipe() method for chaining: `data.pipe(SMA, period=20).pipe(RSI, period=14)`
189+
- Indicators support both class instantiation and direct function calls
190+
191+
### Price Precision
192+
- All price handling uses Decimal for precision
193+
- Automatic tick size alignment in OrderManager
194+
- Price formatting utilities in utils.py
195+
196+
### Error Handling
197+
- Custom exception hierarchy in exceptions.py
198+
- All API errors wrapped in ProjectX-specific exceptions
199+
- Comprehensive error context and retry logic
200+
201+
### Testing Strategy
202+
- Pytest with async support and mocking
203+
- Test markers: unit, integration, slow, realtime
204+
- High test coverage required (configured in pyproject.toml)
205+
- Mock external API calls in unit tests
206+
207+
## Environment Setup
208+
209+
Required environment variables:
210+
- `PROJECT_X_API_KEY`: TopStepX API key
211+
- `PROJECT_X_USERNAME`: TopStepX username
212+
213+
Optional configuration:
214+
- `PROJECTX_API_URL`: Custom API endpoint
215+
- `PROJECTX_TIMEOUT_SECONDS`: Request timeout
216+
- `PROJECTX_RETRY_ATTEMPTS`: Retry attempts
217+
218+
## Performance Optimizations
219+
220+
### Connection Pooling & Caching (client.py)
221+
- HTTP connection pooling with retry strategies for 50-70% fewer connection overhead
222+
- Instrument caching reduces repeated API calls by 80%
223+
- Preemptive JWT token refresh at 80% lifetime prevents authentication delays
224+
- Session-based requests with automatic retry on failures
225+
226+
### Memory Management
227+
- **OrderBook**: Sliding windows with configurable limits (max 10K trades, 1K depth entries)
228+
- **RealtimeDataManager**: Automatic cleanup maintains 1K bars per timeframe
229+
- **Indicators**: LRU cache for repeated calculations (100 entry limit)
230+
- Periodic garbage collection after large data operations
231+
232+
### Optimized DataFrame Operations
233+
- **Chained operations** reduce intermediate DataFrame creation by 30-40%
234+
- **Lazy evaluation** with Polars for better memory efficiency
235+
- **Efficient datetime parsing** with cached timezone objects
236+
- **Vectorized operations** in orderbook analysis
237+
238+
### Performance Monitoring
239+
Use async built-in methods to monitor performance:
240+
```python
241+
# Client performance stats (async)
242+
async with ProjectX.from_env() as client:
243+
await client.authenticate()
244+
245+
# Check performance metrics
246+
stats = await client.get_performance_stats()
247+
print(f"API calls: {stats['api_calls']}")
248+
print(f"Cache hits: {stats['cache_hits']}")
249+
250+
# Health check
251+
health = await client.get_health_status()
252+
253+
# Memory usage monitoring
254+
orderbook_stats = await orderbook.get_memory_stats()
255+
data_manager_stats = await data_manager.get_memory_stats()
256+
```
257+
258+
### Expected Performance Improvements
259+
- **50-70% reduction in API calls** through intelligent caching
260+
- **30-40% faster indicator calculations** via chained operations
261+
- **60% less memory usage** through sliding windows and cleanup
262+
- **Sub-second response times** for cached operations
263+
- **95% reduction in polling** with real-time WebSocket feeds
264+
265+
### Memory Limits (Configurable)
266+
- `max_trades = 10000` (OrderBook trade history)
267+
- `max_depth_entries = 1000` (OrderBook depth per side)
268+
- `max_bars_per_timeframe = 1000` (Real-time data per timeframe)
269+
- `tick_buffer_size = 1000` (Tick data buffer)
270+
- `cache_max_size = 100` (Indicator cache entries)
271+
272+
## Recent Changes
273+
274+
### v2.0.4 - Package Refactoring
275+
- **Major Architecture Change**: Converted monolithic modules to multi-file packages
276+
- All core modules now organized as packages with focused submodules
277+
- Improved code organization, maintainability, and testability
278+
- Backward compatible - all imports work as before
279+
280+
### v2.0.2 - Pattern Recognition Indicators
281+
- Added Fair Value Gap (FVG) indicator for price imbalance detection
282+
- Added Order Block indicator for institutional zone identification
283+
- Added Waddah Attar Explosion for volatility-based trend strength
284+
- All indicators support async data processing
285+
286+
### v2.0.0 - Complete Async Migration
287+
- **Breaking Change**: Entire SDK migrated to async-only architecture
288+
- All methods now require `await` keyword
289+
- Context managers for proper resource management
290+
- No synchronous fallbacks or compatibility layers
291+
292+
### Key Async Examples
293+
```python
294+
# Basic usage
295+
async with ProjectX.from_env() as client:
296+
await client.authenticate()
297+
bars = await client.get_bars("MNQ", days=5)
298+
299+
# Real-time data
300+
async def stream_data():
301+
async with ProjectX.from_env() as client:
302+
await client.authenticate()
303+
304+
realtime = await create_realtime_client(
305+
client.jwt_token,
306+
str(client.account_id)
307+
)
308+
309+
data_manager = create_realtime_data_manager(
310+
"MNQ", client, realtime
311+
)
312+
313+
# Set up callbacks
314+
data_manager.on_bar_received = handle_bar
315+
316+
# Start streaming
317+
await realtime.connect()
318+
await data_manager.start_realtime_feed()
319+
```
42320

43321
## Coding Rules for Edits
44322
When using str_replace_editor:
@@ -56,5 +334,4 @@ When using str_replace_editor:
56334
- Validate payloads strictly.
57335
- Map enums correctly.
58336

59-
For any updates, ensure consistency with .cursorrules and CLAUDE.md.
60-
337+
For any updates, ensure consistency with .cursorrules.

0 commit comments

Comments
 (0)