-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathnotification_system.py
More file actions
380 lines (322 loc) · 11.1 KB
/
notification_system.py
File metadata and controls
380 lines (322 loc) · 11.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
"""
Notification System Module
Provides alert and notification capabilities for trading events.
"""
from typing import List, Dict, Any, Optional, Callable
from datetime import datetime
from enum import Enum
import queue
import threading
from logger import system_logger, trading_logger
class NotificationLevel(Enum):
"""Notification severity levels."""
INFO = "INFO"
WARNING = "WARNING"
ERROR = "ERROR"
CRITICAL = "CRITICAL"
SUCCESS = "SUCCESS"
class Notification:
"""Represents a single notification."""
def __init__(
self,
level: NotificationLevel,
title: str,
message: str,
category: str = "GENERAL",
metadata: Optional[Dict] = None
):
"""
Create notification.
Args:
level: Notification level
title: Notification title
message: Notification message
category: Category (TRADE, RISK, SYSTEM, etc.)
metadata: Additional metadata
"""
self.level = level
self.title = title
self.message = message
self.category = category
self.metadata = metadata or {}
self.timestamp = datetime.now()
self.id = f"{self.timestamp.timestamp()}_{hash(message)}"
def __str__(self) -> str:
return f"[{self.level.value}] {self.title}: {self.message}"
def to_dict(self) -> Dict[str, Any]:
"""Convert to dictionary."""
return {
'id': self.id,
'level': self.level.value,
'title': self.title,
'message': self.message,
'category': self.category,
'metadata': self.metadata,
'timestamp': self.timestamp.isoformat()
}
class NotificationSystem:
"""
Centralized notification system for the trading platform.
Manages alerts, notifications, and callbacks.
"""
def __init__(self, max_notifications: int = 1000):
"""
Initialize notification system.
Args:
max_notifications: Maximum notifications to keep in history
"""
self.max_notifications = max_notifications
self.notifications: List[Notification] = []
self.notification_queue = queue.Queue()
self.callbacks: Dict[str, List[Callable]] = {
'INFO': [],
'WARNING': [],
'ERROR': [],
'CRITICAL': [],
'SUCCESS': [],
'ALL': []
}
self._lock = threading.Lock()
def subscribe(
self,
callback: Callable[[Notification], None],
level: Optional[str] = 'ALL'
):
"""
Subscribe to notifications.
Args:
callback: Callback function to receive notifications
level: Notification level to subscribe to (default: ALL)
"""
with self._lock:
if level not in self.callbacks:
level = 'ALL'
self.callbacks[level].append(callback)
system_logger.debug(f"Subscribed callback to {level} notifications")
def unsubscribe(self, callback: Callable, level: Optional[str] = 'ALL'):
"""
Unsubscribe from notifications.
Args:
callback: Callback function to remove
level: Notification level
"""
with self._lock:
if level in self.callbacks and callback in self.callbacks[level]:
self.callbacks[level].remove(callback)
system_logger.debug(f"Unsubscribed callback from {level} notifications")
def notify(
self,
level: NotificationLevel,
title: str,
message: str,
category: str = "GENERAL",
metadata: Optional[Dict] = None
):
"""
Send a notification.
Args:
level: Notification level
title: Notification title
message: Notification message
category: Notification category
metadata: Additional metadata
"""
notification = Notification(level, title, message, category, metadata)
with self._lock:
# Add to history
self.notifications.append(notification)
# Limit history size
if len(self.notifications) > self.max_notifications:
self.notifications.pop(0)
# Add to queue
self.notification_queue.put(notification)
# Log notification
log_message = f"[{category}] {title}: {message}"
if level == NotificationLevel.INFO:
system_logger.info(log_message)
elif level == NotificationLevel.WARNING:
system_logger.warning(log_message)
elif level in [NotificationLevel.ERROR, NotificationLevel.CRITICAL]:
system_logger.error(log_message)
# Execute callbacks
self._execute_callbacks(notification)
def _execute_callbacks(self, notification: Notification):
"""
Execute registered callbacks for a notification.
Args:
notification: Notification to process
"""
with self._lock:
# Level-specific callbacks
for callback in self.callbacks.get(notification.level.value, []):
try:
callback(notification)
except Exception as e:
system_logger.error(f"Callback error: {str(e)}")
# General callbacks
for callback in self.callbacks.get('ALL', []):
try:
callback(notification)
except Exception as e:
system_logger.error(f"Callback error: {str(e)}")
def info(self, title: str, message: str, category: str = "GENERAL", **kwargs):
"""Send INFO notification."""
self.notify(NotificationLevel.INFO, title, message, category, kwargs)
def success(self, title: str, message: str, category: str = "GENERAL", **kwargs):
"""Send SUCCESS notification."""
self.notify(NotificationLevel.SUCCESS, title, message, category, kwargs)
def warning(self, title: str, message: str, category: str = "GENERAL", **kwargs):
"""Send WARNING notification."""
self.notify(NotificationLevel.WARNING, title, message, category, kwargs)
def error(self, title: str, message: str, category: str = "GENERAL", **kwargs):
"""Send ERROR notification."""
self.notify(NotificationLevel.ERROR, title, message, category, kwargs)
def critical(self, title: str, message: str, category: str = "GENERAL", **kwargs):
"""Send CRITICAL notification."""
self.notify(NotificationLevel.CRITICAL, title, message, category, kwargs)
# Trading-specific notifications
def trade_executed(
self,
symbol: str,
side: str,
quantity: int,
price: float,
order_id: str = None
):
"""
Notify about trade execution.
Args:
symbol: Stock symbol
side: BUY or SELL
quantity: Trade quantity
price: Execution price
order_id: Order ID
"""
self.success(
"Trade Executed",
f"{side} {quantity} {symbol} @ ${price:.2f}",
category="TRADE",
symbol=symbol,
side=side,
quantity=quantity,
price=price,
order_id=order_id
)
def trade_failed(
self,
symbol: str,
side: str,
quantity: int,
error: str
):
"""
Notify about trade failure.
Args:
symbol: Stock symbol
side: BUY or SELL
quantity: Trade quantity
error: Error message
"""
self.error(
"Trade Failed",
f"Failed to {side} {quantity} {symbol}: {error}",
category="TRADE",
symbol=symbol,
side=side,
quantity=quantity,
error=error
)
def risk_alert(self, alert_type: str, message: str, severity: str = "WARNING"):
"""
Notify about risk alert.
Args:
alert_type: Type of risk alert
message: Alert message
severity: Alert severity
"""
level = NotificationLevel.WARNING
if severity == "CRITICAL":
level = NotificationLevel.CRITICAL
elif severity == "ERROR":
level = NotificationLevel.ERROR
self.notify(
level,
f"Risk Alert: {alert_type}",
message,
category="RISK",
alert_type=alert_type
)
def system_event(self, event: str, details: str = ""):
"""
Notify about system event.
Args:
event: Event name
details: Event details
"""
self.info(
f"System: {event}",
details,
category="SYSTEM",
event=event
)
def performance_milestone(self, milestone: str, value: Any):
"""
Notify about performance milestone.
Args:
milestone: Milestone description
value: Milestone value
"""
self.success(
"Performance Milestone",
f"{milestone}: {value}",
category="PERFORMANCE",
milestone=milestone,
value=value
)
def get_notifications(
self,
category: Optional[str] = None,
level: Optional[NotificationLevel] = None,
limit: int = 100
) -> List[Notification]:
"""
Get notifications with optional filtering.
Args:
category: Filter by category
level: Filter by level
limit: Maximum number to return
Returns:
List of notifications
"""
with self._lock:
notifications = self.notifications.copy()
# Apply filters
if category:
notifications = [n for n in notifications if n.category == category]
if level:
notifications = [n for n in notifications if n.level == level]
# Return most recent
return notifications[-limit:]
def clear_notifications(self, category: Optional[str] = None):
"""
Clear notifications.
Args:
category: Optional category to clear (clears all if None)
"""
with self._lock:
if category:
self.notifications = [
n for n in self.notifications
if n.category != category
]
else:
self.notifications.clear()
def get_unread_count(self) -> int:
"""
Get count of notifications in queue.
Returns:
Number of unread notifications
"""
return self.notification_queue.qsize()
# Global notification system instance
notification_system = NotificationSystem()