|
| 1 | +""" |
| 2 | +Statistics tracking mixin for consistent error and memory tracking. |
| 3 | +
|
| 4 | +Author: SDK v3.1.14 |
| 5 | +Date: 2025-01-17 |
| 6 | +""" |
| 7 | + |
| 8 | +import sys |
| 9 | +import time |
| 10 | +import traceback |
| 11 | +from collections import deque |
| 12 | +from datetime import datetime |
| 13 | +from typing import Any, Optional |
| 14 | + |
| 15 | + |
| 16 | +class StatsTrackingMixin: |
| 17 | + """ |
| 18 | + Mixin for tracking errors, memory usage, and activity across managers. |
| 19 | +
|
| 20 | + Provides consistent error tracking, memory usage monitoring, and activity |
| 21 | + timestamps for all manager components in TradingSuite. |
| 22 | + """ |
| 23 | + |
| 24 | + def _init_stats_tracking(self, max_errors: int = 100) -> None: |
| 25 | + """ |
| 26 | + Initialize statistics tracking attributes. |
| 27 | +
|
| 28 | + Args: |
| 29 | + max_errors: Maximum number of errors to retain in history |
| 30 | + """ |
| 31 | + self._error_count = 0 |
| 32 | + self._error_history: deque[dict[str, Any]] = deque(maxlen=max_errors) |
| 33 | + self._last_activity: Optional[datetime] = None |
| 34 | + self._start_time = time.time() |
| 35 | + |
| 36 | + def _track_error( |
| 37 | + self, |
| 38 | + error: Exception, |
| 39 | + context: Optional[str] = None, |
| 40 | + details: Optional[dict[str, Any]] = None, |
| 41 | + ) -> None: |
| 42 | + """ |
| 43 | + Track an error occurrence. |
| 44 | +
|
| 45 | + Args: |
| 46 | + error: The exception that occurred |
| 47 | + context: Optional context about where/why the error occurred |
| 48 | + details: Optional additional details about the error |
| 49 | + """ |
| 50 | + self._error_count += 1 |
| 51 | + self._error_history.append( |
| 52 | + { |
| 53 | + "timestamp": datetime.now(), |
| 54 | + "error_type": type(error).__name__, |
| 55 | + "message": str(error), |
| 56 | + "context": context, |
| 57 | + "details": details, |
| 58 | + "traceback": traceback.format_exc() |
| 59 | + if hasattr(error, "__traceback__") |
| 60 | + else None, |
| 61 | + } |
| 62 | + ) |
| 63 | + |
| 64 | + def _update_activity(self) -> None: |
| 65 | + """Update the last activity timestamp.""" |
| 66 | + self._last_activity = datetime.now() |
| 67 | + |
| 68 | + def get_memory_usage_mb(self) -> float: |
| 69 | + """ |
| 70 | + Get estimated memory usage of this component in MB. |
| 71 | +
|
| 72 | + Returns: |
| 73 | + Estimated memory usage in megabytes |
| 74 | + """ |
| 75 | + # Get size of key attributes |
| 76 | + size = 0 |
| 77 | + |
| 78 | + # Check common attributes |
| 79 | + attrs_to_check = [ |
| 80 | + "_orders", |
| 81 | + "_positions", |
| 82 | + "_trades", |
| 83 | + "_data", |
| 84 | + "_order_history", |
| 85 | + "_position_history", |
| 86 | + "_managed_tasks", |
| 87 | + "_persistent_tasks", |
| 88 | + "stats", |
| 89 | + "_error_history", |
| 90 | + ] |
| 91 | + |
| 92 | + for attr_name in attrs_to_check: |
| 93 | + if hasattr(self, attr_name): |
| 94 | + attr = getattr(self, attr_name) |
| 95 | + size += sys.getsizeof(attr) |
| 96 | + |
| 97 | + # For collections, also count items |
| 98 | + if isinstance(attr, (list, dict, set, deque)): |
| 99 | + try: |
| 100 | + for item in attr.values() if isinstance(attr, dict) else attr: |
| 101 | + size += sys.getsizeof(item) |
| 102 | + except: |
| 103 | + pass # Skip if iteration fails |
| 104 | + |
| 105 | + # Convert to MB |
| 106 | + return size / (1024 * 1024) |
| 107 | + |
| 108 | + def get_error_stats(self) -> dict[str, Any]: |
| 109 | + """ |
| 110 | + Get error statistics. |
| 111 | +
|
| 112 | + Returns: |
| 113 | + Dictionary with error statistics |
| 114 | + """ |
| 115 | + recent_errors = list(self._error_history)[-10:] # Last 10 errors |
| 116 | + |
| 117 | + # Count errors by type |
| 118 | + error_types: dict[str, int] = {} |
| 119 | + for error in self._error_history: |
| 120 | + error_type = error["error_type"] |
| 121 | + error_types[error_type] = error_types.get(error_type, 0) + 1 |
| 122 | + |
| 123 | + return { |
| 124 | + "total_errors": self._error_count, |
| 125 | + "recent_errors": recent_errors, |
| 126 | + "error_types": error_types, |
| 127 | + "last_error": recent_errors[-1] if recent_errors else None, |
| 128 | + } |
| 129 | + |
| 130 | + def get_activity_stats(self) -> dict[str, Any]: |
| 131 | + """ |
| 132 | + Get activity statistics. |
| 133 | +
|
| 134 | + Returns: |
| 135 | + Dictionary with activity statistics |
| 136 | + """ |
| 137 | + uptime = time.time() - self._start_time |
| 138 | + |
| 139 | + return { |
| 140 | + "uptime_seconds": uptime, |
| 141 | + "last_activity": self._last_activity, |
| 142 | + "is_active": self._last_activity is not None |
| 143 | + and (datetime.now() - self._last_activity).total_seconds() < 60, |
| 144 | + } |
0 commit comments