Skip to content

Commit a3ad4ab

Browse files
authored
Merge pull request #24 from TexasCoding/refactor_v2
feat(v2.0.5): Enterprise-grade error handling and modular architecture refactoring
2 parents 4236fc5 + d354836 commit a3ad4ab

Some content is hidden

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

89 files changed

+6026
-1691
lines changed

CHANGELOG.md

Lines changed: 41 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,47 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
1313
- Old implementations are removed when improved
1414
- Clean, modern code architecture is prioritized
1515

16+
## [2.0.5] - 2025-08-03
17+
18+
### Added
19+
- **🛡️ Centralized Error Handling System**: Comprehensive error handling infrastructure
20+
- `@handle_errors` decorator for consistent error catching and logging
21+
- `@retry_on_network_error` decorator with exponential backoff
22+
- `@handle_rate_limit` decorator for automatic rate limit management
23+
- `@validate_response` decorator for API response validation
24+
- Standardized error messages via `ErrorMessages` constants
25+
- Structured error context with `ErrorContext` manager
26+
27+
- **📊 Enhanced Logging System**: Production-ready structured logging
28+
- `ProjectXLogger` factory for consistent logger configuration
29+
- `LogMessages` constants for standardized log messages
30+
- `LogContext` manager for adding contextual information
31+
- JSON-formatted logging for production environments
32+
- Performance logging utilities for operation timing
33+
- Configurable SDK-wide logging via `configure_sdk_logging()`
34+
35+
### Changed
36+
- **🔄 Complete Error Handling Migration**: All modules now use new error handling patterns
37+
- Phase 1: Authentication and order management
38+
- Phase 2: HTTP client and market data methods
39+
- Phase 3: WebSocket and real-time components
40+
- Phase 4: Position manager and orderbook components
41+
- Phase 5: Cleanup of old error handling code
42+
43+
### Improved
44+
- **✅ Code Quality**: Zero mypy errors and all ruff checks pass
45+
- **🔍 Error Visibility**: Structured logging provides better debugging in production
46+
- **⚡ Reliability**: Automatic retry mechanisms reduce transient failures
47+
- **📈 Monitoring**: JSON logs enable better log aggregation and analysis
48+
- **🛠️ Developer Experience**: Consistent error handling patterns across codebase
49+
50+
### Technical Details
51+
- **Error Decorators**: Applied to 100+ methods across all modules
52+
- **Type Safety**: Full mypy compliance with strict type checking
53+
- **Logging Context**: All operations include structured context (operation, timestamps, IDs)
54+
- **Performance**: Error handling adds minimal overhead (<1ms per operation)
55+
- **Testing**: All error paths covered with comprehensive test cases
56+
1657
## [2.0.4] - 2025-08-02
1758

1859
### Changed

CONTRIBUTING.md

Lines changed: 39 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -67,6 +67,7 @@ This project follows strict code style guidelines to maintain consistency and qu
6767
- Use Python 3.10+ union syntax: `int | None` instead of `Optional[int]`
6868
- Use `isinstance(x, (A | B))` instead of `isinstance(x, (A, B))`
6969
- Use `dict[str, Any]` instead of `Dict[str, Any]`
70+
- Run mypy to ensure type safety: `uv run mypy src/`
7071

7172
### Async/Await
7273
- This project uses an async-first architecture
@@ -80,11 +81,43 @@ This project follows strict code style guidelines to maintain consistency and qu
8081
- Use vectorized operations where possible
8182
- Validate DataFrame schemas before operations
8283

83-
### Error Handling
84-
- Wrap ProjectX API calls in try-catch blocks
85-
- Log errors with context: `self.logger.error(f"Error in {method_name}: {e}")`
86-
- Return meaningful error responses instead of raising exceptions
87-
- Validate input parameters and API data
84+
### Error Handling (v2.0.5+)
85+
86+
Use the centralized error handling system:
87+
88+
1. **Use Error Handling Decorators**
89+
```python
90+
from project_x_py.utils import handle_errors, retry_on_network_error
91+
92+
@handle_errors("operation name")
93+
@retry_on_network_error(max_attempts=3)
94+
async def my_method(self, ...):
95+
# Method implementation
96+
```
97+
98+
2. **Use Structured Logging**
99+
```python
100+
from project_x_py.utils import ProjectXLogger, LogMessages, LogContext
101+
102+
logger = ProjectXLogger.get_logger(__name__)
103+
104+
with LogContext(logger, operation="fetch_data", symbol="MGC"):
105+
logger.info(LogMessages.DATA_FETCH)
106+
```
107+
108+
3. **Use Standardized Error Messages**
109+
```python
110+
from project_x_py.utils import ErrorMessages, format_error_message
111+
112+
raise ProjectXError(
113+
format_error_message(ErrorMessages.ORDER_NOT_FOUND, order_id=order_id)
114+
)
115+
```
116+
117+
4. **Validate Input Parameters**
118+
- Use `@validate_response` decorator for API responses
119+
- Validate parameters at method entry
120+
- Return typed errors with context
88121

