Skip to content

Commit 36600fc

Browse files
TexasCodingclaude
andcommitted
feat(orderbook): implement dynamic tick size detection with client integration
- Add optional ProjectX client parameter to OrderBook constructor - Implement _fetch_instrument_tick_size() method for cached instrument metadata - Enhance _calculate_price_tolerance() to use cached tick size (3x multiplier) - Update create_orderbook() factory function to accept project_x parameter - Eliminate repeated get_instrument() API calls during cluster detection - Maintain backward compatibility with fallback to hardcoded tick sizes Performance improvements: - Single API call during initialization vs repeated calls per method - Cached tick size ensures consistent analysis throughout lifecycle - Accurate price tolerance based on real instrument metadata Updated documentation: - README.md: Enhanced OrderBook section with client integration example - CHANGELOG.md: Added v1.1.2 release notes - docs/api/orderbook.rst: Updated Quick Start with proper initialization 🤖 Generated with [Claude Code](https://claude.ai/code) Co-Authored-By: Claude <[email protected]>
1 parent 6d1127a commit 36600fc

34 files changed

+1331
-272
lines changed

.gitignore

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,7 @@
22
__pycache__/
33
*.py[cod]
44
*$py.class
5-
5+
.grok/settings.json
66
# C extensions
77
*.so
88

.grok/GROK.md

Lines changed: 60 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,60 @@
1+
# GROK.md
2+
3+
This file provides guidance to Grok CLI (x.ai/grok) when assisting with file editing, coding tasks, and system operations in this repository.
4+
5+
## Project Overview
6+
This is a Python SDK/client library for the ProjectX Trading Platform Gateway API. It enables developers to build trading strategies with access to real-time market data, order management, and analysis using Polars for high-performance data processing.
7+
8+
**Note**: Focus on toolkit development, not on creating trading strategies.
9+
10+
## Tool Usage Guidelines
11+
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.
12+
13+
- **ALWAYS** create a todo list for complex tasks.
14+
- **NEVER** overwrite existing files with create_file; use str_replace_editor.
15+
- **ALWAYS** view files before editing.
16+
- For searches, use the search tool or bash commands like grep.
17+
18+
## Development Commands
19+
Use bash tool to execute these:
20+
21+
### Package Management (UV)
22+
uv add [package] # Add a dependency
23+
uv add --dev [package] # Add a development dependency
24+
uv sync # Install/sync dependencies
25+
uv run [command] # Run command in virtual environment
26+
27+
### Testing
28+
uv run pytest # Run all tests
29+
uv run pytest tests/test_client.py # Run specific test file
30+
31+
### Code Quality
32+
uv run ruff check . # Lint code
33+
uv run ruff check . --fix # Auto-fix linting issues
34+
uv run ruff format . # Format code
35+
uv run mypy src/ # Type checking
36+
37+
## 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.
42+
43+
## Coding Rules for Edits
44+
When using str_replace_editor:
45+
- **ALWAYS** use modern Python 3.10+ features.
46+
- **PREFER** Polars over Pandas.
47+
- **ALWAYS** add type hints using | for unions.
48+
- **HANDLE** errors with custom exceptions.
49+
50+
## Performance Considerations
51+
- Implement memory management in edits (e.g., sliding windows).
52+
- Optimize DataFrame operations with chaining and lazy evaluation.
53+
54+
## Integration with ProjectX API
55+
- Use configurable endpoints.
56+
- Validate payloads strictly.
57+
- Map enums correctly.
58+
59+
For any updates, ensure consistency with .cursorrules and CLAUDE.md.
60+

CHANGELOG.md

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,23 @@ All notable changes to the ProjectX Python client will be documented in this fil
55
The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/),
66
and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
77

8+
## [1.1.2] - 2025-01-28
9+
10+
### Enhanced
11+
- **🚀 OrderBook Performance Optimization**: Significant performance improvements for cluster detection
12+
- **Dynamic Tick Size Detection**: OrderBook now uses real instrument metadata from ProjectX client
13+
- **Cached Instrument Data**: Tick size fetched once during initialization, eliminating repeated API calls
14+
- **Improved Cluster Analysis**: More accurate price tolerance based on actual instrument tick sizes
15+
- **Backward Compatibility**: Maintains fallback to hardcoded values when client unavailable
16+
- **🔧 Factory Function Updates**: Enhanced `create_orderbook()` to accept ProjectX client reference
17+
- **Better Integration**: OrderBook now integrates seamlessly with ProjectX client architecture
18+
- **Dependency Injection**: Proper client reference passing for instrument metadata access
19+
20+
### Fixed
21+
- **⚡ API Call Reduction**: Eliminated redundant `get_instrument()` calls during cluster detection
22+
- **🎯 Price Tolerance Accuracy**: Fixed hardcoded tick size assumptions with dynamic instrument lookup
23+
- **📊 Consistent Analysis**: OrderBook methods now use consistent, accurate tick size throughout lifecycle
24+
825
## [1.1.0] - 2025-01-27
926

1027
### Added

README.md

Lines changed: 7 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -22,13 +22,13 @@ This Python SDK acts as a bridge between your trading strategies and the Project
2222

2323
## 📊 SDK Status
2424

25-
**Current Version**: v1.1.1 (Documentation Accuracy & Enhanced Project Structure)
25+
**Current Version**: v1.1.2 (Documentation Accuracy & Enhanced Project Structure)
2626

