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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
// FILE-SIZE-OK: 1184 lines — tests extracted to tests/processor_tests.rs
//! Core open deviation bar processing algorithm
//!
//! Implements non-lookahead bias open deviation bar construction where bars close when
//! price moves ±threshold dbps from the bar's OPEN price.
use crate::checkpoint::{
AnomalySummary, Checkpoint, CheckpointError, PositionVerification, PriceWindow,
};
use crate::fixed_point::FixedPoint;
use crate::interbar::{InterBarConfig, TradeHistory}; // Issue #59
use crate::spread_accumulator::SpreadAccumulator; // Phase 53
use crate::trade::BreachMode; // Phase 53: Breach mode gating for SpreadAccumulator
// Issue #59: Intra-bar features - using compute_intra_bar_features_with_config (Issue #128)
use crate::types::{AggTrade, OpenDeviationBar};
#[cfg(feature = "python")]
use pyo3::prelude::*;
use smallvec::SmallVec; // Issue #119: Trade accumulation with inline buffer (512 slots ≈ 29KB)
// Re-export ProcessingError from errors.rs (Phase 2a extraction)
pub use crate::errors::ProcessingError;
// Re-export ExportOpenDeviationBarProcessor from export_processor.rs (Phase 2d extraction)
pub use crate::export_processor::ExportOpenDeviationBarProcessor;
/// Open deviation bar processor with non-lookahead bias guarantee
pub struct OpenDeviationBarProcessor {
/// Threshold in decimal basis points (250 = 25bps, v3.0.0+)
threshold_decimal_bps: u32,
/// Issue #96 Task #98: Pre-computed threshold ratio for fast delta calculation
/// Stores (threshold_decimal_bps * SCALE) / BASIS_POINTS_SCALE as fixed-point
/// This allows compute_range_thresholds() to compute delta = (price * ratio) / SCALE
/// without repeated division, avoiding i128 arithmetic in hot path.
/// Performance: Eliminates BASIS_POINTS_SCALE division on every bar creation.
/// Made public for testing purposes.
pub threshold_ratio: i64,
/// Current bar state for streaming processing (Q19)
/// Enables get_incomplete_bar() and stateful process_single_trade()
current_bar_state: Option<OpenDeviationBarState>,
/// Price window for checkpoint hash verification
price_window: PriceWindow,
/// Last processed trade ID (for gap detection on resume)
last_trade_id: Option<i64>,
/// Last completed bar's trade ID for dedup floor initialization (v1.4)
///
/// Updated ONLY on bar completion (process_single_trade returns Some) and
/// orphan emission (reset_at_ouroboros). NOT updated on every trade.
/// This gives committed_floors a floor that excludes the forming bar tail,
/// preventing suppression of bars at the REST-to-WS junction.
last_completed_bar_tid: Option<i64>,
/// Last processed timestamp (for position verification)
last_timestamp_us: i64,
/// Anomaly tracking for debugging
anomaly_summary: AnomalySummary,
/// Flag indicating this processor was created from a checkpoint
/// When true, process_agg_trade_records will continue from existing bar state
resumed_from_checkpoint: bool,
/// Prevent bars from closing on same timestamp as they opened (Issue #36)
///
/// When true (default): A bar cannot close until a trade arrives with a
/// different timestamp than the bar's open_time. This prevents "instant bars"
/// during flash crashes where multiple trades occur at the same millisecond.
///
/// When false: Legacy behavior - bars can close on any breach regardless
/// of timestamp, which may produce bars with identical timestamps.
prevent_same_timestamp_close: bool,
/// Deferred bar open flag (Issue #46)
///
/// When true: The previous trade triggered a threshold breach and closed a bar.
/// The next trade arriving via `process_single_trade()` should open a new bar
/// instead of being treated as a continuation.
///
/// This matches the batch path's `defer_open` semantics in
/// `process_agg_trade_records()` where the breaching trade closes the current
/// bar and the NEXT trade opens the new bar.
defer_open: bool,
/// Trade history for inter-bar feature computation (Issue #59)
///
/// Ring buffer of recent trades for computing lookback-based features.
/// When Some, features are computed from trades BEFORE each bar's open_time.
/// When None, inter-bar features are disabled (all lookback_* fields = None).
trade_history: Option<TradeHistory>,
/// Configuration for inter-bar features (Issue #59)
///
/// Controls lookback mode (fixed count or time window) and which feature
/// tiers to compute. When None, inter-bar features are disabled.
inter_bar_config: Option<InterBarConfig>,
/// Enable intra-bar feature computation (Issue #59)
///
/// When true, the processor accumulates trades during bar construction
/// and computes 22 features from trades WITHIN each bar at bar close.
/// Features include ITH (Investment Time Horizon), statistical, and
/// complexity metrics. When false, all intra_* fields are None.
include_intra_bar_features: bool,
/// Issue #128: Configuration for intra-bar feature computation.
/// Controls which complexity features (Hurst, PE) are computed.
intra_bar_config: crate::intrabar::IntraBarConfig,
/// Issue #112: Maximum timestamp gap in microseconds before discarding a forming bar
///
/// When resuming from checkpoint with a forming bar, if the gap between
/// the forming bar's close_time and the first incoming trade exceeds this
/// threshold, the forming bar is discarded as an orphan (same as ouroboros reset).
/// This prevents "oversized" bars caused by large data gaps (e.g., 38-hour outages).
///
/// Default: 3,600,000,000 μs (1 hour)
max_gap_us: i64,
/// Phase 53: Breach mode determines which price is tested against thresholds
/// and whether SpreadAccumulator is active (Portcullis/Mid/Directional = Some,
/// Last = None for zero overhead on crypto).
breach_mode: BreachMode,
/// Phase 54: Controls Tier 2+3 advanced spread feature computation (SA-04)
/// When true, SpreadAccumulator computes 11 additional features.
/// When false, advanced features return None (zero overhead).
compute_spread_advanced: bool,
}
/// Cold path: scan trades to find first unsorted pair and return error
/// Extracted from validate_trade_ordering() to improve hot-path code layout
#[cold]
#[inline(never)]
fn find_unsorted_trade(trades: &[AggTrade]) -> Result<(), ProcessingError> {
for i in 1..trades.len() {
let prev = &trades[i - 1];
let curr = &trades[i];
if curr.timestamp < prev.timestamp
|| (curr.timestamp == prev.timestamp && curr.ref_id <= prev.ref_id)
{
return Err(ProcessingError::UnsortedTrades {
index: i,
prev_time: prev.timestamp,
prev_id: prev.ref_id,
curr_time: curr.timestamp,
curr_id: curr.ref_id,
});
}
}
Ok(())
}
/// Cold path: construct unsorted trade error
/// Extracted to keep error construction out of the hot validation loop
#[cold]
#[inline(never)]
fn unsorted_trade_error(
index: usize,
prev: &AggTrade,
curr: &AggTrade,
) -> Result<(), ProcessingError> {
Err(ProcessingError::UnsortedTrades {
index,
prev_time: prev.timestamp,
prev_id: prev.ref_id,
curr_time: curr.timestamp,
curr_id: curr.ref_id,
})
}
impl OpenDeviationBarProcessor {
/// Create new processor with given threshold
///
/// Uses default behavior: `prevent_same_timestamp_close = true` (Issue #36)
///
/// # Arguments
///
/// * `threshold_decimal_bps` - Threshold in **decimal basis points**
/// - Example: `250` → 25bps = 0.25%
/// - Example: `10` → 1bps = 0.01%
/// - Minimum: `1` → 0.1bps = 0.001%
///
/// # Breaking Change (v3.0.0)
///
/// Prior to v3.0.0, `threshold_decimal_bps` was in 1bps units.
/// **Migration**: Multiply all threshold values by 10.
pub fn new(threshold_decimal_bps: u32) -> Result<Self, ProcessingError> {
Self::with_options(threshold_decimal_bps, true)
}
/// Create new processor with explicit timestamp gating control
///
/// # Arguments
///
/// * `threshold_decimal_bps` - Threshold in **decimal basis points**
/// * `prevent_same_timestamp_close` - If true, bars cannot close until
/// timestamp advances from open_time. This prevents "instant bars" during
/// flash crashes. Set to false for legacy behavior (pre-v9).
///
/// # Example
///
/// ```ignore
/// // Default behavior (v9+): timestamp gating enabled
/// let processor = OpenDeviationBarProcessor::new(250)?;
///
/// // Legacy behavior: allow instant bars
/// let processor = OpenDeviationBarProcessor::with_options(250, false)?;
/// ```
pub fn with_options(
threshold_decimal_bps: u32,
prevent_same_timestamp_close: bool,
) -> Result<Self, ProcessingError> {
// Validation bounds (v3.0.0: dbps units)
// Min: 1 dbps = 0.001%
// Max: 100,000 dbps = 100%
if threshold_decimal_bps < 1 {
return Err(ProcessingError::InvalidThreshold {
threshold_decimal_bps,
});
}
if threshold_decimal_bps > 100_000 {
return Err(ProcessingError::InvalidThreshold {
threshold_decimal_bps,
});
}
// Issue #96 Task #98: Pre-compute threshold ratio
// Ratio = (threshold_decimal_bps * SCALE) / BASIS_POINTS_SCALE
// This is used in compute_range_thresholds() for fast delta calculation
let threshold_ratio = ((threshold_decimal_bps as i64) * crate::fixed_point::SCALE)
/ (crate::fixed_point::BASIS_POINTS_SCALE as i64);
Ok(Self {
threshold_decimal_bps,
threshold_ratio,
current_bar_state: None,
price_window: PriceWindow::new(),
last_trade_id: None,
last_completed_bar_tid: None,
last_timestamp_us: 0,
anomaly_summary: AnomalySummary::default(),
resumed_from_checkpoint: false,
prevent_same_timestamp_close,
defer_open: false,
trade_history: None, // Issue #59: disabled by default
inter_bar_config: None, // Issue #59: disabled by default
include_intra_bar_features: false, // Issue #59: disabled by default
intra_bar_config: crate::intrabar::IntraBarConfig::default(), // Issue #128
max_gap_us: 3_600_000_000, // Issue #112: 1 hour default
breach_mode: BreachMode::Last, // Phase 53: Default for crypto (no spread accumulator)
compute_spread_advanced: false, // Phase 54: Default off for base-only use cases
})
}
/// Create new processor with explicit breach mode for Portcullis support (Phase 53)
///
/// When breach_mode is Portcullis, Mid, or Directional, the processor initializes
/// a SpreadAccumulator on each new bar and calls update() per tick with bid/ask data.
/// When breach_mode is Last (default), spread_accumulator remains None (zero overhead).
pub fn new_with_breach_mode(
threshold_decimal_bps: u32,
breach_mode: BreachMode,
) -> Result<Self, ProcessingError> {
let mut processor = Self::with_options(threshold_decimal_bps, true)?;
processor.breach_mode = breach_mode;
Ok(processor)
}
/// Create processor with breach mode and explicit timestamp gating (Phase 53)
///
/// Full-control constructor combining breach mode and timestamp gate options.
pub fn with_breach_mode(
threshold_decimal_bps: u32,
prevent_same_timestamp_close: bool,
breach_mode: BreachMode,
) -> Result<Self, ProcessingError> {
let mut processor =
Self::with_options(threshold_decimal_bps, prevent_same_timestamp_close)?;
processor.breach_mode = breach_mode;
Ok(processor)
}
/// Create processor with breach mode and advanced spread features (Phase 54)
///
/// Combines breach mode selection with the compute_spread_advanced toggle.
/// When `compute_spread_advanced` is true, SpreadAccumulator computes 11
/// additional Tier 2+3 features. When false, advanced features are None.
pub fn with_spread_advanced(
threshold_decimal_bps: u32,
breach_mode: BreachMode,
compute_spread_advanced: bool,
) -> Result<Self, ProcessingError> {
let mut processor = Self::with_options(threshold_decimal_bps, true)?;
processor.breach_mode = breach_mode;
processor.compute_spread_advanced = compute_spread_advanced;
Ok(processor)
}
/// Consuming builder: set the compute_spread_advanced flag (#357).
///
/// Lets the PyO3 constructor enable advanced spread features after
/// choosing a breach mode via `with_breach_mode()`. Chainable with the
/// other `with_*` builders used by core_bindings.rs.
pub fn set_spread_advanced(mut self, enabled: bool) -> Self {
self.compute_spread_advanced = enabled;
self
}
/// Get the current breach mode
pub fn breach_mode(&self) -> BreachMode {
self.breach_mode
}
/// Phase 51: Substitute trade.price with mid-price for breach modes that
/// accumulate OHLCV/VWAP/turnover from quote midpoints (Portcullis, Mid).
///
/// For `Last` and `Directional`, returns the trade unchanged.
/// For `Portcullis`/`Mid`, returns a copy with `price = (bid + ask) / 2` when
/// both quotes are present; otherwise returns the trade unchanged.
#[inline]
fn effective_trade(&self, trade: &AggTrade) -> AggTrade {
match self.breach_mode {
BreachMode::Portcullis | BreachMode::Mid => {
if let (Some(bid), Some(ask)) = (trade.best_bid, trade.best_ask) {
let mid = crate::FixedPoint(i64::midpoint(bid.0, ask.0));
AggTrade {
price: mid,
..*trade
}
} else {
*trade
}
}
BreachMode::Last | BreachMode::Directional => *trade,
}
}
/// Phase 51: Breach decision honoring a given `breach_mode`.
///
/// Associated function (no `&self`) so callers can hold a mutable borrow on
/// `self.current_bar_state` and still invoke the breach check.
///
/// - `Last`/`Mid`/`Directional`: standard `price >= upper || price <= lower`
/// (caller is expected to pass an already-substituted effective trade for `Mid`).
/// - `Portcullis`: asymmetric — breach iff `bid >= upper` OR `ask <= lower`.
/// The original (un-substituted) trade must be supplied so its bid/ask survive.
#[inline]
fn check_breach_mode(
breach_mode: BreachMode,
trade: &AggTrade,
upper: crate::FixedPoint,
lower: crate::FixedPoint,
) -> bool {
match breach_mode {
BreachMode::Portcullis => {
if let (Some(bid), Some(ask)) = (trade.best_bid, trade.best_ask) {
bid >= upper || ask <= lower
} else {
trade.price >= upper || trade.price <= lower
}
}
BreachMode::Last | BreachMode::Mid | BreachMode::Directional => {
trade.price >= upper || trade.price <= lower
}
}
}
/// Get the compute_spread_advanced setting (Phase 54)
pub fn compute_spread_advanced(&self) -> bool {
self.compute_spread_advanced
}
/// Get the prevent_same_timestamp_close setting
pub fn prevent_same_timestamp_close(&self) -> bool {
self.prevent_same_timestamp_close
}
/// Enable inter-bar feature computation with the given configuration (Issue #59)
///
/// When enabled, the processor maintains a trade history buffer and computes
/// lookback-based microstructure features on each bar close. Features are
/// computed from trades that occurred BEFORE each bar's open_time, ensuring
/// no lookahead bias.
///
/// Uses a local entropy cache (default behavior, backward compatible).
/// For multi-symbol workloads, use `with_inter_bar_config_and_cache()` with a global cache.
///
/// # Arguments
///
/// * `config` - Configuration controlling lookback mode and feature tiers
///
/// # Example
///
/// ```ignore
/// use opendeviationbar_core::processor::OpenDeviationBarProcessor;
/// use opendeviationbar_core::interbar::{InterBarConfig, LookbackMode};
///
/// let processor = OpenDeviationBarProcessor::new(1000)?
/// .with_inter_bar_config(InterBarConfig {
/// lookback_mode: LookbackMode::FixedCount(500),
/// compute_tier2: true,
/// compute_tier3: true,
/// ..Default::default()
/// });
/// ```
pub fn with_inter_bar_config(self, config: InterBarConfig) -> Self {
self.with_inter_bar_config_and_cache(config, None)
}
/// Enable inter-bar feature computation with optional external entropy cache
///
/// Issue #145 Phase 3: Multi-Symbol Entropy Cache Sharing
///
/// # Arguments
///
/// * `config` - Configuration controlling lookback mode and feature tiers
/// * `external_cache` - Optional shared entropy cache from `get_global_entropy_cache()`
/// - If provided: Uses the shared global cache (recommended for multi-symbol)
/// - If None: Creates a local 128-entry cache (default, backward compatible)
///
/// # Usage
///
/// ```ignore
/// use opendeviationbar_core::{processor::OpenDeviationBarProcessor, entropy_cache_global::get_global_entropy_cache, interbar::InterBarConfig};
///
/// // Single-symbol: use local cache (default)
/// let processor = OpenDeviationBarProcessor::new(1000)?
/// .with_inter_bar_config(config);
///
/// // Multi-symbol: share global cache
/// let global_cache = get_global_entropy_cache();
/// let processor = OpenDeviationBarProcessor::new(1000)?
/// .with_inter_bar_config_and_cache(config, Some(global_cache));
/// ```
pub fn with_inter_bar_config_and_cache(
mut self,
config: InterBarConfig,
external_cache: Option<
std::sync::Arc<parking_lot::RwLock<crate::interbar_math::EntropyCache>>,
>,
) -> Self {
self.trade_history = Some(TradeHistory::new_with_cache(config.clone(), external_cache));
self.inter_bar_config = Some(config);
self
}
/// Check if inter-bar features are enabled
pub fn inter_bar_enabled(&self) -> bool {
self.inter_bar_config.is_some()
}
/// Issue #112: Configure maximum timestamp gap for checkpoint recovery
///
/// When resuming from checkpoint with a forming bar, if the gap between
/// the forming bar's close_time and the first incoming trade exceeds this
/// threshold, the forming bar is discarded as an orphan.
///
/// # Arguments
///
/// * `max_gap_us` - Maximum gap in microseconds (default: 3,600,000,000 = 1 hour)
pub fn with_max_gap(mut self, max_gap_us: i64) -> Self {
self.max_gap_us = max_gap_us;
self
}
/// Get the maximum gap threshold in microseconds
pub fn max_gap_us(&self) -> i64 {
self.max_gap_us
}
/// Enable intra-bar feature computation (Issue #59)
///
/// When enabled, the processor accumulates trades during bar construction
/// and computes 22 features from trades WITHIN each bar at bar close:
/// - 8 ITH features (Investment Time Horizon)
/// - 12 statistical features (OFI, intensity, Kyle lambda, etc.)
/// - 2 complexity features (Hurst exponent, permutation entropy)
///
/// # Memory Note
///
/// Trades are accumulated per-bar and freed when the bar closes.
/// Typical 1000 dbps bar: ~50-500 trades, ~2-24 KB overhead.
///
/// # Example
///
/// ```ignore
/// let processor = OpenDeviationBarProcessor::new(1000)?
/// .with_intra_bar_features();
/// ```
pub fn with_intra_bar_features(mut self) -> Self {
self.include_intra_bar_features = true;
self
}
/// Check if intra-bar features are enabled
pub fn intra_bar_enabled(&self) -> bool {
self.include_intra_bar_features
}
/// Re-enable inter-bar features on an existing processor (Issue #97).
///
/// Used after `from_checkpoint()` to restore microstructure config that
/// is not preserved in checkpoint state. Uses a local entropy cache by default.
/// For multi-symbol workloads, use `set_inter_bar_config_with_cache()` with a global cache.
pub fn set_inter_bar_config(&mut self, config: InterBarConfig) {
self.set_inter_bar_config_with_cache(config, None);
}
/// Re-enable inter-bar features with optional external entropy cache (Issue #145 Phase 3).
///
/// Used after `from_checkpoint()` to restore microstructure config that
/// is not preserved in checkpoint state. Allows specifying a shared entropy cache
/// for multi-symbol processors.
pub fn set_inter_bar_config_with_cache(
&mut self,
config: InterBarConfig,
external_cache: Option<
std::sync::Arc<parking_lot::RwLock<crate::interbar_math::EntropyCache>>,
>,
) {
self.trade_history = Some(TradeHistory::new_with_cache(config.clone(), external_cache));
self.inter_bar_config = Some(config);
}
/// Re-enable intra-bar features on an existing processor (Issue #97).
pub fn set_intra_bar_features(&mut self, enabled: bool) {
self.include_intra_bar_features = enabled;
}
/// Issue #128: Set intra-bar feature configuration.
/// Controls which complexity features (Hurst, PE) are computed.
pub fn with_intra_bar_config(mut self, config: crate::intrabar::IntraBarConfig) -> Self {
self.intra_bar_config = config;
self
}
/// Issue #128: Set intra-bar feature configuration on existing processor.
pub fn set_intra_bar_config(&mut self, config: crate::intrabar::IntraBarConfig) {
self.intra_bar_config = config;
}
/// Process a single trade and return completed bar if any
///
/// Maintains internal state for streaming use case. State persists across calls
/// until a bar completes (threshold breach), enabling get_incomplete_bar().
///
/// # Arguments
///
/// * `trade` - Single aggregated trade to process
///
/// # Returns
///
/// `Some(OpenDeviationBar)` if a bar was completed, `None` otherwise
///
/// # State Management
///
/// - First trade: Initializes new bar state
/// - Subsequent trades: Updates existing bar or closes on breach
/// - Breach: Returns completed bar, starts new bar with breaching trade
///
/// Issue #96 Task #78: Accept borrowed AggTrade to eliminate clones in fan-out loops.
/// Streaming pipelines (4+ thresholds) were cloning ~57 byte trades per processor.
/// Signature change to `&AggTrade` eliminates 4-8x unnecessary allocations.
/// Issue #96 Task #84: `#[inline]` — main hot-path entry point called on every trade.
#[inline]
pub fn process_single_trade(
&mut self,
trade: &AggTrade,
) -> Result<Option<OpenDeviationBar>, ProcessingError> {
// Track price and position for checkpoint
self.price_window.push(trade.price);
self.last_trade_id = Some(trade.ref_id);
self.last_timestamp_us = trade.timestamp;
// Issue #59: Push trade to history buffer for inter-bar feature computation
// This must happen BEFORE bar processing so lookback window includes recent trades
if let Some(ref mut history) = self.trade_history {
history.push(trade);
}
// Phase 51: Substitute trade.price with mid-price for Portcullis/Mid modes.
// Original trade is preserved (bid/ask) for breach detection and SpreadAccumulator.
let effective = self.effective_trade(trade);
// Issue #46: If previous call triggered a breach, this trade opens the new bar.
// This matches the batch path's defer_open semantics - the breaching trade
// closes the current bar, and the NEXT trade opens the new bar.
if self.defer_open {
// Issue #68: Notify history that new bar is opening (preserves pre-bar trades)
if let Some(ref mut history) = self.trade_history {
history.on_bar_open(effective.timestamp);
}
self.current_bar_state = Some(if self.include_intra_bar_features {
OpenDeviationBarState::new_with_trade_accumulation(
&effective,
self.threshold_ratio,
&self.breach_mode,
self.compute_spread_advanced,
)
} else {
OpenDeviationBarState::new(
&effective,
self.threshold_ratio,
&self.breach_mode,
self.compute_spread_advanced,
)
});
self.defer_open = false;
return Ok(None);
}
match &mut self.current_bar_state {
None => {
// First trade - initialize new bar
// Issue #68: Notify history that new bar is opening (preserves pre-bar trades)
if let Some(ref mut history) = self.trade_history {
history.on_bar_open(effective.timestamp);
}
self.current_bar_state = Some(if self.include_intra_bar_features {
OpenDeviationBarState::new_with_trade_accumulation(
&effective,
self.threshold_ratio,
&self.breach_mode,
self.compute_spread_advanced,
)
} else {
OpenDeviationBarState::new(
&effective,
self.threshold_ratio,
&self.breach_mode,
self.compute_spread_advanced,
)
});
Ok(None)
}
Some(bar_state) => {
// Issue #59 & #96 Task #44: Accumulate trade for intra-bar features (before breach check)
// Pass the ORIGINAL trade so SpreadAccumulator sees raw bid/ask quotes.
bar_state.accumulate_trade(trade, self.include_intra_bar_features);
// Phase 51: Breach decision uses bid/ask asymmetry for Portcullis;
// pass ORIGINAL trade (not effective) so bid/ask are visible.
let price_breaches = Self::check_breach_mode(
self.breach_mode,
trade,
bar_state.upper_threshold,
bar_state.lower_threshold,
);
// Timestamp gate (Issue #36): prevent bars from closing on same timestamp
// This eliminates "instant bars" during flash crashes where multiple trades
// occur at the same millisecond.
let timestamp_allows_close = !self.prevent_same_timestamp_close
|| effective.timestamp != bar_state.bar.open_time;
if price_breaches && timestamp_allows_close {
// Breach detected AND timestamp changed - close current bar
// #356: gap detection only runs for breach modes with sequential ref_ids
bar_state
.bar
.update_with_trade(&effective, self.breach_mode.has_sequential_ref_ids());
// Validation: Ensure high/low include open/close extremes
debug_assert!(
bar_state.bar.high >= bar_state.bar.open.max(bar_state.bar.close)
);
debug_assert!(bar_state.bar.low <= bar_state.bar.open.min(bar_state.bar.close));
// Compute microstructure features at bar finalization (Issue #25)
bar_state.bar.compute_microstructure_features();
// Issue #59: Compute inter-bar features from lookback window
// Features are computed from trades BEFORE bar.open_time (no lookahead)
if let Some(ref mut history) = self.trade_history {
let inter_bar_features = history.compute_features(bar_state.bar.open_time);
bar_state.bar.set_inter_bar_features(&inter_bar_features);
// Issue #68: Notify history that bar is closing (resumes normal pruning)
history.on_bar_close();
}
// Issue #59: Compute intra-bar features from accumulated trades
if self.include_intra_bar_features {
// Issue #96 Task #173: Use reusable scratch buffers from bar_state
let mut intra_bar_features =
crate::intrabar::compute_intra_bar_features_with_config(
&bar_state.accumulated_trades,
&mut bar_state.scratch_prices,
&mut bar_state.scratch_volumes,
&self.intra_bar_config, // Issue #128
);
// #363 follow-up: override drawdown/runup with streaming-correct
// values (computed over ALL trades, not just the capped buffer).
if let Some((dd, ru)) = bar_state.intra_stream.finalize() {
intra_bar_features.intra_max_drawdown =
Some(crate::intrabar::normalize::normalize_drawdown(dd));
intra_bar_features.intra_max_runup =
Some(crate::intrabar::normalize::normalize_runup(ru));
}
bar_state.bar.set_intra_bar_features(&intra_bar_features);
}
// Phase 53: Finalize spread features from SpreadAccumulator
if let Some(ref acc) = bar_state.spread_accumulator {
let spread_features = acc.finalize();
bar_state.bar.set_spread_features(&spread_features);
}
// Move bar out instead of cloning — bar_state borrow ends after
// last use above (NLL), so take() is safe here.
let completed_bar = self.current_bar_state.take().unwrap().bar;
// v1.4: Track last completed bar's trade ID for dedup floor
self.last_completed_bar_tid = Some(completed_bar.last_agg_trade_id);
// Issue #46: Don't start new bar with breaching trade.
// Next trade will open the new bar via defer_open.
self.defer_open = true;
Ok(Some(completed_bar))
} else {
// Either no breach OR same timestamp (gate active) - update existing bar
// #356: gate gap detection on breach mode
bar_state
.bar
.update_with_trade(&effective, self.breach_mode.has_sequential_ref_ids());
Ok(None)
}
}
}
}
/// Get any incomplete bar currently being processed
///
/// Returns clone of current bar state for inspection without consuming it.
/// Useful for final bar at stream end or progress monitoring.
///
/// # Returns
///
/// `Some(OpenDeviationBar)` if bar is in progress, `None` if no active bar
pub fn get_incomplete_bar(&self) -> Option<OpenDeviationBar> {
self.current_bar_state.as_ref().map(|state| {
let mut bar = state.bar.clone();
// Issue #275: Compute microstructure features for incomplete bars.
// Without this, duration_us (and derived trade_intensity) remain at
// their default of 0 when the bar is inspected mid-construction.
bar.compute_microstructure_features();
bar
})
}
/// Get the last processed aggregate trade ID (for gap detection on reconnect).
///
/// Returns `None` for fresh processors that have not yet processed any trades.
/// After checkpoint restore, returns the last trade ID from the checkpoint.
pub fn last_agg_trade_id(&self) -> Option<i64> {
self.last_trade_id
}
/// Get the last COMPLETED bar's aggregate trade ID.
///
/// Unlike `last_agg_trade_id()` which includes the forming bar tail,
/// this returns the trade ID from the most recently completed or orphaned bar.
/// Used by committed_floors initialization to avoid suppressing junction bars.
///
/// Returns `None` for fresh processors that have not yet completed any bar.
pub fn last_completed_bar_tid(&self) -> Option<i64> {
self.last_completed_bar_tid
}
/// Process AggTrade records into open deviation bars including incomplete bars for analysis
///
/// # Arguments
///
/// * `agg_trade_records` - Slice of AggTrade records sorted by (timestamp, agg_trade_id)
///
/// # Returns
///
/// Vector of open deviation bars including incomplete bars at end of data
///
/// # Warning
///
/// This method is for analysis purposes only. Incomplete bars violate the
/// fundamental open deviation bar algorithm and should not be used for production trading.
pub fn process_agg_trade_records_with_incomplete(
&mut self,
agg_trade_records: &[AggTrade],
) -> Result<Vec<OpenDeviationBar>, ProcessingError> {
self.process_agg_trade_records_with_options(agg_trade_records, true)
}
/// Process Binance aggregated trade records into open deviation bars
///
/// This is the primary method for converting AggTrade records (which aggregate
/// multiple individual trades) into open deviation bars based on price movement thresholds.
///
/// # Parameters
///
/// * `agg_trade_records` - Slice of AggTrade records sorted by (timestamp, agg_trade_id)
/// Each record represents multiple individual trades aggregated at same price
///
/// # Returns
///
/// Vector of completed open deviation bars (ONLY bars that breached thresholds).
/// Each bar tracks both individual trade count and AggTrade record count.
pub fn process_agg_trade_records(
&mut self,
agg_trade_records: &[AggTrade],
) -> Result<Vec<OpenDeviationBar>, ProcessingError> {
self.process_agg_trade_records_with_options(agg_trade_records, false)
}
/// Process AggTrade records with options for including incomplete bars
///
/// Batch processing mode: Clears any existing state before processing.
/// Use process_single_trade() for stateful streaming instead.
///
/// # Parameters
///
/// * `agg_trade_records` - Slice of AggTrade records sorted by (timestamp, agg_trade_id)
/// * `include_incomplete` - Whether to include incomplete bars at end of processing
///
/// # Returns
///
/// Vector of open deviation bars (completed + incomplete if requested)
pub fn process_agg_trade_records_with_options(
&mut self,
agg_trade_records: &[AggTrade],
include_incomplete: bool,
) -> Result<Vec<OpenDeviationBar>, ProcessingError> {
if agg_trade_records.is_empty() {
return Ok(Vec::new());
}
// Validate records are sorted
self.validate_trade_ordering(agg_trade_records)?;
// Use existing bar state if resuming from checkpoint, otherwise start fresh
// This is CRITICAL for cross-file continuation (Issues #2, #3)
let mut current_bar: Option<OpenDeviationBarState> = if self.resumed_from_checkpoint {
// Continue from checkpoint's incomplete bar
self.resumed_from_checkpoint = false; // Consume the flag
let restored_bar = self.current_bar_state.take();
// Issue #112: Gap-aware checkpoint recovery
// If the forming bar's close_time is too far from the first incoming trade,
// discard it as an orphan to prevent oversized bars from data gaps.
if let Some(ref bar_state) = restored_bar {
let first_trade_ts = agg_trade_records[0].timestamp;
let gap = first_trade_ts - bar_state.bar.close_time;
if gap > self.max_gap_us {
self.anomaly_summary.record_gap();
// Discard forming bar — same treatment as ouroboros reset
None
} else {
restored_bar
}
} else {
restored_bar
}
} else {
// Start fresh for normal batch processing
self.current_bar_state = None;
None
};
let mut bars = Vec::with_capacity(agg_trade_records.len() / 50); // Heuristic: 50 trades/bar covers consolidation regimes
let mut defer_open = false;
for agg_record in agg_trade_records {
// Phase 51: Substitute price with mid for Portcullis/Mid; preserve original
// for breach detection (bid/ask) and SpreadAccumulator (raw quotes).
let effective_record = self.effective_trade(agg_record);
// Track price and position for checkpoint
self.price_window.push(effective_record.price);
self.last_trade_id = Some(effective_record.ref_id);
self.last_timestamp_us = effective_record.timestamp;
// Issue #59: Push trade to history buffer for inter-bar feature computation
if let Some(ref mut history) = self.trade_history {
history.push(&effective_record);
}
if defer_open {
// Previous bar closed, this agg_record opens new bar
// Issue #68: Notify history that new bar is opening (preserves pre-bar trades)
if let Some(ref mut history) = self.trade_history {
history.on_bar_open(effective_record.timestamp);
}
current_bar = Some(if self.include_intra_bar_features {
OpenDeviationBarState::new_with_trade_accumulation(
&effective_record,
self.threshold_ratio,
&self.breach_mode,
self.compute_spread_advanced,
)
} else {
OpenDeviationBarState::new(
&effective_record,
self.threshold_ratio,
&self.breach_mode,
self.compute_spread_advanced,
)
});
defer_open = false;
continue;
}
match current_bar {
None => {
// First bar initialization
// Issue #68: Notify history that new bar is opening (preserves pre-bar trades)
if let Some(ref mut history) = self.trade_history {
history.on_bar_open(effective_record.timestamp);
}
current_bar = Some(if self.include_intra_bar_features {
OpenDeviationBarState::new_with_trade_accumulation(
&effective_record,
self.threshold_ratio,
&self.breach_mode,
self.compute_spread_advanced,
)
} else {
OpenDeviationBarState::new(
&effective_record,
self.threshold_ratio,
&self.breach_mode,
self.compute_spread_advanced,
)
});
}
Some(ref mut bar_state) => {
// Issue #59 & #96 Task #44: Accumulate trade for intra-bar features (before breach check)
// Pass ORIGINAL agg_record so SpreadAccumulator sees raw bid/ask quotes.
bar_state.accumulate_trade(agg_record, self.include_intra_bar_features);
// Phase 51: Breach decision uses bid/ask asymmetry for Portcullis;
// pass ORIGINAL agg_record (not effective) so bid/ask are visible.
let price_breaches = Self::check_breach_mode(
self.breach_mode,
agg_record,
bar_state.upper_threshold,
bar_state.lower_threshold,
);
// Timestamp gate (Issue #36): prevent bars from closing on same timestamp
// This eliminates "instant bars" during flash crashes where multiple trades
// occur at the same millisecond.
let timestamp_allows_close = !self.prevent_same_timestamp_close
|| effective_record.timestamp != bar_state.bar.open_time;
if price_breaches && timestamp_allows_close {
// Breach detected AND timestamp changed - update bar with breaching record
// #356: gate gap detection on breach mode
bar_state.bar.update_with_trade(
&effective_record,
self.breach_mode.has_sequential_ref_ids(),
);
// Validation: Ensure high/low include open/close extremes
debug_assert!(
bar_state.bar.high >= bar_state.bar.open.max(bar_state.bar.close)
);
debug_assert!(
bar_state.bar.low <= bar_state.bar.open.min(bar_state.bar.close)
);
// Compute microstructure features at bar finalization (Issue #34)
bar_state.bar.compute_microstructure_features();
// Issue #59: Compute inter-bar features from lookback window
if let Some(ref mut history) = self.trade_history {
let inter_bar_features =
history.compute_features(bar_state.bar.open_time);
bar_state.bar.set_inter_bar_features(&inter_bar_features);
// Issue #68: Notify history that bar is closing (resumes normal pruning)
history.on_bar_close();
}
// Issue #59: Compute intra-bar features from accumulated trades
if self.include_intra_bar_features {
// Issue #96 Task #173: Use reusable scratch buffers from bar_state
let mut intra_bar_features =
crate::intrabar::compute_intra_bar_features_with_config(
&bar_state.accumulated_trades,
&mut bar_state.scratch_prices,
&mut bar_state.scratch_volumes,
&self.intra_bar_config, // Issue #128
);
// #363 follow-up: streaming-correct drawdown/runup override.
if let Some((dd, ru)) = bar_state.intra_stream.finalize() {
intra_bar_features.intra_max_drawdown =
Some(crate::intrabar::normalize::normalize_drawdown(dd));
intra_bar_features.intra_max_runup =
Some(crate::intrabar::normalize::normalize_runup(ru));
}
bar_state.bar.set_intra_bar_features(&intra_bar_features);
}
// Phase 53: Finalize spread features from SpreadAccumulator
if let Some(ref acc) = bar_state.spread_accumulator {
let spread_features = acc.finalize();
bar_state.bar.set_spread_features(&spread_features);
}
// Move bar out instead of cloning — bar_state borrow ends
// after last use above (NLL), so take() is safe here.
bars.push(current_bar.take().unwrap().bar);
// v1.4: Track last completed bar's trade ID for dedup floor
self.last_completed_bar_tid = Some(bars.last().unwrap().last_agg_trade_id);
defer_open = true; // Next record will open new bar
} else {
// Either no breach OR same timestamp (gate active) - normal update
// #356: gate gap detection on breach mode
bar_state.bar.update_with_trade(
&effective_record,
self.breach_mode.has_sequential_ref_ids(),
);
}
}
}
}
// Save current bar state for checkpoint and optionally append incomplete bar.
// When include_incomplete=true, clone for checkpoint then consume for output.
// When include_incomplete=false, move directly (no clone needed).
if include_incomplete {
// Issue #96 Task #95: Optimize checkpoint cloning with take() to avoid Vec allocation
// (accumulated_trades not needed after intra-bar features computed).
// Using std::mem::take() instead of clone+clear reduces allocation overhead.
if let Some(ref state) = current_bar {
// Construct checkpoint state without cloning accumulated_trades/scratch buffers
// (they're not needed for checkpoint restoration). Avoids cloning ~3.5KB inline SmallVec.
self.current_bar_state = Some(OpenDeviationBarState {
bar: state.bar.clone(),
upper_threshold: state.upper_threshold,
lower_threshold: state.lower_threshold,
accumulated_trades: SmallVec::new(),
scratch_prices: SmallVec::new(),
scratch_volumes: SmallVec::new(),
spread_accumulator: state.spread_accumulator.clone(), // Phase 53
// Streaming accumulator state is intentionally NOT carried over —
// checkpointing already drops accumulated_trades; intra-bar features
// are recomputed fresh on the post-checkpoint bar.
intra_stream: crate::intrabar::IntraStreamAccumulator::new(),
});
}
// Add final partial bar only if explicitly requested
// This preserves algorithm integrity: bars should only close on threshold breach
if let Some(mut bar_state) = current_bar {
// Compute microstructure features for incomplete bar (Issue #34)
bar_state.bar.compute_microstructure_features();
// Issue #59: Compute inter-bar features from lookback window
if let Some(ref history) = self.trade_history {
let inter_bar_features = history.compute_features(bar_state.bar.open_time);
bar_state.bar.set_inter_bar_features(&inter_bar_features);
}
// Issue #59: Compute intra-bar features from accumulated trades
if self.include_intra_bar_features {
// Issue #96 Task #173: Use reusable scratch buffers from bar_state
let mut intra_bar_features =
crate::intrabar::compute_intra_bar_features_with_config(
&bar_state.accumulated_trades,
&mut bar_state.scratch_prices,
&mut bar_state.scratch_volumes,
&self.intra_bar_config, // Issue #128
);
// #363 follow-up: streaming-correct drawdown/runup override.
if let Some((dd, ru)) = bar_state.intra_stream.finalize() {
intra_bar_features.intra_max_drawdown =
Some(crate::intrabar::normalize::normalize_drawdown(dd));
intra_bar_features.intra_max_runup =
Some(crate::intrabar::normalize::normalize_runup(ru));
}
bar_state.bar.set_intra_bar_features(&intra_bar_features);
}
// Phase 53: Finalize spread features for incomplete bar
if let Some(ref acc) = bar_state.spread_accumulator {
let spread_features = acc.finalize();
bar_state.bar.set_spread_features(&spread_features);
}
bars.push(bar_state.bar);
}
} else {
// No incomplete bar appended — move ownership directly, no clone needed
self.current_bar_state = current_bar;
}
Ok(bars)
}
// === CHECKPOINT METHODS ===
/// Create checkpoint for cross-file continuation
///
/// Captures current processing state for seamless continuation:
/// - Incomplete bar (if any) with FIXED thresholds
/// - Position tracking (timestamp, trade_id if available)
/// - Price hash for verification
///
/// # Arguments
///
/// * `symbol` - Symbol being processed (e.g., "BTCUSDT")
///
/// # Example
///
/// ```ignore
/// let bars = processor.process_agg_trade_records(&trades)?;
/// let checkpoint = processor.create_checkpoint("BTCUSDT");
/// let json = serde_json::to_string(&checkpoint)?;
/// std::fs::write("checkpoint.json", json)?;
/// ```
pub fn create_checkpoint(&self, symbol: &str) -> Checkpoint {
let (incomplete_bar, thresholds) = match &self.current_bar_state {
Some(state) => (
Some(state.bar.clone()),
Some((state.upper_threshold, state.lower_threshold)),
),
None => (None, None),
};
let mut checkpoint = Checkpoint::new(
symbol.to_string(),
self.threshold_decimal_bps,
incomplete_bar,
thresholds,
self.last_timestamp_us,
self.last_trade_id,
self.price_window.compute_hash(),
self.prevent_same_timestamp_close,
);
// Issue #46: Persist defer_open state for cross-session continuity
checkpoint.defer_open = self.defer_open;
// v1.4: Persist last_completed_bar_tid for dedup floor initialization
checkpoint.last_completed_bar_tid = self.last_completed_bar_tid;
// Phase 53: Persist SpreadAccumulator state for cross-session continuity
checkpoint.spread_accumulator = self
.current_bar_state
.as_ref()
.and_then(|state| state.spread_accumulator.clone());
// Phase 53: Persist breach_mode for cross-session continuity
checkpoint.breach_mode = self.breach_mode;
checkpoint
}
/// Resume processing from checkpoint
///
/// Restores incomplete bar state with IMMUTABLE thresholds.
/// Next trade continues building the bar until threshold breach.
///
/// # Errors
///
/// - `CheckpointError::MissingThresholds` - Checkpoint has bar but no thresholds
///
/// # Example
///
/// ```ignore
/// let json = std::fs::read_to_string("checkpoint.json")?;
/// let checkpoint: Checkpoint = serde_json::from_str(&json)?;
/// let mut processor = OpenDeviationBarProcessor::from_checkpoint(checkpoint)?;
/// let bars = processor.process_agg_trade_records(&next_file_trades)?;
/// ```
pub fn from_checkpoint(checkpoint: Checkpoint) -> Result<Self, CheckpointError> {
// Issue #85 Phase 2: Apply checkpoint schema migration if needed
let checkpoint = Self::migrate_checkpoint(checkpoint);
// Issue #62: Validate threshold range before restoring from checkpoint
// Valid range: 1-100,000 dbps (0.0001% to 10%)
const THRESHOLD_MIN: u32 = 1;
const THRESHOLD_MAX: u32 = 100_000;
if checkpoint.threshold_decimal_bps < THRESHOLD_MIN
|| checkpoint.threshold_decimal_bps > THRESHOLD_MAX
{
return Err(CheckpointError::InvalidThreshold {
threshold: checkpoint.threshold_decimal_bps,
min_threshold: THRESHOLD_MIN,
max_threshold: THRESHOLD_MAX,
});
}
// Validate checkpoint consistency
if checkpoint.incomplete_bar.is_some() && checkpoint.thresholds.is_none() {
return Err(CheckpointError::MissingThresholds);
}
// Restore bar state if there's an incomplete bar
// Note: accumulated_trades is reset to empty - intra-bar features won't be
// accurate for bars resumed from checkpoint (partial trade history lost)
// Phase 53: Extract spread_accumulator before moving checkpoint fields
let spread_accumulator = checkpoint.spread_accumulator.clone();
let current_bar_state = match (checkpoint.incomplete_bar, checkpoint.thresholds) {
(Some(bar), Some((upper, lower))) => Some(OpenDeviationBarState {
bar,
upper_threshold: upper,
lower_threshold: lower,
accumulated_trades: SmallVec::new(), // Lost on checkpoint - features may be partial
scratch_prices: SmallVec::new(),
scratch_volumes: SmallVec::new(),
spread_accumulator, // Phase 53: Restore from checkpoint
// Same partial-history caveat as accumulated_trades — intra-bar features
// recompute fresh from post-checkpoint trades only.
intra_stream: crate::intrabar::IntraStreamAccumulator::new(),
}),
_ => None,
};
// Issue #96 Task #98: Pre-compute threshold ratio (same as with_options)
let threshold_ratio = ((checkpoint.threshold_decimal_bps as i64)
* crate::fixed_point::SCALE)
/ (crate::fixed_point::BASIS_POINTS_SCALE as i64);
Ok(Self {
threshold_decimal_bps: checkpoint.threshold_decimal_bps,
threshold_ratio,
current_bar_state,
price_window: PriceWindow::new(), // Reset - will be rebuilt from new trades
last_trade_id: checkpoint.last_trade_id,
last_timestamp_us: checkpoint.last_timestamp_us,
anomaly_summary: checkpoint.anomaly_summary,
resumed_from_checkpoint: true, // Signal to continue from existing bar state
prevent_same_timestamp_close: checkpoint.prevent_same_timestamp_close,
defer_open: checkpoint.defer_open, // Issue #46: Restore deferred open state
last_completed_bar_tid: checkpoint.last_completed_bar_tid, // v1.4: Restore dedup floor
trade_history: None, // Issue #59: Must be re-enabled after restore
inter_bar_config: None, // Issue #59: Must be re-enabled after restore
include_intra_bar_features: false, // Issue #59: Must be re-enabled after restore
intra_bar_config: crate::intrabar::IntraBarConfig::default(), // Issue #128
max_gap_us: 3_600_000_000, // Issue #112: 1 hour default
breach_mode: checkpoint.breach_mode, // Phase 53: Restore breach mode
// Phase 54: Restore compute_spread_advanced from SpreadAccumulator state
compute_spread_advanced: checkpoint
.spread_accumulator
.as_ref()
.is_some_and(crate::spread_accumulator::SpreadAccumulator::compute_advanced),
})
}
/// Migrate checkpoint between schema versions
/// Issue #85 Phase 2: Handle v1 → v2 migration
/// Safe: JSON deserialization is field-name-based, so old v1 checkpoints load correctly
fn migrate_checkpoint(mut checkpoint: Checkpoint) -> Checkpoint {
match checkpoint.version {
1 => {
// v1 → v2: OpenDeviationBar struct field reordering (no behavioral changes)
// JSON serialization is position-independent, so no transformation needed
checkpoint.version = 2;
checkpoint
}
2 => {
// Already current version
checkpoint
}
_ => {
// Unknown version - log warning and continue with best effort
eprintln!(
"Warning: Checkpoint has unknown version {}, treating as v2",
checkpoint.version
);
checkpoint.version = 2;
checkpoint
}
}
}
/// Verify we're at the right position in the data stream
///
/// Call with first trade of new file to verify continuity.
/// Returns verification result indicating if there's a gap or exact match.
///
/// # Arguments
///
/// * `first_trade` - First trade of the new file/chunk
///
/// # Example
///
/// ```ignore
/// let processor = OpenDeviationBarProcessor::from_checkpoint(checkpoint)?;
/// let verification = processor.verify_position(&next_file_trades[0]);
/// match verification {
/// PositionVerification::Exact => println!("Perfect continuation!"),
/// PositionVerification::Gap { missing_count, .. } => {
/// println!("Warning: {} trades missing", missing_count);
/// }
/// PositionVerification::TimestampOnly { gap_ms } => {
/// println!("Timestamp-only data: {}ms gap", gap_ms);
/// }
/// }
/// ```
pub fn verify_position(&self, first_trade: &AggTrade) -> PositionVerification {
match self.last_trade_id {
Some(last_id) => {
// Binance: has trade IDs - check for gaps
let expected_id = last_id + 1;
if first_trade.ref_id == expected_id {
PositionVerification::Exact
} else {
let missing_count = first_trade.ref_id - expected_id;
PositionVerification::Gap {
expected_id,
actual_id: first_trade.ref_id,
missing_count,
}
}
}
None => {
// No trade IDs available - use timestamp only
let gap_us = first_trade.timestamp - self.last_timestamp_us;
let gap_ms = gap_us / 1000;
PositionVerification::TimestampOnly { gap_ms }
}
}
}
/// Get the current anomaly summary
pub fn anomaly_summary(&self) -> &AnomalySummary {
&self.anomaly_summary
}
/// Get the threshold in decimal basis points
pub fn threshold_decimal_bps(&self) -> u32 {
self.threshold_decimal_bps
}
/// Validate that trades are properly sorted for deterministic processing
///
/// Issue #96 Task #62: Early-exit optimization for sorted data
/// For typical workloads (95%+ sorted), quick first/last check identifies
/// unsorted batches immediately without full O(n) validation.
fn validate_trade_ordering(&self, trades: &[AggTrade]) -> Result<(), ProcessingError> {
if trades.is_empty() {
return Ok(());
}
// Issue #96 Task #62: Fast-path check for obviously unsorted data
// If first and last trades are not ordered, data is definitely unsorted
// This early-exit catches common failures without full validation
let first = &trades[0];
let last = &trades[trades.len() - 1];
if last.timestamp < first.timestamp
|| (last.timestamp == first.timestamp && last.ref_id <= first.ref_id)
{
// Definitely unsorted - find exact error location (cold path)
return find_unsorted_trade(trades);
}
// Full validation for typical sorted case
for i in 1..trades.len() {
let prev = &trades[i - 1];
let curr = &trades[i];
// Check ordering: (timestamp, agg_trade_id) ascending
if curr.timestamp < prev.timestamp
|| (curr.timestamp == prev.timestamp && curr.ref_id <= prev.ref_id)
{
return unsorted_trade_error(i, prev, curr);
}
}
Ok(())
}
/// Reset processor state at a UTC-midnight ouroboros boundary (day mode only).
///
/// Clears the incomplete bar and position tracking while preserving
/// the threshold configuration. Use this when starting fresh at a
/// known boundary for reproducibility.
///
/// # Returns
///
/// The orphaned incomplete bar (if any) so caller can decide
/// whether to include it in results with `is_orphan=True` flag.
///
/// # Example
///
/// ```ignore
/// // At year boundary (Jan 1 00:00:00 UTC)
/// let orphaned = processor.reset_at_ouroboros();
/// if let Some(bar) = orphaned {
/// // Handle incomplete bar from previous year
/// }
/// // Continue processing new year's data with clean state
/// ```
pub fn reset_at_ouroboros(&mut self) -> Option<OpenDeviationBar> {
let orphaned = self.current_bar_state.take().map(|mut state| {
// Issue #275: Compute microstructure features for orphan bars.
// Without this, duration_us (and derived trade_intensity) remain at
// their default of 0, even though close_time − open_time > 0.
state.bar.compute_microstructure_features();
state.bar
});
// v1.4: Track orphan bar's trade ID for dedup floor (orphan IS a completed bar)
// Do NOT reset last_completed_bar_tid to None — it persists across day boundaries
if let Some(ref bar) = orphaned {
self.last_completed_bar_tid = Some(bar.last_agg_trade_id);
}
self.price_window = PriceWindow::new();
self.last_trade_id = None;
self.last_timestamp_us = 0;
self.resumed_from_checkpoint = false;
self.defer_open = false;
// Issue #81: Clear bar boundary tracking at ouroboros reset.
// Trades are preserved — still valid lookback for first bar of new segment.
if let Some(ref mut history) = self.trade_history {
history.reset_bar_boundaries();
}
orphaned
}
}
/// Internal state for a open deviation bar being built
#[derive(Clone)]
struct OpenDeviationBarState {
/// The open deviation bar being constructed
pub bar: OpenDeviationBar,
/// Upper breach threshold (FIXED from bar open)
pub upper_threshold: FixedPoint,
/// Lower breach threshold (FIXED from bar open)
pub lower_threshold: FixedPoint,
/// Accumulated trades for intra-bar feature computation (Issue #59)
///
/// When intra-bar features are enabled, trades are accumulated here
/// during bar construction and used to compute features at bar close.
/// Cleared when bar closes to free memory.
/// Issue #136: Optimized from 512→64→48 slots.
/// Profile data: max trades/bar = 26 (P99 = 14), so 64 slots provides
/// 2.46x safety margin. SmallVec transparently spills to heap if exceeded.
pub accumulated_trades: SmallVec<[AggTrade; 64]>,
/// Issue #96: Scratch buffer for intra-bar price extraction
/// SmallVec<[f64; 64]> keeps 95%+ of bars on stack (P99 trades/bar = 14, max = 26)
/// Eliminates heap allocation for typical bars, spills transparently for large ones
pub scratch_prices: SmallVec<[f64; 64]>,
/// Issue #96: Scratch buffer for intra-bar volume extraction
/// Same sizing rationale as scratch_prices
pub scratch_volumes: SmallVec<[f64; 64]>,
/// Phase 53: SpreadAccumulator for bid/ask spread features
/// Some when breach mode uses bid/ask data (Portcullis, Mid, Directional).
/// None for crypto Last breach mode (zero overhead).
pub spread_accumulator: Option<SpreadAccumulator>,
/// #363 follow-up: streaming O(1)-memory accumulator for
/// `intra_max_drawdown` / `intra_max_runup`. Runs unconditionally on every
/// trade so these two fields stay bit-exact even when the
/// `MAX_ACCUMULATED_TRADES` cap truncates the buffer fed to bull/bear ITH.
/// See `intrabar/streaming.rs` for the bit-exactness contract.
pub intra_stream: crate::intrabar::IntraStreamAccumulator,
}
impl OpenDeviationBarState {
/// Create new open deviation bar state from opening trade
/// Issue #96 Task #98: Accept pre-computed threshold_ratio for fast threshold calculation
/// Phase 53: breach_mode gates SpreadAccumulator initialization
/// Phase 54: compute_spread_advanced passed to SpreadAccumulator::new()
#[inline]
fn new(
trade: &AggTrade,
threshold_ratio: i64,
breach_mode: &BreachMode,
compute_spread_advanced: bool,
) -> Self {
let bar = OpenDeviationBar::new(trade);
// Issue #96 Task #98: Use cached ratio instead of repeated division
// This avoids BASIS_POINTS_SCALE division on every bar creation
let (upper_threshold, lower_threshold) =
bar.open.compute_range_thresholds_cached(threshold_ratio);
Self {
bar,
upper_threshold,
lower_threshold,
accumulated_trades: SmallVec::new(),
scratch_prices: SmallVec::new(),
scratch_volumes: SmallVec::new(),
spread_accumulator: match breach_mode {
BreachMode::Portcullis | BreachMode::Mid | BreachMode::Directional => {
Some(SpreadAccumulator::new(compute_spread_advanced))
}
BreachMode::Last => None, // Phase 53: Zero overhead for crypto
},
// No-intra path: accumulator stays default (never queried).
intra_stream: crate::intrabar::IntraStreamAccumulator::new(),
}
}
/// Create new open deviation bar state with intra-bar feature accumulation
/// Issue #96 Task #98: Accept pre-computed threshold_ratio for fast threshold calculation
/// Phase 53: breach_mode gates SpreadAccumulator initialization
/// Phase 54: compute_spread_advanced passed to SpreadAccumulator::new()
#[inline]
fn new_with_trade_accumulation(
trade: &AggTrade,
threshold_ratio: i64,
breach_mode: &BreachMode,
compute_spread_advanced: bool,
) -> Self {
let bar = OpenDeviationBar::new(trade);
// Issue #96 Task #98: Use cached ratio instead of repeated division
// This avoids BASIS_POINTS_SCALE division on every bar creation
let (upper_threshold, lower_threshold) =
bar.open.compute_range_thresholds_cached(threshold_ratio);
let mut intra_stream = crate::intrabar::IntraStreamAccumulator::new();
// Feed the opening trade so the streaming accumulator's first nav matches
// accumulated_trades[0] exactly — both go through the same downstream
// normalization (`price * (1.0 / price[0])`).
intra_stream.update(trade.price.to_f64());
Self {
bar,
upper_threshold,
lower_threshold,
accumulated_trades: {
let mut sv = SmallVec::new();
sv.push(*trade);
sv
},
scratch_prices: SmallVec::new(),
scratch_volumes: SmallVec::new(),
spread_accumulator: match breach_mode {
BreachMode::Portcullis | BreachMode::Mid | BreachMode::Directional => {
Some(SpreadAccumulator::new(compute_spread_advanced))
}
BreachMode::Last => None, // Phase 53: Zero overhead for crypto
},
intra_stream,
}
}
/// Accumulate a trade for intra-bar feature computation
///
/// Issue #96 Task #44: Only accumulates if intra-bar features are enabled,
/// avoiding unnecessary clones for the majority of use cases where they're disabled.
/// Issue #96 Task #79: #[inline] allows compiler to fold invariant branch
/// (include_intra is constant for processor lifetime)
///
/// #363 follow-up (cap removed): the original 100_000-trade cap silently
/// truncated the buffer fed to bull/bear ITH and to every per-bar statistic
/// that reads `n = trades.len()` — corrupting `intra_trade_count`,
/// `intra_intensity`, ITH epoch density / excess gain / CV, drawdown / runup,
/// volume skew/kurt, etc. on any bar exceeding 100K agg trades (BTCUSDT@250
/// hit this regularly). Per-bar memory is naturally bounded by bar duration
/// vs. trade arrival rate; the original "8 GB RSS spike" was cross-process
/// accumulation during parallel `fill_from_rest`, which a per-bar cap could
/// not have prevented. Drawdown / runup are now also covered by the O(1)
/// `intra_stream` accumulator (kept as defense-in-depth + structural example).
#[inline]
fn accumulate_trade(&mut self, trade: &AggTrade, include_intra: bool) {
if include_intra {
// O(1)-memory streaming drawdown / runup (always correct, regardless
// of buffer length) — see intrabar/streaming.rs for the bit-exactness
// contract against bull_ith / bear_ith.
self.intra_stream.update(trade.price.to_f64());
self.accumulated_trades.push(*trade);
}
// Phase 53: Feed bid/ask spread data to SpreadAccumulator
// Only active for Portcullis/Mid/Directional (spread_accumulator is Some)
if let Some(ref mut acc) = self.spread_accumulator {
if let (Some(bid), Some(ask)) = (trade.best_bid, trade.best_ask) {
acc.update(bid.to_f64(), ask.to_f64(), trade.timestamp);
}
}
}
}