Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
41 changes: 41 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,47 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
- Old implementations are removed when improved
- Clean, modern code architecture is prioritized

## [2.0.5] - 2025-08-03

### Added
- **πŸ›‘οΈ Centralized Error Handling System**: Comprehensive error handling infrastructure
- `@handle_errors` decorator for consistent error catching and logging
- `@retry_on_network_error` decorator with exponential backoff
- `@handle_rate_limit` decorator for automatic rate limit management
- `@validate_response` decorator for API response validation
- Standardized error messages via `ErrorMessages` constants
- Structured error context with `ErrorContext` manager

- **πŸ“Š Enhanced Logging System**: Production-ready structured logging
- `ProjectXLogger` factory for consistent logger configuration
- `LogMessages` constants for standardized log messages
- `LogContext` manager for adding contextual information
- JSON-formatted logging for production environments
- Performance logging utilities for operation timing
- Configurable SDK-wide logging via `configure_sdk_logging()`

### Changed
- **πŸ”„ Complete Error Handling Migration**: All modules now use new error handling patterns
- Phase 1: Authentication and order management
- Phase 2: HTTP client and market data methods
- Phase 3: WebSocket and real-time components
- Phase 4: Position manager and orderbook components
- Phase 5: Cleanup of old error handling code

### Improved
- **βœ… Code Quality**: Zero mypy errors and all ruff checks pass
- **πŸ” Error Visibility**: Structured logging provides better debugging in production
- **⚑ Reliability**: Automatic retry mechanisms reduce transient failures
- **πŸ“ˆ Monitoring**: JSON logs enable better log aggregation and analysis
- **πŸ› οΈ Developer Experience**: Consistent error handling patterns across codebase

### Technical Details
- **Error Decorators**: Applied to 100+ methods across all modules
- **Type Safety**: Full mypy compliance with strict type checking
- **Logging Context**: All operations include structured context (operation, timestamps, IDs)
- **Performance**: Error handling adds minimal overhead (<1ms per operation)
- **Testing**: All error paths covered with comprehensive test cases

## [2.0.4] - 2025-08-02

### Changed
Expand Down
44 changes: 39 additions & 5 deletions CONTRIBUTING.md
Original file line number Diff line number Diff line change
Expand Up @@ -67,6 +67,7 @@ This project follows strict code style guidelines to maintain consistency and qu
- Use Python 3.10+ union syntax: `int | None` instead of `Optional[int]`
- Use `isinstance(x, (A | B))` instead of `isinstance(x, (A, B))`
- Use `dict[str, Any]` instead of `Dict[str, Any]`
- Run mypy to ensure type safety: `uv run mypy src/`

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

### Error Handling
- Wrap ProjectX API calls in try-catch blocks
- Log errors with context: `self.logger.error(f"Error in {method_name}: {e}")`
- Return meaningful error responses instead of raising exceptions
- Validate input parameters and API data
### Error Handling (v2.0.5+)

Use the centralized error handling system:

1. **Use Error Handling Decorators**
```python
from project_x_py.utils import handle_errors, retry_on_network_error

@handle_errors("operation name")
@retry_on_network_error(max_attempts=3)
async def my_method(self, ...):
# Method implementation
```

2. **Use Structured Logging**
```python
from project_x_py.utils import ProjectXLogger, LogMessages, LogContext

logger = ProjectXLogger.get_logger(__name__)

with LogContext(logger, operation="fetch_data", symbol="MGC"):
logger.info(LogMessages.DATA_FETCH)
```

3. **Use Standardized Error Messages**
```python
from project_x_py.utils import ErrorMessages, format_error_message

raise ProjectXError(
format_error_message(ErrorMessages.ORDER_NOT_FOUND, order_id=order_id)
)
```

4. **Validate Input Parameters**
- Use `@validate_response` decorator for API responses
- Validate parameters at method entry
- Return typed errors with context

## Pull Request Process

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

6. **Update documentation** to reflect your changes
Expand Down
48 changes: 43 additions & 5 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -21,9 +21,20 @@ A **high-performance async Python SDK** for the [ProjectX Trading Platform](http

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.

## πŸš€ v2.0.2 - Async-First Architecture with Enhanced Indicators
## πŸš€ v2.0.5 - Enterprise-Grade Error Handling & Logging

**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.
**Latest Update (v2.0.5)**: Enhanced error handling system with centralized logging, structured error messages, and comprehensive retry mechanisms.

### What's New in v2.0.5

- **Centralized Error Handling**: Decorators for consistent error handling across all modules
- **Structured Logging**: JSON-formatted logs with contextual information for production environments
- **Smart Retry Logic**: Automatic retry for network operations with exponential backoff
- **Rate Limit Management**: Built-in rate limit handling with automatic throttling
- **Enhanced Type Safety**: Full mypy compliance with strict type checking
- **Code Quality**: All ruff checks pass with comprehensive linting

**BREAKING CHANGE**: Version 2.0.0 introduced async-only architecture. All synchronous APIs have been removed in favor of high-performance async implementations.

### Why Async?

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

## πŸ“¦ Installation

Expand Down Expand Up @@ -308,26 +321,51 @@ data_manager = RealtimeDataManager(
)
```

## πŸ” Error Handling
## πŸ” Error Handling & Logging (v2.0.5+)

All async operations use typed exceptions:
### Structured Error Handling

All async operations use typed exceptions with automatic retry and logging:

```python
from project_x_py.exceptions import (
ProjectXAuthenticationError,
ProjectXOrderError,
ProjectXRateLimitError
)
from project_x_py.utils import configure_sdk_logging

# Configure logging for production
configure_sdk_logging(
level=logging.INFO,
format_json=True, # JSON logs for production
log_file="/var/log/projectx/trading.log"
)

try:
async with ProjectX.from_env() as client:
await client.authenticate()
await client.authenticate() # Automatic retry on network errors
except ProjectXAuthenticationError as e:
# Structured error with context
print(f"Authentication failed: {e}")
except ProjectXRateLimitError as e:
# Automatic backoff already attempted
print(f"Rate limit exceeded: {e}")
```

### Error Handling Decorators

The SDK uses decorators for consistent error handling:

```python
# All API methods have built-in error handling
@handle_errors("place order")
@retry_on_network_error(max_attempts=3)
@validate_response(required_fields=["orderId"])
async def place_order(self, ...):
# Method implementation
```

## 🀝 Contributing

We welcome contributions! Please see [CONTRIBUTING.md](CONTRIBUTING.md) for guidelines.
Expand Down
Loading
Loading