2727
**Production Ready SDK Components**:
2828
- Complete ProjectX Gateway API integration with connection pooling
2929
- Historical and real-time market data APIs with intelligent caching
3030
- 55+ technical indicators with computation caching (Full TA-Lib compatibility)
31-
- Institutional-grade orderbook analysis tools with memory management
31+
- Institutional-grade orderbook analysis tools with memory management and dynamic tick size detection
3232
- Portfolio and risk management APIs
3333
- **NEW**: 50-70% performance improvements through optimization
3434
- **NEW**: 60% memory usage reduction with sliding windows
@@ -296,10 +296,11 @@ for order in orders:
296296

297297
### Level 2 Market Depth Analysis
298298
```python
299-
from project_x_py import create_orderbook
299+
from project_x_py import create_orderbook, ProjectX
300300

301-
# Create orderbook with memory management
302-
orderbook = create_orderbook("MGC")
301+
# Create orderbook with dynamic tick size detection
302+
client = ProjectX.from_env()
303+
orderbook = create_orderbook("MGC", project_x=client) # Uses real instrument metadata
303304

304305
# Process market depth data (automatically from WebSocket)
305306
depth_snapshot = orderbook.get_orderbook_snapshot()
@@ -605,7 +606,7 @@ We welcome contributions! Please follow these guidelines:
605606

606607
## 📝 Changelog
607608

608-
### Version 1.1.1 (Latest)
609+
### Version 1.1.2 (Latest)
609610
**📊 Documentation Accuracy & Enhanced Project Structure**
610611
-**Documentation Alignment**: Updated all documentation to match actual codebase
611612
-**Version Consistency**: Corrected version references throughout project

docs/api/orderbook.rst

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -21,11 +21,11 @@ Quick Start
2121

2222
.. code-block:: python
2323
24-
from project_x_py import ProjectX, OrderBook
24+
from project_x_py import ProjectX, create_orderbook
2525
26-
# Create client and orderbook
26+
# Create client and orderbook with dynamic tick size detection
2727
client = ProjectX.from_env()
28-
orderbook = OrderBook("MGC")
28+
orderbook = create_orderbook("MGC", project_x=client) # Uses real instrument metadata
2929
3030
# Get real-time market depth (requires real-time data subscription)
3131
snapshot = orderbook.get_orderbook_snapshot(levels=10)

docs/conf.py

Lines changed: 3 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,6 @@
33
# For the full list of built-in configuration values, see the documentation:
44
# https://www.sphinx-doc.org/en/master/usage/configuration.html
55

6-
import os
76
import sys
87
from pathlib import Path
98

@@ -24,8 +23,8 @@
2423
project = "project-x-py"
2524
copyright = "2025, Jeff West"
2625
author = "Jeff West"
27-
release = "1.1.1"
28-
version = "1.1.1"
26+
release = "1.1.2"
27+
version = "1.1.2"
2928

3029
# -- General configuration ---------------------------------------------------
3130

@@ -199,7 +198,7 @@
199198

200199
# SEO
201200
html_title = f"ProjectX Python SDK {version} documentation"
202-
html_short_title = f"ProjectX Python SDK docs"
201+
html_short_title = "ProjectX Python SDK docs"
203202

204203
# GitHub integration
205204
html_context = {

examples/04_realtime_data.py

Lines changed: 24 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -229,13 +229,10 @@ def monitor_realtime_feed(data_manager, duration_seconds=60):
229229
# Health check
230230
try:
231231
health = data_manager.health_check()
232-
if health.get("status") == "healthy":
232+
if health:
233233
print(" ✅ System Health: Good")
234234
else:
235-
issues = health.get("issues", [])
236235
print(" ⚠️ System Health: Issues detected")
237-
for issue in issues:
238-
print(f" • {issue}")
239236
except Exception as e:
240237
print(f" ❌ Health check error: {e}")
241238

@@ -265,6 +262,10 @@ def main():
265262
print("🚀 Real-time Data Streaming Example")
266263
print("=" * 60)
267264

265+
# Initialize variables for cleanup
266+
data_manager = None
267+
realtime_client = None
268+
268269
try:
269270
# Initialize client
270271
print("🔑 Initializing ProjectX client...")
@@ -286,6 +287,16 @@ def main():
286287
try:
287288
jwt_token = client.get_session_token()
288289
realtime_client = create_realtime_client(jwt_token, str(account.id))
290+
291+
# Connect the realtime client
292+
print(" Connecting to real-time WebSocket feeds...")
293+
if realtime_client.connect():
294+
print(" ✅ Real-time client connected successfully")
295+
else:
296+
print(
297+
" ⚠️ Real-time client connection failed - continuing with limited functionality"
298+
)
299+
289300
data_manager = create_data_manager(
290301
instrument="MNQ",
291302
project_x=client,
@@ -451,14 +462,22 @@ def main():
451462
return False
452463
finally:
453464
# Cleanup
454-
if "data_manager" in locals():
465+
if data_manager is not None:
455466
try:
456467
print("\n🧹 Stopping real-time feed...")
457468
data_manager.stop_realtime_feed()
458469
print("✅ Real-time feed stopped")
459470
except Exception as e:
460471
print(f"⚠️ Stop feed warning: {e}")
461472

473+
if realtime_client is not None:
474+
try:
475+
print("🧹 Disconnecting real-time client...")
476+
realtime_client.disconnect()
477+
print("✅ Real-time client disconnected")
478+
except Exception as e:
479+
print(f"⚠️ Disconnect warning: {e}")
480+
462481

463482
if __name__ == "__main__":
464483
success = main()

0 commit comments

Comments
 (0)