forked from BobbyAxerol/quantbt
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathnative_event.py
More file actions
5048 lines (4814 loc) · 218 KB
/
Copy pathnative_event.py
File metadata and controls
5048 lines (4814 loc) · 218 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
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"""
quantbt.backends.native_event
-----------------------------
Native event-driven backend using a Numba matching kernel.
"""
from __future__ import annotations
from dataclasses import asdict, dataclass, field, replace
import math
from pathlib import Path
from typing import Dict, List, Mapping, Optional, Sequence, Union
import numpy as np
import pandas as pd
from ..core.event import (
ACTIVATION_IMMEDIATE,
ACTIVATION_ON_PARENT_FIRST_FILL,
ACTIVATION_ON_PARENT_FULL_FILL,
COMMAND_ACTION_AMEND,
COMMAND_ACTION_CANCEL,
COMMAND_ACTION_CANCEL_ALL,
COMMAND_ACTION_PLACE,
COMMAND_ACTION_REPLACE,
LIQ_AFTER_FUNDING,
LIQ_AFTER_ORDER,
LIQ_INTRABAR,
LIQ_NONE,
ORDER_EVENT_ACTIVATE,
ORDER_EVENT_AMEND,
ORDER_EVENT_CANCEL,
ORDER_EVENT_EXPIRE,
ORDER_EVENT_FILL,
ORDER_EVENT_PLACE,
ORDER_EVENT_REJECT,
ORDER_STATUS_CANCELED,
ORDER_STATUS_FILLED,
ORDER_STATUS_PENDING,
ORDER_STATUS_REJECTED,
ORDER_TYPE_LIMIT,
ORDER_TYPE_MARKET,
ORDER_TYPE_STOP_LIMIT,
ORDER_TYPE_STOP_MARKET,
REJECT_INSUFFICIENT_MARGIN,
REJECT_REDUCE_ONLY_NO_POSITION,
REJECT_UNKNOWN_ORDER,
SIDE_BUY,
SIDE_SELL,
TIF_FOK,
TIF_GTC,
TIF_GTD,
TIF_IOC,
_engine_event_v1,
_engine_event_v2,
)
from ..core.constraints import build_quantity_constraints, quantize_signed_quantity
from ..core.arbitrage import (
ArbitrageSpec,
ArbitragePlan,
BasisArbitrageSpec,
CalendarSpreadSpec,
CrossExchangeArbSpec,
FundingArbitrageSpec,
IndexBasketArbSpec,
OptionsVolArbSpec,
PackageExecutionKind,
PackageRejection,
SizingPolicyKind,
SpotPerpCashCarrySpec,
StatArbPairSpec,
TriangularArbSpec,
build_arbitrage_order_plan,
)
from ..core.basket import build_frozen_basket_orders
from ..core.order_compiler import (
CompiledOrderArrays,
CompiledOrderCommandArrays,
compile_order_commands,
compile_order_intents,
)
from ..core.orders import Fill, OrderAction, OrderActivationPolicy, OrderCommand, OrderIntent
from ..core.preprocessor import (
PreparedMarketArrays,
align_series,
build_market_arrays,
make_funding_mask,
prepare_funding,
validate_datetime,
)
from ..core.results import (
BacktestResultV2,
NativeAccountingArrays,
NativeEventScalarScoreResult,
NativeEventScoreResult,
)
from ..core.reactive import (
NativeActiveOrderSnapshot,
NativeEventStrategyError,
NativeFillEvent,
NativeOrderEvent,
NativeStrategyContext,
)
from ..core.schema import (
AccountConfig,
BasketLegSpec,
BasketSpec,
ExecutionConfig,
LiquiditySide,
OrderSide,
OrderType,
TimeInForce,
InstrumentSpec,
)
from ._native_event_rust import (
NativeEventBackendSelection,
NativeEventRustBackendError,
RustBatchedRunner,
RustFullRunner,
RustReactiveSessionAdapter,
resolve_native_event_backend,
)
def _event_type_name(event_type: int) -> str:
return {
0: "place",
1: "cancel",
2: "replace",
3: "amend",
4: "fill",
5: "expire",
6: "activate",
7: "reject",
}.get(int(event_type), "unknown")
@dataclass(frozen=True)
class NativeEventConfig:
account: AccountConfig
execution: ExecutionConfig = field(default_factory=ExecutionConfig)
fee_rate: Union[float, Dict[str, float]] = 0.0
use_funding: bool = True
report_level: str = "audit"
audit_sink: str = "memory"
audit_sink_path: Optional[str] = None
reactive_kernel_mode: str = "replay_certified"
native_backend: Optional[str] = None
def __post_init__(self) -> None:
if isinstance(self.fee_rate, dict):
if any(float(rate) < 0.0 for rate in self.fee_rate.values()):
raise ValueError("fee_rate must be >= 0")
elif float(self.fee_rate) < 0.0:
raise ValueError("fee_rate must be >= 0")
object.__setattr__(self, "report_level", _normalize_native_event_report_level(self.report_level))
object.__setattr__(self, "audit_sink", _normalize_native_event_audit_sink(self.audit_sink))
object.__setattr__(self, "reactive_kernel_mode", _normalize_reactive_kernel_mode(self.reactive_kernel_mode))
if self.native_backend is not None:
selected = str(self.native_backend).lower().strip()
if selected not in {"python", "rust", "auto", "replay_certified"}:
raise ValueError(
"native_backend must be one of: auto, python, replay_certified, rust"
)
object.__setattr__(self, "native_backend", selected)
@dataclass(frozen=True)
class NativeEventArtifactPlan:
keep_equity_path: bool
keep_position_path: bool
keep_fee_path: bool
keep_funding_path: bool
keep_margin_path: bool
keep_fill_ledger: bool
keep_command_terminal_state: bool
keep_event_ledger: bool
keep_command_tape: bool
materialize_pandas: bool
materialize_python_objects: bool
materialize_active_orders: bool
@dataclass(frozen=True, slots=True)
class NativeEventScoreRequirements:
"""Internal retention contract for direct prepared-score execution.
The public ``PreparedNativeEventStrategyRunner.score`` compatibility
contract exposes accounting arrays. Prepared optimization uses
``scalar_score_contract()`` instead, which relies on online metrics and
keeps only live reactive state. Context flags are separate from ledger
retention: a strategy may consume current-bar fills without retaining the
complete fill history.
"""
need_equity_path: bool = False
need_position_path: bool = False
need_fee_path: bool = False
need_funding_path: bool = False
need_margin_path: bool = False
need_turnover_path: bool = False
need_rejection_path: bool = False
need_cancellation_path: bool = False
need_trade_stats: bool = True
need_fill_ledger: bool = False
need_event_ledger: bool = False
need_terminal_orders: bool = False
need_context_fills: bool = True
need_context_events: bool = True
need_context_active_orders: bool = True
need_context_positions: bool = True
need_context_margin: bool = True
need_command_tape: bool = False
@classmethod
def public_score_contract(cls) -> "NativeEventScoreRequirements":
"""Return the compatible array set required by ``NativeEventScoreResult``."""
return cls(
need_equity_path=True,
need_position_path=True,
need_fee_path=True,
need_funding_path=True,
need_margin_path=True,
need_trade_stats=False,
)
@classmethod
def scalar_score_contract(cls) -> "NativeEventScoreRequirements":
"""Return the low-retention contract used by prepared optimization."""
return cls(
need_equity_path=False,
need_position_path=False,
need_fee_path=False,
need_funding_path=False,
need_margin_path=False,
need_turnover_path=False,
need_rejection_path=False,
need_cancellation_path=False,
need_trade_stats=True,
need_fill_ledger=False,
need_event_ledger=False,
need_terminal_orders=False,
need_context_fills=True,
need_context_events=True,
need_context_active_orders=True,
need_context_positions=True,
need_context_margin=True,
need_command_tape=False,
)
@classmethod
def from_strategy(
cls,
strategy,
*,
base: Optional["NativeEventScoreRequirements"] = None,
) -> "NativeEventScoreRequirements":
"""Apply an optional strategy context declaration to a base contract."""
requirements = base or cls.scalar_score_contract()
declaration = getattr(strategy, "native_context_requirements", None)
if declaration is None:
return requirements
if not isinstance(declaration, Mapping):
raise TypeError("native_context_requirements must be a mapping")
aliases = {
"fills": "need_context_fills",
"events": "need_context_events",
"active_orders": "need_context_active_orders",
"positions": "need_context_positions",
"margin": "need_context_margin",
}
valid = set(aliases) | set(aliases.values())
updates = {}
for key, value in declaration.items():
if key not in valid:
raise ValueError(f"unsupported native context requirement: {key!r}")
updates[aliases.get(key, key)] = bool(value)
return replace(requirements, **updates)
@dataclass(frozen=True)
class CompactFillLedger:
bar: np.ndarray
command_index: np.ndarray
original_index: np.ndarray
order_id_code: np.ndarray
symbol_code: np.ndarray
side: np.ndarray
qty: np.ndarray
price: np.ndarray
fee: np.ndarray
id_values: tuple[str, ...]
symbols: tuple[str, ...]
@property
def fill_count(self) -> int:
return int(len(self.bar))
@dataclass(frozen=True)
class CompactCommandLedger:
original_index: np.ndarray
command_bar: np.ndarray
action: np.ndarray
symbol_code: np.ndarray
side: np.ndarray
order_type: np.ndarray
order_id_code: np.ndarray
target_order_id_code: np.ndarray
parent_order_id_code: np.ndarray
group_id_code: np.ndarray
oco_group_id_code: np.ndarray
status: np.ndarray
reject_code: np.ndarray
fill_bar: np.ndarray
fill_qty: np.ndarray
fill_price: np.ndarray
fill_fee: np.ndarray
active: np.ndarray
waiting_parent: np.ndarray
working_qty: np.ndarray
working_price: np.ndarray
working_trigger: np.ndarray
id_values: tuple[str, ...]
symbols: tuple[str, ...]
@dataclass(frozen=True)
class CompactOrderEventLedger:
bar: np.ndarray
command_index: np.ndarray
event_type: np.ndarray
status: np.ndarray
related_command_index: np.ndarray
@property
def event_count(self) -> int:
return int(len(self.bar))
def _normalize_native_event_report_level(report_level: str) -> str:
level = str(report_level or "audit").lower().strip()
aliases = {"full": "audit", "debug": "audit", "research": "standard", "optimizer": "score", "scoring": "score"}
level = aliases.get(level, level)
if level not in {"score", "minimal", "standard", "audit"}:
raise ValueError("native_event report_level must be score, minimal, standard, audit, or full")
return level
def _normalize_native_event_audit_sink(audit_sink: str) -> str:
sink = str(audit_sink or "memory").lower().strip()
if sink not in {"none", "memory", "jsonl", "parquet"}:
raise ValueError("native_event audit_sink must be none, memory, jsonl, or parquet")
return sink
def _normalize_reactive_kernel_mode(reactive_kernel_mode: str) -> str:
mode = str(reactive_kernel_mode or "replay_certified").lower().strip()
aliases = {"replay": "replay_certified", "certified": "replay_certified", "stateful": "single_pass"}
mode = aliases.get(mode, mode)
if mode not in {"replay_certified", "single_pass"}:
raise ValueError("reactive_kernel_mode must be replay_certified or single_pass")
return mode
def _native_event_artifact_plan(report_level: str) -> NativeEventArtifactPlan:
level = _normalize_native_event_report_level(report_level)
if level == "score":
return NativeEventArtifactPlan(
keep_equity_path=True,
keep_position_path=True,
keep_fee_path=True,
keep_funding_path=True,
keep_margin_path=True,
keep_fill_ledger=False,
keep_command_terminal_state=False,
keep_event_ledger=False,
keep_command_tape=False,
materialize_pandas=False,
materialize_python_objects=False,
materialize_active_orders=False,
)
if level == "minimal":
return NativeEventArtifactPlan(
keep_equity_path=True,
keep_position_path=True,
keep_fee_path=True,
keep_funding_path=True,
keep_margin_path=True,
keep_fill_ledger=True,
keep_command_terminal_state=True,
keep_event_ledger=False,
keep_command_tape=False,
materialize_pandas=True,
materialize_python_objects=False,
materialize_active_orders=False,
)
if level == "standard":
return NativeEventArtifactPlan(
keep_equity_path=True,
keep_position_path=True,
keep_fee_path=True,
keep_funding_path=True,
keep_margin_path=True,
keep_fill_ledger=True,
keep_command_terminal_state=True,
keep_event_ledger=False,
keep_command_tape=False,
materialize_pandas=True,
materialize_python_objects=True,
materialize_active_orders=False,
)
return NativeEventArtifactPlan(
keep_equity_path=True,
keep_position_path=True,
keep_fee_path=True,
keep_funding_path=True,
keep_margin_path=True,
keep_fill_ledger=True,
keep_command_terminal_state=True,
keep_event_ledger=True,
keep_command_tape=True,
materialize_pandas=True,
materialize_python_objects=True,
materialize_active_orders=True,
)
@dataclass(slots=True)
class _ReactiveOrderState:
command: OrderCommand
command_index: int
symbol_col: int
status: int = ORDER_STATUS_PENDING
active: bool = False
waiting_parent: bool = False
working_qty: float = 0.0
working_price: float = 0.0
working_trigger: float = 0.0
reject_code: int = 0
def _compact_score_command(command: OrderCommand) -> OrderCommand:
"""Drop non-execution metadata from a score-only pending order.
Static score runs do not expose fills, events, active-order snapshots, or
terminal order objects. Parent/OCO/group/tag fields remain because they
affect lifecycle matching; strategy metadata is deliberately not retained
on the hot state. Public command objects and audit runs are untouched.
"""
if not command.metadata:
return command
return replace(command, metadata={})
class _OnlineScoreState:
"""Streaming equivalent of the array-first performance metric helpers."""
__slots__ = (
"initial_capital", "n_symbols", "trading_days", "prev_equity", "first_equity",
"last_equity", "peak", "max_drawdown", "drawdown_sum", "drawdown_count",
"bar_count", "bar_mean", "bar_m2", "bar_downside_sq", "bar_downside_count", "bar_gain", "bar_loss",
"bar_win_sum", "bar_win_count", "bar_loss_sum", "bar_loss_count", "daily_day",
"daily_close", "last_daily_close", "daily_points", "daily_mean", "daily_m2",
"daily_downside_sq", "daily_downside_count", "daily_gain", "daily_loss", "daily_win_sum", "daily_win_count",
"daily_loss_sum", "daily_loss_count", "daily_peak", "daily_dd_run", "daily_dd_runs",
"prev_positions", "trade_count", "long_total", "short_total", "long_wins",
"short_wins", "last_timestamp_ns", "last_observed_bar", "max_initial_margin", "max_maintenance_margin",
)
def __init__(self, initial_capital: float, n_symbols: int, trading_days: int = 365) -> None:
self.initial_capital = float(initial_capital)
self.n_symbols = int(n_symbols)
self.trading_days = int(trading_days)
self.prev_equity = None
self.first_equity = None
self.last_equity = float(initial_capital)
self.peak = -np.inf
self.max_drawdown = 0.0
self.drawdown_sum = 0.0
self.drawdown_count = 0
self.bar_count = 0
self.bar_mean = 0.0
self.bar_m2 = 0.0
self.bar_downside_sq = 0.0
self.bar_downside_count = 0
self.bar_gain = 0.0
self.bar_loss = 0.0
self.bar_win_sum = 0.0
self.bar_win_count = 0
self.bar_loss_sum = 0.0
self.bar_loss_count = 0
self.daily_day = None
self.daily_close = None
self.last_daily_close = None
self.daily_points = 0
self.daily_mean = 0.0
self.daily_m2 = 0.0
self.daily_downside_sq = 0.0
self.daily_downside_count = 0
self.daily_gain = 0.0
self.daily_loss = 0.0
self.daily_win_sum = 0.0
self.daily_win_count = 0
self.daily_loss_sum = 0.0
self.daily_loss_count = 0
self.daily_peak = -np.inf
self.daily_dd_run = 0
self.daily_dd_runs: List[int] = []
self.prev_positions = np.zeros(self.n_symbols, dtype=np.float64)
self.trade_count = self.n_symbols
self.long_total = np.zeros(self.n_symbols, dtype=np.int64)
self.short_total = np.zeros(self.n_symbols, dtype=np.int64)
self.long_wins = np.zeros(self.n_symbols, dtype=np.int64)
self.short_wins = np.zeros(self.n_symbols, dtype=np.int64)
self.last_timestamp_ns = None
self.last_observed_bar = -1
self.max_initial_margin = 0.0
self.max_maintenance_margin = 0.0
@staticmethod
def _update_moments(value: float, count: int, mean: float, m2: float) -> tuple[int, float, float]:
count += 1
delta = value - mean
mean += delta / count
m2 += delta * (value - mean)
return count, mean, m2
def _observe_return(self, value: float, *, daily: bool) -> None:
if not np.isfinite(value):
return
if daily:
if value > 0.0:
self.daily_gain += float(value)
self.daily_win_sum += float(value)
self.daily_win_count += 1
elif value < 0.0:
self.daily_loss += float(-value)
self.daily_loss_sum += float(value)
self.daily_loss_count += 1
if value < 0.0:
self.daily_downside_sq += float(value * value)
self.daily_downside_count += 1
self.daily_points, self.daily_mean, self.daily_m2 = self._update_moments(
float(value), self.daily_points - 1, self.daily_mean, self.daily_m2
)
else:
if value > 0.0:
self.bar_gain += float(value)
self.bar_win_sum += float(value)
self.bar_win_count += 1
elif value < 0.0:
self.bar_loss += float(-value)
self.bar_loss_sum += float(value)
self.bar_loss_count += 1
if value < 0.0:
self.bar_downside_sq += float(value * value)
self.bar_downside_count += 1
self.bar_count, self.bar_mean, self.bar_m2 = self._update_moments(
float(value), self.bar_count, self.bar_mean, self.bar_m2
)
def _close_day(self) -> None:
if self.daily_close is None:
return
close = float(self.daily_close)
if self.last_daily_close is not None:
base = float(self.last_daily_close)
daily_return = (close - base) / base if base != 0.0 else 0.0
self._observe_return(float(daily_return), daily=True)
self.last_daily_close = close
self.daily_points += 1
self.daily_peak = max(self.daily_peak, close)
in_drawdown = self.daily_peak != close
if in_drawdown:
self.daily_dd_run += 1
elif self.daily_dd_run > 0:
self.daily_dd_runs.append(self.daily_dd_run)
self.daily_dd_run = 0
def observe(
self,
timestamp,
equity: float,
positions: np.ndarray,
initial_margin: float,
maintenance_margin: float,
) -> None:
"""Consume one canonical post-bar accounting observation."""
value = float(equity)
if self.first_equity is None:
self.first_equity = value
if self.prev_equity is None or self.prev_equity == 0.0:
bar_return = 0.0
else:
bar_return = value / float(self.prev_equity) - 1.0
if math.isfinite(float(bar_return)):
bar_return = float(bar_return)
self.bar_count += 1
delta = bar_return - self.bar_mean
self.bar_mean += delta / self.bar_count
self.bar_m2 += delta * (bar_return - self.bar_mean)
if bar_return > 0.0:
self.bar_gain += bar_return
self.bar_win_sum += bar_return
self.bar_win_count += 1
elif bar_return < 0.0:
self.bar_loss += -bar_return
self.bar_loss_sum += bar_return
self.bar_loss_count += 1
self.bar_downside_sq += bar_return * bar_return
self.bar_downside_count += 1
self.peak = max(self.peak, value)
drawdown = (self.peak - value) / self.peak if self.peak != 0.0 else 0.0
self.max_drawdown = max(self.max_drawdown, float(drawdown))
if drawdown > 0.0:
self.drawdown_sum += float(drawdown)
self.drawdown_count += 1
current = positions
for j in range(self.n_symbols):
position = float(current[j])
if self.bar_count > 1 and position != self.prev_positions[j]:
self.trade_count += 1
if position > 0.0:
self.long_total[j] += 1
if bar_return > 0.0:
self.long_wins[j] += 1
elif position < 0.0:
self.short_total[j] += 1
if bar_return > 0.0:
self.short_wins[j] += 1
self.prev_positions[j] = position
self.prev_equity = value
self.last_equity = value
self.last_timestamp_ns = int(timestamp) if isinstance(timestamp, (int, np.integer)) else int(pd.Timestamp(timestamp).value)
self.max_initial_margin = max(self.max_initial_margin, float(initial_margin))
self.max_maintenance_margin = max(self.max_maintenance_margin, float(maintenance_margin))
day = self.last_timestamp_ns // 86_400_000_000_000
if self.daily_day is not None and day != self.daily_day:
self._close_day()
self.daily_day = day
self.daily_close = value
def finish(self, timestamps: pd.DatetimeIndex) -> Dict[str, float]:
self._close_day()
if self.daily_dd_run > 0:
self.daily_dd_runs.append(self.daily_dd_run)
self.daily_dd_run = 0
use_daily = self.daily_points >= 2
count = self.daily_points - 1 if use_daily else self.bar_count
mean = self.daily_mean if use_daily else self.bar_mean
m2 = self.daily_m2 if use_daily else self.bar_m2
downside_sq = self.daily_downside_sq if use_daily else self.bar_downside_sq
downside_count = self.daily_downside_count if use_daily else self.bar_downside_count
gain = self.daily_gain if use_daily else self.bar_gain
loss = self.daily_loss if use_daily else self.bar_loss
win_sum = self.daily_win_sum if use_daily else self.bar_win_sum
win_count = self.daily_win_count if use_daily else self.bar_win_count
loss_sum = self.daily_loss_sum if use_daily else self.bar_loss_sum
loss_count = self.daily_loss_count if use_daily else self.bar_loss_count
if use_daily:
periods = float(self.trading_days)
else:
ns = np.asarray(timestamps.view("int64"), dtype=np.int64)
deltas = np.diff(ns).astype(np.float64) / 1_000_000_000.0
deltas = deltas[deltas > 0.0]
median_seconds = float(np.median(deltas)) if len(deltas) else 0.0
periods = 365.25 * 24.0 * 60.0 * 60.0 / median_seconds if median_seconds > 0.0 else float(self.trading_days)
std = float(np.sqrt(m2 / (count - 1))) if count >= 2 and m2 > 0.0 else 0.0
sharpe_value = float(mean / std * np.sqrt(periods)) if std > 0.0 else 0.0
downside = float(np.sqrt(downside_sq / downside_count)) if downside_count > 0 else 0.0
sortino_value = float(mean / downside * np.sqrt(periods)) if downside > 0.0 else (np.inf if mean > 0.0 else 0.0)
omega_value = float(gain / loss) if loss > 0.0 else np.inf
pf_value = omega_value
elapsed_days = 0.0
if len(timestamps) >= 2:
elapsed_days = (timestamps[-1] - timestamps[0]).total_seconds() / 86_400.0
years = elapsed_days / 365.25 if elapsed_days > 0.0 else 0.0
total_ret = (self.last_equity - self.initial_capital) / self.initial_capital
if 0.0 < elapsed_days < 1.0:
cagr_value = total_ret
elif years <= 0.0:
cagr_value = 0.0
elif self.first_equity is None or self.last_equity / self.first_equity <= 0.0:
cagr_value = -1.0
else:
annual_log = np.log(self.last_equity / self.first_equity) / years
cagr_value = float(np.expm1(np.clip(annual_log, -50.0, 50.0)))
long_hr = np.divide(self.long_wins, self.long_total, out=np.zeros_like(self.long_wins, dtype=np.float64), where=self.long_total != 0) * 100.0
short_hr = np.divide(self.short_wins, self.short_total, out=np.zeros_like(self.short_wins, dtype=np.float64), where=self.short_total != 0) * 100.0
avg_win = win_sum / win_count * 100.0 if win_count else 0.0
avg_loss = loss_sum / loss_count * 100.0 if loss_count else 0.0
hit_rate = (float(np.mean(long_hr)) + float(np.mean(short_hr))) / 200.0
avg_dd = self.drawdown_sum / self.drawdown_count if self.drawdown_count else 0.0
max_duration = max(self.daily_dd_runs) if self.daily_dd_runs else 0
avg_duration = float(np.mean(self.daily_dd_runs)) if self.daily_dd_runs else 0.0
return {
"initial_capital": float(self.initial_capital),
"final_equity": float(self.last_equity),
"total_return_pct": float(total_ret * 100.0),
"cagr_pct": float(cagr_value * 100.0),
"sharpe": sharpe_value,
"sortino": sortino_value,
"calmar": float(cagr_value / self.max_drawdown) if self.max_drawdown > 0.0 else 0.0,
"omega": omega_value,
"max_drawdown_pct": float(self.max_drawdown * 100.0),
"avg_drawdown_pct": float(avg_dd * 100.0),
"max_dd_duration_days": int(max_duration),
"avg_dd_duration_days": int(avg_duration),
"profit_factor": pf_value,
"long_hitrate_pct": float(np.mean(long_hr)),
"short_hitrate_pct": float(np.mean(short_hr)),
"avg_win_pct": float(avg_win),
"avg_loss_pct": float(avg_loss),
"expectancy_pct": float(hit_rate * avg_win + (1.0 - hit_rate) * avg_loss),
"num_trades": int(self.trade_count),
}
class _NativeEventReactiveSession:
"""
Lightweight per-bar state used only to feed reactive strategy callbacks.
Final accounting still replays the emitted command tape through the Numba
v2 kernel once. Keeping this session Python-level avoids repeated compile
and report construction while preserving a single final source of truth.
"""
def __init__(
self,
*,
idx: pd.DatetimeIndex,
symbols: List[str],
market_arrays: PreparedMarketArrays,
opens_arr: np.ndarray,
volumes_arr: np.ndarray,
constraints,
contract_sizes: np.ndarray,
leverages: np.ndarray,
fee_rates: np.ndarray,
initial_capital: float,
maintenance_ratio: float,
slippage: float,
use_funding: bool,
retain_terminal_orders: bool = True,
score_requirements: Optional[NativeEventScoreRequirements] = None,
) -> None:
self.idx = idx
self.symbols = symbols
self.symbols_tuple = tuple(symbols)
self.n_symbols = len(symbols)
self.symbol_to_col = {symbol: j for j, symbol in enumerate(symbols)}
self.market_arrays = market_arrays
self.opens_arr = opens_arr
self.volumes_arr = volumes_arr
self.constraints = constraints
# Quantity policy is immutable for a session. Cache the decision once
# so score/research loops do not scan every constraint array per bar.
self.constraints_enabled = bool(constraints.enabled)
self.contract_sizes = contract_sizes
self.leverages = leverages
self.fee_rates = fee_rates
self.initial_capital = float(initial_capital)
self.maintenance_ratio = float(maintenance_ratio)
self.slippage = float(slippage)
self.use_funding = bool(use_funding)
self.retain_terminal_orders = bool(retain_terminal_orders)
self.score_requirements = score_requirements
self.retain_fill_ledger = bool(
score_requirements is None or score_requirements.need_fill_ledger
)
self.retain_event_ledger = bool(
score_requirements is None or score_requirements.need_event_ledger
)
self.emit_context_fills = bool(
score_requirements is None or score_requirements.need_context_fills
)
self.emit_context_events = bool(
score_requirements is None or score_requirements.need_context_events
)
self.emit_context_active_orders = bool(
score_requirements is None or score_requirements.need_context_active_orders
)
self.emit_context_positions = bool(
score_requirements is None or score_requirements.need_context_positions
)
self.emit_context_margin = bool(
score_requirements is None or score_requirements.need_context_margin
)
self.compact_score_state = bool(
score_requirements is not None
and not score_requirements.need_context_fills
and not score_requirements.need_context_events
and not score_requirements.need_context_active_orders
and not score_requirements.need_context_positions
and not score_requirements.need_context_margin
and not score_requirements.need_fill_ledger
and not score_requirements.need_event_ledger
and not score_requirements.need_terminal_orders
)
self.current_pos = np.zeros(len(symbols), dtype=np.float64)
self.equity = float(initial_capital)
self.liquidated = False
self.liquidation_bar = -1
self.liquidation_reason = LIQ_NONE
self.command_seq = 0
self.orders: List[_ReactiveOrderState] = []
self.pending: List[_ReactiveOrderState] = []
self.id_to_order: Dict[str, _ReactiveOrderState] = {}
self.scheduled: Dict[int, List[OrderCommand]] = {}
self.fills_by_bar: Dict[int, List[NativeFillEvent]] = {}
self.events_by_bar: Dict[int, List[NativeOrderEvent]] = {}
self.fills: List[NativeFillEvent] = []
self.events: List[NativeOrderEvent] = []
self.fill_count = 0
self.event_count = 0
self.rejected_count = 0
self.canceled_count = 0
self.expired_count = 0
self.total_fee = 0.0
self.total_funding = 0.0
self.total_turnover = 0.0
self.children_by_parent_id: Dict[str, List[_ReactiveOrderState]] = {}
self.members_by_oco_group: Dict[str, List[_ReactiveOrderState]] = {}
self.expiry_by_bar: Dict[int, List[_ReactiveOrderState]] = {}
self.processed_bar = -1
self.last_initial_margin = 0.0
self.last_maintenance_margin = 0.0
self.margin_bar = -1
self.margin_dirty = True
self.size_helper = NativeEventBackend._reactive_size_helper(
symbols=self.symbols,
constraints=self.constraints,
contract_sizes=self.contract_sizes,
)
self.empty_fills: tuple[NativeFillEvent, ...] = ()
self.empty_events: tuple[NativeOrderEvent, ...] = ()
self.empty_active_orders: tuple[NativeActiveOrderSnapshot, ...] = ()
self._active_snapshot_cache: tuple[NativeActiveOrderSnapshot, ...] = self.empty_active_orders
self._active_snapshot_dirty = True
self.execution_counters = {
"bars_processed": 0,
"bars_with_commands": 0,
"contexts_materialized": 0,
"timestamp_objects_materialized": 0,
"active_snapshot_materializations": 0,
"empty_command_batches_skipped": 0,
"constraint_preflight_calls": 0,
"constraint_preflight_skipped": 0,
"commands_retimed": 0,
"commands_quantized": 0,
}
n_bars = len(idx)
n_syms = len(symbols)
requirements = score_requirements
self.equity_path = np.zeros(n_bars, dtype=np.float64) if requirements is None or requirements.need_equity_path else None
self.pos_path = np.zeros((n_bars, n_syms), dtype=np.float64) if requirements is None or requirements.need_position_path else None
self.fee_path = np.zeros(n_bars, dtype=np.float64) if requirements is None or requirements.need_fee_path else None
self.turnover_path = np.zeros(n_bars, dtype=np.float64) if requirements is None or requirements.need_turnover_path else None
self.funding_path = np.zeros(n_bars, dtype=np.float64) if requirements is None or requirements.need_funding_path else None
self.initial_margin_path = np.zeros(n_bars, dtype=np.float64) if requirements is None or requirements.need_margin_path else None
self.maintenance_margin_path = np.zeros(n_bars, dtype=np.float64) if requirements is None or requirements.need_margin_path else None
self.rejected_bar = np.zeros(n_bars, dtype=np.int64) if requirements is None or requirements.need_rejection_path else None
self.canceled_bar = np.zeros(n_bars, dtype=np.int64) if requirements is None or requirements.need_cancellation_path else None
self.online_score = (
_OnlineScoreState(self.initial_capital, n_syms)
if requirements is not None and requirements.need_trade_stats
else None
)
self._record_bar(0)
def schedule(self, bar: int, commands: Sequence[OrderCommand]) -> None:
if not commands or bar >= len(self.idx):
return
self.scheduled.setdefault(int(bar), []).extend(commands)
def release_bar_payload(self, bar: int) -> None:
self.fills_by_bar.pop(int(bar), None)
self.events_by_bar.pop(int(bar), None)
def process_bar(self, bar: int) -> None:
if bar <= self.processed_bar:
return
for i in range(self.processed_bar + 1, int(bar) + 1):
self._process_single_bar(i)
self.processed_bar = i
self.execution_counters["bars_processed"] += 1
def context(self, bar: int) -> NativeStrategyContext:
self.process_bar(bar)
self.execution_counters["contexts_materialized"] += 1
self.execution_counters["timestamp_objects_materialized"] += 1
init_margin, maint_margin = self._refresh_close_margin(bar)
if self.emit_context_positions and self.n_symbols == 1:
positions = {self.symbols[0]: float(self.current_pos[0])}
elif self.emit_context_positions:
positions = {symbol: float(self.current_pos[j]) for j, symbol in enumerate(self.symbols)}
else:
positions = {}
if self.emit_context_fills:
fills_this_bar = tuple(self.fills_by_bar.get(int(bar), self.empty_fills))
else:
fills_this_bar = self.empty_fills
if self.emit_context_events:
events_this_bar = tuple(self.events_by_bar.get(int(bar), self.empty_events))
else:
events_this_bar = self.empty_events
if not self.emit_context_margin:
init_margin = 0.0
maint_margin = 0.0
return NativeStrategyContext(
bar_index=int(bar),
timestamp=self.idx[int(bar)],
open=self.opens_arr[int(bar)],
high=self.market_arrays.highs[int(bar)],
low=self.market_arrays.lows[int(bar)],
close=self.market_arrays.closes[int(bar)],
volume=self.volumes_arr[int(bar)],
equity=float(self.equity),
available_equity=float(self.equity - init_margin),
initial_margin=float(init_margin),
maintenance_margin=float(maint_margin),
positions=positions,
fills_this_bar=fills_this_bar,
order_events_this_bar=events_this_bar,
active_orders=self._active_snapshots() if self.emit_context_active_orders else self.empty_active_orders,
liquidated=bool(self.liquidated),
symbols=self.symbols_tuple,
size_order=self.size_helper,
)
def _process_single_bar(self, bar: int) -> None:
if self.liquidated:
self._record_bar(bar)
return
if bar > 0:
for s in range(len(self.symbols)):
p = self.current_pos[s]
if p != 0.0:
self.equity += (
p
* (self.market_arrays.closes[bar, s] - self.market_arrays.closes[bar - 1, s])
* self.contract_sizes[s]
)
if bar > 0 and self._liquidated_intrabar(bar):
self._liquidate(bar, LIQ_INTRABAR)
self._record_bar(bar)
return
if bar > 0 and self.use_funding and self.market_arrays.is_funding_bar[bar]:
funding_cost = 0.0
for s in range(len(self.symbols)):
p = self.current_pos[s]
if p != 0.0:
funding_cost += (
p
* self.market_arrays.closes[bar, s]
* self.contract_sizes[s]
* self.market_arrays.funding[bar, s]
)
self.equity -= funding_cost
self.total_funding += float(funding_cost)
if self.funding_path is not None:
self.funding_path[bar] += funding_cost
if bar > 0:
_, close_mm = self._refresh_close_margin(bar)
if close_mm > 0.0 and self.equity <= close_mm:
self._liquidate(bar, LIQ_AFTER_FUNDING)
self._record_bar(bar)
return
self._expire_orders(bar)
for command in self.scheduled.pop(bar, ()):
self._apply_command(bar, command)
self._match_orders(bar)
self._compact_pending()
_, close_mm = self._refresh_close_margin(bar)
if close_mm > 0.0 and self.equity <= close_mm:
self._liquidate(bar, LIQ_AFTER_ORDER)
self._record_bar(bar)
def _record_bar(self, bar: int) -> None:
if bar < 0 or bar >= len(self.idx):
return
init_margin, maint_margin = self._refresh_close_margin(bar)
if self.equity_path is not None:
self.equity_path[bar] = float(self.equity)
if self.pos_path is not None:
self.pos_path[bar, :] = self.current_pos
if self.initial_margin_path is not None:
self.initial_margin_path[bar] = float(init_margin)
if self.maintenance_margin_path is not None:
self.maintenance_margin_path[bar] = float(maint_margin)