Skip to content

Commit b6863db

Browse files
TexasCodingclaude
andcommitted
refactor: Complete Phase 1 & 2 - Order tracking consolidation and async task management
Phase 1: Order Tracking Consolidation - Deprecated order_tracker.py module in favor of TradingSuite methods - Added deprecation warnings to OrderTracker and OrderChainBuilder classes - Created MIGRATION.md with clear migration paths and examples - Updated imports to maintain backward compatibility until v4.0.0 - Added comprehensive deprecation tests Phase 2: Async Task Management - Created TaskManagerMixin for centralized async task lifecycle management - Implemented proper task tracking with WeakSet and persistent task sets - Added automatic task cleanup on disconnect/exit - Fixed memory leaks from untracked asyncio.create_task() calls - Updated EventHandlingMixin and MemoryManagementMixin to use TaskManagerMixin - Added comprehensive task management tests with 100% coverage Additional improvements: - Updated CLAUDE.md with MCP server integration documentation - Fixed type hints in mixins to work properly with mypy/pyright - Removed unnecessary type annotations causing linting issues - All tests passing, no ruff/mypy errors BREAKING CHANGES: None (backward compatible until v4.0.0) 🤖 Generated with [Claude Code](https://claude.ai/code) Co-Authored-By: Claude <noreply@anthropic.com>
1 parent 39043ea commit b6863db

File tree

10 files changed

+875
-62
lines changed

10 files changed

+875
-62
lines changed

CLAUDE.md

Lines changed: 115 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -244,6 +244,121 @@ Optional configuration:
244244
- `PROJECTX_TIMEOUT_SECONDS`: Request timeout
245245
- `PROJECTX_RETRY_ATTEMPTS`: Retry attempts
246246

247+
## MCP Server Integration
248+
249+
Several MCP (Model Context Protocol) servers are available to enhance development workflow:
250+
251+
### Essential Development MCPs
252+
253+
#### Memory Bank (`mcp__aakarsh-sasi-memory-bank-mcp`)
254+
Tracks development progress and maintains context across sessions:
255+
```python
256+
# Track feature implementation progress
257+
await mcp__aakarsh_sasi_memory_bank_mcp__track_progress(
258+
action="Implemented bracket order system",
259+
description="Added OCO and bracket order support with automatic stop/target placement"
260+
)
261+
262+
# Log architectural decisions
263+
await mcp__aakarsh_sasi_memory_bank_mcp__log_decision(
264+
title="Event System Architecture",
265+
context="Need unified event handling across components",
266+
decision="Implement EventBus with async handlers and priority support",
267+
alternatives=["Direct callbacks", "Observer pattern", "Pub/sub with Redis"],
268+
consequences=["Better decoupling", "Easier testing", "Slight performance overhead"]
269+
)
270+
271+
# Switch development modes
272+
await mcp__aakarsh_sasi_memory_bank_mcp__switch_mode("debug") # architect, code, debug, test
273+
```
274+
275+
#### Knowledge Graph (`mcp__itseasy-21-mcp-knowledge-graph`)
276+
Maps component relationships and data flow:
277+
```python
278+
# Map trading system relationships
279+
await mcp__itseasy_21_mcp_knowledge_graph__create_entities(
280+
entities=[
281+
{"name": "TradingSuite", "entityType": "Core",
282+
"observations": ["Central orchestrator", "Manages all components"]},
283+
{"name": "OrderManager", "entityType": "Manager",
284+
"observations": ["Handles order lifecycle", "Supports bracket orders"]}
285+
]
286+
)
287+
288+
await mcp__itseasy_21_mcp_knowledge_graph__create_relations(
289+
relations=[
290+
{"from": "TradingSuite", "to": "OrderManager", "relationType": "manages"},
291+
{"from": "OrderManager", "to": "ProjectXClient", "relationType": "uses"}
292+
]
293+
)
294+
```
295+
296+
#### Clear Thought Reasoning (`mcp__waldzellai-clear-thought`)
297+
For complex problem-solving and architecture decisions:
298+
```python
299+
# Analyze performance bottlenecks
300+
await mcp__waldzellai_clear_thought__clear_thought(
301+
operation="debugging_approach",
302+
prompt="WebSocket connection dropping under high message volume",
303+
context="Real-time data manager processing 1000+ ticks/second"
304+
)
305+
306+
# Plan refactoring strategy
307+
await mcp__waldzellai_clear_thought__clear_thought(
308+
operation="systems_thinking",
309+
prompt="Refactor monolithic client into modular mixins",
310+
context="Need better separation of concerns without breaking existing API"
311+
)
312+
```
313+
314+
### Documentation & Research MCPs
315+
316+
#### Project Documentation (`mcp__project-x-py_Docs`)
317+
Quick access to project-specific documentation:
318+
```python
319+
# Search project documentation
320+
await mcp__project_x_py_Docs__search_project_x_py_documentation(
321+
query="bracket order implementation"
322+
)
323+
324+
# Search codebase
325+
await mcp__project_x_py_Docs__search_project_x_py_code(
326+
query="async def place_bracket_order"
327+
)
328+
```
329+
330+
#### External Research (`mcp__tavily-mcp`)
331+
Research trading APIs and async patterns:
332+
```python
333+
# Search for solutions
334+
await mcp__tavily_mcp__tavily_search(
335+
query="python asyncio websocket reconnection pattern futures trading",
336+
max_results=5,
337+
search_depth="advanced"
338+
)
339+
340+
# Extract documentation
341+
await mcp__tavily_mcp__tavily_extract(
342+
urls=["https://docs.python.org/3/library/asyncio-task.html"],
343+
format="markdown"
344+
)
345+
```
346+
347+
### Best Practices for MCP Usage
348+
349+
1. **Memory Bank**: Update after completing significant features or making architectural decisions
350+
2. **Knowledge Graph**: Maintain when adding new components or changing relationships
351+
3. **Clear Thought**: Use for complex debugging, performance analysis, or architecture planning
352+
4. **Documentation MCPs**: Reference before implementing new features to understand existing patterns
353+
354+
### When to Use Each MCP
355+
356+
- **Starting a new feature**: Check Memory Bank for context, use Clear Thought for planning
357+
- **Debugging complex issues**: Clear Thought for analysis, Knowledge Graph for understanding relationships
358+
- **Making architectural decisions**: Log with Memory Bank, analyze with Clear Thought
359+
- **Understanding existing code**: Project Docs for internal code, Tavily for external research
360+
- **Tracking progress**: Memory Bank for TODO tracking and progress updates
361+
247362
## Performance Optimizations
248363

249364
### Connection Pooling & Caching (client.py)

MIGRATION.md

Lines changed: 70 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,70 @@
1+
# Migration Guide
2+
3+
## v3.1.14 - Order Tracking Consolidation
4+
5+
### Overview
6+
The `order_tracker.py` module has been deprecated in favor of using the integrated methods in `TradingSuite`. This change simplifies the API and reduces code duplication.
7+
8+
### Deprecated Components
9+
- `OrderTracker` class from `project_x_py.order_tracker`
10+
- `OrderChainBuilder` class from `project_x_py.order_tracker`
11+
- `track_order()` function from `project_x_py.order_tracker`
12+
13+
These will be removed in v4.0.0 (expected Q2 2025).
14+
15+
### Migration Path
16+
17+
#### OrderTracker
18+
**Old way:**
19+
```python
20+
from project_x_py.order_tracker import OrderTracker
21+
22+
async with OrderTracker(suite) as tracker:
23+
order = await suite.orders.place_limit_order(...)
24+
tracker.track(order)
25+
filled = await tracker.wait_for_fill()
26+
```
27+
28+
**New way (no import needed):**
29+
```python
30+
# OrderTracker is accessed directly from TradingSuite
31+
async with suite.track_order() as tracker:
32+
order = await suite.orders.place_limit_order(...)
33+
tracker.track(order)
34+
filled = await tracker.wait_for_fill()
35+
```
36+
37+
#### OrderChainBuilder
38+
**Old way:**
39+
```python
40+
from project_x_py.order_tracker import OrderChainBuilder
41+
42+
chain = OrderChainBuilder(suite)
43+
chain.market_order(size=2).with_stop_loss(offset=50)
44+
result = await chain.execute()
45+
```
46+
47+
**New way (no import needed):**
48+
```python
49+
# OrderChainBuilder is accessed directly from TradingSuite
50+
chain = suite.order_chain()
51+
chain.market_order(size=2).with_stop_loss(offset=50)
52+
result = await chain.execute()
53+
```
54+
55+
### Benefits of Migration
56+
1. **Simpler API**: No need to import separate classes
57+
2. **Better integration**: Direct access through TradingSuite
58+
3. **Reduced confusion**: Single source of truth for order tracking
59+
4. **Type safety**: Better IDE support with integrated methods
60+
61+
### Backward Compatibility
62+
The deprecated classes are still available and will continue to work until v4.0.0. However, they will emit deprecation warnings when used.
63+
64+
### Timeline
65+
- **v3.1.14** (Current): Deprecation warnings added
66+
- **v3.2.0**: Documentation will be updated to use new patterns
67+
- **v4.0.0**: Deprecated classes will be removed
68+
69+
### Questions?
70+
If you have any questions about this migration, please open an issue on GitHub.

src/project_x_py/__init__.py

Lines changed: 5 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -170,10 +170,13 @@
170170
ScalpingTemplate,
171171
get_template,
172172
)
173+
174+
# Deprecated: These are re-exported for backward compatibility only
175+
# Use TradingSuite.track_order() and TradingSuite.order_chain() instead
173176
from project_x_py.order_tracker import (
174-
OrderChainBuilder,
177+
OrderChainBuilder, # Deprecated: Use TradingSuite.order_chain()
175178
OrderLifecycleError,
176-
OrderTracker,
179+
OrderTracker, # Deprecated: Use TradingSuite.track_order()
177180
)
178181
from project_x_py.orderbook import (
179182
OrderBook,

src/project_x_py/order_tracker.py

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,9 @@
11
"""
22
Order lifecycle tracking and management for ProjectX SDK v3.0.0.
33
4+
DEPRECATED: This module is deprecated as of v3.1.14 and will be removed in v4.0.0.
5+
Use TradingSuite.track_order() and TradingSuite.order_chain() instead.
6+
47
Author: SDK v3.0.0
58
Date: 2025-08-04
69
@@ -69,10 +72,16 @@
6972
logger = logging.getLogger(__name__)
7073

7174

75+
@deprecated(
76+
"OrderTracker is deprecated. Use TradingSuite.track_order() instead. "
77+
"Will be removed in v4.0.0"
78+
)
7279
class OrderTracker:
7380
"""
7481
Context manager for comprehensive order lifecycle tracking.
7582
83+
DEPRECATED: Use TradingSuite.track_order() instead. Will be removed in v4.0.0.
84+
7685
Provides automatic order state management with async waiting capabilities,
7786
eliminating the need for manual order status polling and complex state
7887
tracking in trading strategies.
@@ -361,10 +370,16 @@ def is_terminal(self) -> bool:
361370
) # FILLED, CANCELLED, EXPIRED, REJECTED
362371

363372

373+
@deprecated(
374+
"OrderChainBuilder is deprecated. Use TradingSuite.order_chain() instead. "
375+
"Will be removed in v4.0.0"
376+
)
364377
class OrderChainBuilder:
365378
"""
366379
Fluent API for building complex order chains.
367380
381+
DEPRECATED: Use TradingSuite.order_chain() instead. Will be removed in v4.0.0.
382+
368383
Allows creating multi-part orders (entry + stops + targets) with a
369384
clean, chainable syntax that's easy to read and maintain.
370385

0 commit comments

Comments
 (0)