onesecondtrader 0.14.2__py3-none-any.whl → 0.16.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,868 +0,0 @@
1
- """
2
- This module provides the event messages used for decoupled communication between the
3
- trading infrastructure's components.
4
- Events are organized into namespaces (`Strategy`, `Market`, `Request`, `Response`, and
5
- `System`) to provide clear semantic groupings.
6
- Base event messages used for structure inheritance are grouped under the
7
- `Base` namespace.
8
- Dataclass field validation logic is grouped under the `_Validate` namespace.
9
-
10
- ???+ note "Module Overview: `events.py`"
11
- ```mermaid
12
- ---
13
- config:
14
- themeVariables:
15
- fontSize: "11px"
16
- ---
17
- graph LR
18
-
19
- R[events.Base.Event]
20
- R1[events.Base.Market]
21
- R2[events.Base.Request]
22
- R21[events.Base.OrderRequest]
23
- R22[events.Base.CancelRequest]
24
- R3[events.Base.Response]
25
- R4[events.Base.System]
26
- R5[events.Base.Strategy]
27
-
28
- R --> R1
29
- R --> R2
30
- R --> R3
31
- R --> R4
32
- R --> R5
33
-
34
- R2 --> R21
35
- R2 --> R22
36
-
37
- A1[events.Market.IncomingBar]
38
-
39
- R1 --> A1
40
-
41
- style A1 fill:#6F42C1,fill-opacity:0.3
42
-
43
- B1[events.Request.MarketOrder]
44
- B2[events.Request.LimitOrder]
45
- B3[events.Request.StopOrder]
46
- B4[events.Request.StopLimitOrder]
47
- B5[events.Request.CancelOrder]
48
- B6[events.Request.FlushSymbol]
49
- B7[events.Request.FlushAll]
50
-
51
- R21 --> B1
52
- R21 --> B2
53
- R21 --> B3
54
- R21 --> B4
55
- R22 --> B5
56
- R22 --> B6
57
- R22 --> B7
58
-
59
- style B1 fill:#6F42C1,fill-opacity:0.3
60
- style B2 fill:#6F42C1,fill-opacity:0.3
61
- style B3 fill:#6F42C1,fill-opacity:0.3
62
- style B4 fill:#6F42C1,fill-opacity:0.3
63
- style B5 fill:#6F42C1,fill-opacity:0.3
64
- style B6 fill:#6F42C1,fill-opacity:0.3
65
- style B7 fill:#6F42C1,fill-opacity:0.3
66
-
67
- C1[events.Response.OrderSubmitted]
68
- C2[events.Response.OrderFilled]
69
- C3[events.Response.OrderCancelled]
70
- C4[events.Response.OrderRejected]
71
-
72
- R3 --> C1
73
- R3 --> C2
74
- R3 --> C3
75
- R3 --> C4
76
-
77
- style C1 fill:#6F42C1,fill-opacity:0.3
78
- style C2 fill:#6F42C1,fill-opacity:0.3
79
- style C3 fill:#6F42C1,fill-opacity:0.3
80
- style C4 fill:#6F42C1,fill-opacity:0.3
81
-
82
- D1[events.System.Shutdown]
83
-
84
- R4 --> D1
85
-
86
- style D1 fill:#6F42C1,fill-opacity:0.3
87
-
88
- E1[events.Strategy.SymbolRelease]
89
- E2[events.Strategy.SymbolAssignment]
90
- E3[events.Strategy.StopTrading]
91
-
92
- R5 --> E1
93
- R5 --> E2
94
- R5 --> E3
95
-
96
- style E1 fill:#6F42C1,fill-opacity:0.3
97
- style E2 fill:#6F42C1,fill-opacity:0.3
98
- style E3 fill:#6F42C1,fill-opacity:0.3
99
-
100
- subgraph Market ["Market Update Event Messages"]
101
- R1
102
- A1
103
-
104
- subgraph MarketNamespace ["events.Market Namespace"]
105
- A1
106
- end
107
-
108
- end
109
-
110
-
111
- subgraph Request ["Broker Request Event Messages"]
112
- R2
113
- R21
114
- R22
115
- B1
116
- B2
117
- B3
118
- B4
119
- B5
120
- B6
121
- B7
122
-
123
- subgraph RequestNamespace ["events.Request Namespace"]
124
- B1
125
- B2
126
- B3
127
- B4
128
- B5
129
- B6
130
- B7
131
- end
132
-
133
- end
134
-
135
- subgraph Response ["Broker Response Event Messages"]
136
- R3
137
- C1
138
- C2
139
- C3
140
- C4
141
-
142
- subgraph ResponseNamespace ["events.Response Namespace"]
143
- C1
144
- C2
145
- C3
146
- C4
147
- end
148
-
149
- end
150
-
151
- subgraph System ["System-Internal Event Messages"]
152
- R4
153
- D1
154
-
155
- subgraph SystemNamespace ["events.System Namespace"]
156
- D1
157
- end
158
-
159
- end
160
-
161
- subgraph Strategy ["Strategy Coord. Event Messages"]
162
- R5
163
- E1
164
- E2
165
- E3
166
-
167
- subgraph StrategyNamespace ["events.Strategy Namespace"]
168
- E1
169
- E2
170
- E3
171
- end
172
-
173
- end
174
- ```
175
- """
176
-
177
- import dataclasses
178
- import pandas as pd
179
- import re
180
- import uuid
181
- from onesecondtrader.core import models
182
- from onesecondtrader.monitoring import console
183
- from onesecondtrader.strategies import base_strategy
184
-
185
-
186
- class Base:
187
- """
188
- Namespace for event base dataclasses.
189
- """
190
-
191
- @dataclasses.dataclass(kw_only=True, frozen=True)
192
- class Event:
193
- """
194
- Base event message dataclass.
195
- This dataclass cannot be instantiated directly.
196
-
197
- Attributes:
198
- ts_event (pd.Timestamp): Timestamp of the event in pandas Timestamp format.
199
- (Must be timezone-aware.)
200
- event_bus_sequence_number (int | None): Auto-generated Sequence number of
201
- the event.
202
- This will be assigned as soon as the event enters the event bus via
203
- `messaging.EventBus.publish(<event>)`.
204
- """
205
-
206
- ts_event: pd.Timestamp
207
- event_bus_sequence_number: int | None = dataclasses.field(
208
- default=None, init=False
209
- )
210
-
211
- def __new__(cls, *args, **kwargs):
212
- if cls is Base.Event:
213
- console.logger.error(
214
- f"Cannot instantiate abstract class '{cls.__name__}' directly"
215
- )
216
- return super().__new__(cls)
217
-
218
- def __post_init__(self) -> None:
219
- _Validate.timezone_aware(self.ts_event, "ts_event", "Event")
220
-
221
- @dataclasses.dataclass(kw_only=True, frozen=True)
222
- class Market(Event):
223
- """
224
- Base event message dataclass for market events.
225
- Inherits from `Base.Event`.
226
- Each market event message is associated with a specific financial instrument via
227
- the `symbol` field.
228
- This dataclass cannot be instantiated directly.
229
-
230
- Attributes:
231
- symbol (str): Symbol of the financial instrument.
232
- """
233
-
234
- symbol: str
235
-
236
- def __new__(cls, *args, **kwargs):
237
- if cls is Base.Market:
238
- console.logger.error(
239
- f"Cannot instantiate abstract class '{cls.__name__}' directly"
240
- )
241
- return super().__new__(cls)
242
-
243
- def __post_init__(self) -> None:
244
- super().__post_init__()
245
- _Validate.symbol(self.symbol, "Market event")
246
-
247
- @dataclasses.dataclass(kw_only=True, frozen=True)
248
- class Request(Event):
249
- """
250
- Base event message dataclass for broker requests.
251
- This dataclass cannot be instantiated directly.
252
- `ts_event` is auto-generated by default.
253
-
254
- Attributes:
255
- ts_event: Timestamp of the event. (defaults to current UTC time;
256
- auto-generated)
257
- """
258
-
259
- ts_event: pd.Timestamp = dataclasses.field(
260
- default_factory=lambda: pd.Timestamp.now(tz="UTC")
261
- )
262
-
263
- def __new__(cls, *args, **kwargs):
264
- if cls is Base.Request:
265
- console.logger.error(
266
- f"Cannot instantiate abstract class '{cls.__name__}' directly"
267
- )
268
- return super().__new__(cls)
269
-
270
- @dataclasses.dataclass(kw_only=True, frozen=True)
271
- class OrderRequest(Request):
272
- """
273
- Base event message dataclass for order requests.
274
- Inherits from `Base.Request`.
275
- This dataclass cannot be instantiated directly.
276
-
277
- Attributes:
278
- symbol (str): Symbol of the financial instrument.
279
- side (models.Side): Side of the order.
280
- quantity (float): Quantity of the order.
281
- time_in_force (models.TimeInForce): Time in force of the order.
282
- order_expiration (pd.Timestamp | None): Expiration timestamp of the order
283
- (optional).
284
- Only relevant if `time_in_force` is `models.TimeInForce.GTD`.
285
- order_id (uuid.UUID): Unique ID of the order. (auto-generated)
286
- """
287
-
288
- symbol: str
289
- side: models.Side
290
- quantity: float
291
- time_in_force: models.TimeInForce
292
- order_expiration: pd.Timestamp | None = None
293
- order_id: uuid.UUID = dataclasses.field(default_factory=uuid.uuid4)
294
-
295
- def __new__(cls, *args, **kwargs):
296
- if cls is Base.OrderRequest:
297
- console.logger.error(
298
- f"Cannot instantiate abstract class '{cls.__name__}' directly"
299
- )
300
- return super().__new__(cls)
301
-
302
- def __post_init__(self) -> None:
303
- super().__post_init__()
304
- _Validate.symbol(self.symbol, f"Order {self.order_id}")
305
-
306
- _Validate.timezone_aware(
307
- self.order_expiration, "order_expiration", f"Order {self.order_id}"
308
- )
309
- _Validate.quantity(self.quantity, f"Order {self.order_id}")
310
-
311
- if self.time_in_force is models.TimeInForce.GTD:
312
- if self.order_expiration is None:
313
- console.logger.error(
314
- f"Order {self.order_id}: GTD order missing expiration "
315
- f"timestamp."
316
- )
317
- elif self.order_expiration <= self.ts_event:
318
- console.logger.error(
319
- f"Order {self.order_id}: GTD expiration "
320
- f"{self.order_expiration} "
321
- f"is not after event timestamp {self.ts_event}."
322
- )
323
-
324
- @dataclasses.dataclass(kw_only=True, frozen=True)
325
- class CancelRequest(Request):
326
- """
327
- Base event message dataclass for order cancellation requests.
328
- Inherits from `Base.Request`.
329
- This dataclass cannot be instantiated directly.
330
- """
331
-
332
- def __new__(cls, *args, **kwargs):
333
- if cls is Base.CancelRequest:
334
- console.logger.error(
335
- f"Cannot instantiate abstract class '{cls.__name__}' directly"
336
- )
337
- return super().__new__(cls)
338
-
339
- @dataclasses.dataclass(kw_only=True, frozen=True)
340
- class Response(Event):
341
- """
342
- Base event message dataclass for broker responses.
343
- This dataclass cannot be instantiated directly.
344
- """
345
-
346
- def __new__(cls, *args, **kwargs):
347
- if cls is Base.Response:
348
- console.logger.error(
349
- f"Cannot instantiate abstract class '{cls.__name__}' directly"
350
- )
351
- return super().__new__(cls)
352
-
353
- @dataclasses.dataclass(kw_only=True, frozen=True)
354
- class System(Event):
355
- """
356
- Base event message dataclass for system-internal messages.
357
- This dataclass cannot be instantiated directly.
358
- `ts_event` is auto-generated by default.
359
-
360
- Attributes:
361
- ts_event: Timestamp of the event. (defaults to current UTC time;
362
- auto-generated)
363
- """
364
-
365
- ts_event: pd.Timestamp = dataclasses.field(
366
- default_factory=lambda: pd.Timestamp.now(tz="UTC")
367
- )
368
-
369
- def __new__(cls, *args, **kwargs):
370
- if cls is Base.System:
371
- console.logger.error(
372
- f"Cannot instantiate abstract class '{cls.__name__}' directly"
373
- )
374
- return super().__new__(cls)
375
-
376
- @dataclasses.dataclass(kw_only=True, frozen=True)
377
- class Strategy(Event):
378
- """
379
- Base event message dataclass for strategy coordination messages.
380
- This dataclass cannot be instantiated directly.
381
-
382
- Attributes:
383
- ts_event: Timestamp of the event. (defaults to current UTC time;
384
- auto-generated)
385
- """
386
-
387
- ts_event: pd.Timestamp = dataclasses.field(
388
- default_factory=lambda: pd.Timestamp.now(tz="UTC")
389
- )
390
- strategy: base_strategy.Strategy
391
-
392
- def __new__(cls, *args, **kwargs):
393
- if cls is Base.Strategy:
394
- console.logger.error(
395
- f"Cannot instantiate abstract class '{cls.__name__}' directly"
396
- )
397
- return super().__new__(cls)
398
-
399
- def __post_init__(self) -> None:
400
- super().__post_init__()
401
- if not isinstance(self.strategy, base_strategy.Strategy):
402
- console.logger.error(
403
- f"{type(self).__name__}: strategy must inherit from Strategy"
404
- )
405
-
406
-
407
- class Market:
408
- """
409
- Namespace for market update event messages.
410
- """
411
-
412
- @dataclasses.dataclass(kw_only=True, frozen=True)
413
- class IncomingBar(Base.Market):
414
- """
415
- Event message dataclass for incoming market data bars.
416
- Inherits from `Base.Market`.
417
-
418
- Attributes:
419
- bar (models.Bar): Bar of market data.
420
-
421
- Examples:
422
- >>> from onesecondtrader.messaging import events
423
- >>> from onesecondtrader.core import models
424
- >>> event = events.Market.IncomingBar(
425
- ... ts_event=pd.Timestamp("2023-01-01 00:00:00", tz="UTC"),
426
- ... symbol="AAPL",
427
- ... bar=models.Bar(
428
- ... open=100.0,
429
- ... high=101.0,
430
- ... low=99.0,
431
- ... close=100.5,
432
- ... volume=10000,
433
- ... ),
434
- ... )
435
-
436
- """
437
-
438
- bar: models.Bar
439
-
440
-
441
- class Request:
442
- """
443
- Namespace for broker request event messages.
444
- """
445
-
446
- @dataclasses.dataclass(kw_only=True, frozen=True)
447
- class MarketOrder(Base.OrderRequest):
448
- """
449
- Event message dataclass for submitting a market order to the broker.
450
-
451
- Attributes:
452
- order_type (models.OrderType): Type of the order (automatically set to
453
- models.OrderType.MARKET).
454
-
455
- Examples:
456
- >>> from onesecondtrader.messaging import events
457
- >>> event = events.Request.MarketOrder(
458
- ... symbol="AAPL",
459
- ... side=models.Side.BUY,
460
- ... quantity=100.0,
461
- ... time_in_force=models.TimeInForce.DAY,
462
- ... )
463
- """
464
-
465
- order_type: models.OrderType = dataclasses.field(
466
- init=False, default=models.OrderType.MARKET
467
- )
468
-
469
- @dataclasses.dataclass(kw_only=True, frozen=True)
470
- class LimitOrder(Base.OrderRequest):
471
- """
472
- Event message dataclass for submitting a limit order to the broker.
473
-
474
- Attributes:
475
- order_type (models.OrderType): Type of the order (automatically set to
476
- models.OrderType.LIMIT).
477
- limit_price (float): Limit price of the order.
478
-
479
- Examples:
480
- >>> from onesecondtrader.messaging import events
481
- >>> event = events.Request.LimitOrder(
482
- ... symbol="AAPL",
483
- ... side=models.Side.BUY,
484
- ... quantity=100.0,
485
- ... time_in_force=models.TimeInForce.DAY,
486
- ... limit_price=100.0,
487
- ... )
488
- """
489
-
490
- order_type: models.OrderType = dataclasses.field(
491
- init=False, default=models.OrderType.LIMIT
492
- )
493
- limit_price: float
494
-
495
- @dataclasses.dataclass(kw_only=True, frozen=True)
496
- class StopOrder(Base.OrderRequest):
497
- """
498
- Event message dataclass for submitting a stop order to the broker.
499
-
500
- Attributes:
501
- order_type (models.OrderType): Type of the order (automatically set to
502
- models.OrderType.STOP).
503
- stop_price (float): Stop price of the order.
504
-
505
- Examples:
506
- >>> from onesecondtrader.messaging import events
507
- >>> event = events.Request.StopOrder(
508
- ... symbol="AAPL",
509
- ... side=models.Side.BUY,
510
- ... quantity=100.0,
511
- ... time_in_force=models.TimeInForce.DAY,
512
- ... stop_price=100.0,
513
- ... )
514
- """
515
-
516
- order_type: models.OrderType = dataclasses.field(
517
- init=False, default=models.OrderType.STOP
518
- )
519
- stop_price: float
520
-
521
- @dataclasses.dataclass(kw_only=True, frozen=True)
522
- class StopLimitOrder(Base.OrderRequest):
523
- """
524
- Event message dataclass for submitting a stop-limit order to the broker.
525
-
526
- Attributes:
527
- order_type (models.OrderType): Type of the order (automatically set to
528
- models.OrderType.STOP_LIMIT).
529
- stop_price (float): Stop price of the order.
530
- limit_price (float): Limit price of the order.
531
-
532
- Examples:
533
- >>> from onesecondtrader.messaging import events
534
- >>> event = events.Request.StopLimitOrder(
535
- ... symbol="AAPL",
536
- ... side=models.Side.BUY,
537
- ... quantity=100.0,
538
- ... time_in_force=models.TimeInForce.DAY,
539
- ... stop_price=100.0,
540
- ... limit_price=100.0,
541
- ... )
542
- """
543
-
544
- order_type: models.OrderType = dataclasses.field(
545
- init=False, default=models.OrderType.STOP_LIMIT
546
- )
547
- stop_price: float
548
- limit_price: float
549
-
550
- @dataclasses.dataclass(kw_only=True, frozen=True)
551
- class CancelOrder(Base.CancelRequest):
552
- """
553
- Event message dataclass for cancelling an order.
554
-
555
- Attributes:
556
- order_id (uuid.UUID): Unique ID of the order to cancel.
557
-
558
- Examples:
559
- >>> from onesecondtrader.messaging import events
560
- >>> event = events.Request.CancelOrder(
561
- ... order_id=uuid.UUID("12345678-1234-5678-1234-567812345678"),
562
- ... )
563
- """
564
-
565
- order_id: uuid.UUID
566
-
567
- @dataclasses.dataclass(kw_only=True, frozen=True)
568
- class FlushSymbol(Base.Request):
569
- """
570
- Event message dataclass for flushing all orders for a symbol.
571
-
572
- Attributes:
573
- symbol (str): Symbol to flush.
574
-
575
- Examples:
576
- >>> from onesecondtrader.messaging import events
577
- >>> event = events.Request.FlushSymbol(
578
- ... symbol="AAPL",
579
- ... )
580
- """
581
-
582
- symbol: str
583
-
584
- def __post_init__(self) -> None:
585
- super().__post_init__()
586
- _Validate.symbol(self.symbol, "Flush request")
587
-
588
- @dataclasses.dataclass(kw_only=True, frozen=True)
589
- class FlushAll(Base.Request):
590
- """
591
- Event message dataclass for flushing all orders for all symbols.
592
-
593
- Examples:
594
- >>> from onesecondtrader.messaging import events
595
- >>> event = events.Request.FlushAll()
596
- """
597
-
598
- pass
599
-
600
-
601
- class Response:
602
- """
603
- Namespace for broker response event messages.
604
- """
605
-
606
- @dataclasses.dataclass(kw_only=True, frozen=True)
607
- class OrderSubmitted(Base.Response):
608
- """
609
- Event message dataclass for order submission confirmation from the broker.
610
-
611
- Attributes:
612
- order_submitted_id (uuid.UUID): Unique ID of the submitted order.
613
- associated_request_id (uuid.UUID): Unique ID of the request that triggered
614
- the order submission.
615
-
616
- Examples:
617
- >>> from onesecondtrader.messaging import events
618
- >>> import pandas as pd
619
- >>> import uuid
620
- >>> event = events.Response.OrderSubmitted(
621
- ... ts_event=pd.Timestamp(
622
- ... "2023-01-01 00:00:00", tz="UTC"),
623
- ... order_submitted_id=uuid.UUID(
624
- ... "12345678-1234-5678-1234-567812345678"),
625
- ... associated_request_id=uuid.UUID(
626
- ... "12345678-1234-5678-1234-567812345678"
627
- ... ),
628
- ... )
629
- """
630
-
631
- order_submitted_id: uuid.UUID
632
- associated_request_id: uuid.UUID
633
-
634
- @dataclasses.dataclass(kw_only=True, frozen=True)
635
- class OrderFilled(Base.Response):
636
- """
637
- Event message dataclass for order fill confirmation from the broker.
638
-
639
- Attributes:
640
- fill_id (uuid.UUID): Unique ID of the fill. (auto-generated)
641
- associated_order_submitted_id (uuid.UUID): Unique ID of the submitted order
642
- that triggered the fill.
643
- side (models.Side): Side of the fill.
644
- quantity_filled (float): Quantity filled.
645
- filled_at_price (float): Price at which the fill was executed.
646
- commission_and_fees (float): Commission and fees for the fill.
647
- net_fill_value (float): Net fill value (auto-generated).
648
- exchange (str | None): Exchange on which the fill was executed. (optional;
649
- defaults to "SIMULATED")
650
-
651
- Examples:
652
- >>> from onesecondtrader.messaging import events
653
- >>> from onesecondtrader.core import models
654
- >>> import pandas as pd
655
- >>> import uuid
656
- >>> event = events.Response.OrderFilled(
657
- ... ts_event=pd.Timestamp("2023-01-01 00:00:00", tz="UTC"),
658
- ... associated_order_submitted_id=uuid.UUID(
659
- ... "12345678-1234-5678-1234-567812345678"
660
- ... ),
661
- ... side=models.Side.BUY,
662
- ... quantity_filled=100.0,
663
- ... filled_at_price=100.0,
664
- ... commission_and_fees=1.0,
665
- ... )
666
- """
667
-
668
- fill_id: uuid.UUID = dataclasses.field(default_factory=uuid.uuid4)
669
- associated_order_submitted_id: uuid.UUID
670
- side: models.Side
671
- quantity_filled: float
672
- filled_at_price: float
673
- commission_and_fees: float
674
- net_fill_value: float = dataclasses.field(init=False)
675
- exchange: str | None = None
676
-
677
- def __post_init__(self):
678
- object.__setattr__(self, "fill_id", self.fill_id or uuid.uuid4())
679
-
680
- gross_value = self.filled_at_price * self.quantity_filled
681
-
682
- if self.side is models.Side.BUY:
683
- net_value = gross_value + self.commission_and_fees
684
- else:
685
- net_value = gross_value - self.commission_and_fees
686
-
687
- object.__setattr__(self, "net_fill_value", net_value)
688
-
689
- object.__setattr__(self, "exchange", self.exchange or "SIMULATED")
690
-
691
- @dataclasses.dataclass(kw_only=True, frozen=True)
692
- class OrderCancelled(Base.Response):
693
- """
694
- Event message dataclass for order cancellation confirmation from the broker.
695
-
696
- Attributes:
697
- associated_order_submitted_id (uuid.UUID): Unique ID of the submitted order
698
- that was cancelled.
699
-
700
- Examples:
701
- >>> from onesecondtrader.messaging import events
702
- >>> import pandas as pd
703
- >>> import uuid
704
- >>> event = events.Response.OrderCancelled(
705
- ... ts_event=pd.Timestamp("2023-01-01 00:00:00", tz="UTC"),
706
- ... associated_order_submitted_id=uuid.UUID(
707
- ... "12345678-1234-5678-1234-567812345678"
708
- ... ),
709
- ... )
710
- """
711
-
712
- associated_order_submitted_id: uuid.UUID
713
-
714
- @dataclasses.dataclass(kw_only=True, frozen=True)
715
- class OrderRejected(Base.Response):
716
- """
717
- Event message dataclass for order rejection confirmation from the broker.
718
-
719
- Attributes:
720
- associated_order_submitted_id (uuid.UUID): Unique ID of the submitted order
721
- that was rejected.
722
- reason (models.OrderRejectionReason): Reason for the rejection.
723
-
724
- Examples:
725
- >>> from onesecondtrader.messaging import events
726
- >>> from onesecondtrader.core import models
727
- >>> import pandas as pd
728
- >>> import uuid
729
- >>> event = events.Response.OrderRejected(
730
- ... ts_event=pd.Timestamp("2023-01-01 00:00:00", tz="UTC"),
731
- ... associated_order_submitted_id=uuid.UUID(
732
- ... "12345678-1234-5678-1234-567812345678"
733
- ... ),
734
- ... reason=models.OrderRejectionReason.NEGATIVE_QUANTITY,
735
- ... )
736
- """
737
-
738
- associated_order_submitted_id: uuid.UUID
739
- reason: models.OrderRejectionReason
740
-
741
-
742
- class System:
743
- """
744
- Namespace for system-internal event messages.
745
- """
746
-
747
- @dataclasses.dataclass(kw_only=True, frozen=True)
748
- class Shutdown(Base.System):
749
- """
750
- Event message dataclass for system shutdown.
751
-
752
- Examples:
753
- >>> from onesecondtrader.messaging import events
754
- >>> event = events.System.Shutdown()
755
- """
756
-
757
- pass
758
-
759
-
760
- class Strategy:
761
- """
762
- Namespace for strategy coordination event messages.
763
- """
764
-
765
- @dataclasses.dataclass(kw_only=True, frozen=True)
766
- class SymbolRelease(Base.Strategy):
767
- """
768
- Event to indicate a strategy releases ownership of a symbol.
769
-
770
- Attributes:
771
- symbol (str): Symbol released.
772
-
773
- Examples:
774
- >>> from onesecondtrader.messaging import events
775
- >>> event = events.Strategy.SymbolRelease(
776
- ... symbol="AAPL",
777
- ... )
778
- """
779
-
780
- symbol: str
781
-
782
- def __post_init__(self) -> None:
783
- super().__post_init__()
784
- _Validate.symbol(self.symbol, "Strategy.SymbolRelease")
785
-
786
- @dataclasses.dataclass(kw_only=True, frozen=True)
787
- class SymbolAssignment(Base.Strategy):
788
- """
789
- Event message to indicate that a symbol should be assigned to a strategy.
790
-
791
- Attributes:
792
- symbol_list (list[str]): List of symbols to be assigned.
793
-
794
- Examples:
795
- >>> from onesecondtrader.messaging import events
796
- >>> event = events.Strategy.SymbolAssignment(
797
- ... strategy=my_strategy,
798
- ... symbol=["AAPL"],
799
- ... )
800
- """
801
-
802
- symbol_list: list[str]
803
-
804
- def __post_init__(self) -> None:
805
- super().__post_init__()
806
- for symbol in self.symbol_list:
807
- _Validate.symbol(symbol, "Strategy.SymbolAssignment")
808
-
809
- @dataclasses.dataclass(kw_only=True, frozen=True)
810
- class StopTrading(Base.Strategy):
811
- """
812
- Event to indicate a strategy should stop trading.
813
-
814
- Attributes:
815
- shutdown_mode (models.StrategyShutdownMode): Shutdown mode to use.
816
-
817
- Examples:
818
- >>> from onesecondtrader.messaging import events
819
- >>> event = events.Strategy.StopTrading(
820
- ... strategy=my_strategy,
821
- ... shutdown_mode=models.StrategyShutdownMode.SOFT,
822
- ... )
823
- """
824
-
825
- shutdown_mode: models.StrategyShutdownMode
826
-
827
-
828
- class _Validate:
829
- """Internal validation utilities for events."""
830
-
831
- @staticmethod
832
- def symbol(symbol: str, context: str = "") -> None:
833
- """Validate symbol format and log errors."""
834
- if not symbol or not symbol.strip():
835
- console.logger.error(f"{context}: Symbol cannot be empty or whitespace")
836
- return
837
-
838
- if not re.fullmatch(r"[A-Z0-9._-]+", symbol):
839
- console.logger.error(f"{context}: Invalid symbol format: {symbol}")
840
-
841
- @staticmethod
842
- def quantity(quantity: float, context: str = "") -> None:
843
- """Validate quantity values and log errors."""
844
- if (
845
- quantity != quantity
846
- or quantity == float("inf")
847
- or quantity == float("-inf")
848
- ):
849
- console.logger.error(f"{context}: quantity cannot be NaN or infinite")
850
- return
851
-
852
- if quantity <= 0:
853
- console.logger.error(
854
- f"{context}: quantity must be positive, got {quantity}"
855
- )
856
-
857
- if quantity > 1e9:
858
- console.logger.error(f"{context}: quantity too large: {quantity}")
859
-
860
- @staticmethod
861
- def timezone_aware(
862
- timestamp: pd.Timestamp | None, field_name: str, context: str = ""
863
- ) -> None:
864
- """Validate that timestamp is timezone-aware and log errors."""
865
- if timestamp is not None and timestamp.tz is None:
866
- console.logger.error(
867
- f"{context}: {field_name} must be timezone-aware, got {timestamp}"
868
- )