89122
## Pull Request Process
90123

@@ -106,6 +139,7 @@ This project follows strict code style guidelines to maintain consistency and qu
106139
```bash
107140
uv run ruff format .
108141
uv run ruff check --fix .
142+
uv run mypy src/
109143
```
110144

111145
6. **Update documentation** to reflect your changes

README.md

Lines changed: 43 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -21,9 +21,20 @@ A **high-performance async Python SDK** for the [ProjectX Trading Platform](http
2121

2222
This Python SDK acts as a bridge between your trading strategies and the ProjectX platform, handling all the complex API interactions, data processing, and real-time connectivity.
2323

24-
## 🚀 v2.0.2 - Async-First Architecture with Enhanced Indicators
24+
## 🚀 v2.0.5 - Enterprise-Grade Error Handling & Logging
2525

26-
**BREAKING CHANGE**: Version 2.0.0 is a complete rewrite with async-only architecture. All synchronous APIs have been removed in favor of high-performance async implementations.
26+
**Latest Update (v2.0.5)**: Enhanced error handling system with centralized logging, structured error messages, and comprehensive retry mechanisms.
27+
28+
### What's New in v2.0.5
29+
30+
- **Centralized Error Handling**: Decorators for consistent error handling across all modules
31+
- **Structured Logging**: JSON-formatted logs with contextual information for production environments
32+
- **Smart Retry Logic**: Automatic retry for network operations with exponential backoff
33+
- **Rate Limit Management**: Built-in rate limit handling with automatic throttling
34+
- **Enhanced Type Safety**: Full mypy compliance with strict type checking
35+
- **Code Quality**: All ruff checks pass with comprehensive linting
36+
37+
**BREAKING CHANGE**: Version 2.0.0 introduced async-only architecture. All synchronous APIs have been removed in favor of high-performance async implementations.
2738

2839
### Why Async?
2940

@@ -63,6 +74,8 @@ async with ProjectX.from_env() as client:
6374
- **Real-time WebSockets**: Async streaming for quotes, trades, and account updates
6475
- **Performance Optimized**: Connection pooling, intelligent caching, memory management
6576
- **Pattern Recognition**: Fair Value Gaps, Order Blocks, and Waddah Attar Explosion indicators
77+
- **Enterprise Error Handling**: Production-ready error handling with decorators and structured logging
78+
- **Comprehensive Testing**: High test coverage with async-safe testing patterns
6679

6780
## 📦 Installation
6881

@@ -308,26 +321,51 @@ data_manager = RealtimeDataManager(
308321
)
309322
```
310323

311-
## 🔍 Error Handling
324+
## 🔍 Error Handling & Logging (v2.0.5+)
312325

313-
All async operations use typed exceptions:
326+
### Structured Error Handling
327+
328+
All async operations use typed exceptions with automatic retry and logging:
314329

315330
```python
316331
from project_x_py.exceptions import (
317332
ProjectXAuthenticationError,
318333
ProjectXOrderError,
319334
ProjectXRateLimitError
320335
)
336+
from project_x_py.utils import configure_sdk_logging
337+
338+
# Configure logging for production
339+
configure_sdk_logging(
340+
level=logging.INFO,
341+
format_json=True, # JSON logs for production
342+
log_file="/var/log/projectx/trading.log"
343+
)
321344

322345
try:
323346
async with ProjectX.from_env() as client:
324-
await client.authenticate()
347+
await client.authenticate() # Automatic retry on network errors
325348
except ProjectXAuthenticationError as e:
349+
# Structured error with context
326350
print(f"Authentication failed: {e}")
327351
except ProjectXRateLimitError as e:
352+
# Automatic backoff already attempted
328353
print(f"Rate limit exceeded: {e}")
329354
```
330355

356+
### Error Handling Decorators
357+
358+
The SDK uses decorators for consistent error handling:
359+
360+
```python
361+
# All API methods have built-in error handling
362+
@handle_errors("place order")
363+
@retry_on_network_error(max_attempts=3)
364+
@validate_response(required_fields=["orderId"])
365+
async def place_order(self, ...):
366+
# Method implementation
367+
```
368+
331369
## 🤝 Contributing
332370

333371
We welcome contributions! Please see [CONTRIBUTING.md](CONTRIBUTING.md) for guidelines.

0 commit comments

Comments
 (0)