of_analytics 0.1.0

Advanced market microstructure analytics for Orderflow
Documentation
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
# `of_analytics`

[![Crates.io](https://img.shields.io/crates/v/of_analytics.svg)](https://crates.io/crates/of_analytics)
[![Docs.rs](https://docs.rs/of_analytics/badge.svg)](https://docs.rs/of_analytics)
[![License: MIT](https://img.shields.io/badge/license-MIT-blue.svg)](../../LICENSE)

`of_analytics` contains additive advanced market microstructure analytics for
Orderflow. The crate exists so heavier analytics can evolve outside `of_core`
without breaking existing `AnalyticsAccumulator`, runtime, C ABI, Python, or
Java APIs.

`of_analytics` starts at `0.1.0` in the broader Orderflow `0.5.0` development
line because it is a new public Rust surface.

The first foundation is dependency-light:

- market-quality/TCA primitives for quoted spread, effective spread, realized
  spread, price improvement, quote freshness, and side-aware slippage,
- execution-quality/TCA primitives for implementation shortfall, arrival and
  decision slippage, adverse selection, trade-through, and fill-quality score,
- liquidity/depth primitives for top-of-book depth, multi-level depth,
  proportional imbalance, order-flow imbalance, depth slope, depth convexity,
  book pressure, replenishment/depletion rates, drought detection, and
  sweepability,
- market-impact primitives for Kyle-style lambda, Amihud-style illiquidity,
  calibrated expected impact, square-root impact, temporary/permanent impact,
  impact decay, and child-order attribution,
- VPIN-style fixed-bucket toxicity primitives plus post-trade markout,
  adverse-selection, quote-fade, toxic-burst, and informed-flow proxy signals,
- fixed-window volatility/noise primitives with bipower variation, jump
  variation, OHLC range estimators, signature-plot points, and intraday
  seasonality buckets,
- threshold-based market regime classification plus composite trend/range/chop,
  liquidity, spread, session, hidden-liquidity, and transition-confidence
  labels,
- feed-quality primitives for sequence gaps, out-of-order events, duplicates,
  stale events, locked/crossed books, timestamp skew, resets, health scoring,
  replay usability, primary issue selection, and operator review reports,
- feature-vector primitives for stable feature ids, ordered schemas, schema
  hashes, missing-value policy, quality labels, and reusable fixed-capacity
  writers,
- resiliency primitives for threshold-based spread/depth shock detection,
  recovery timing, and liquidity resiliency scoring,
- queue/fill primitives for passive queue position estimates, fill
  probability, expected time-to-fill, amend queue loss, top-level survival,
  cancel/replace cost, and maker/taker decision scoring,
- pattern-risk primitives for spoofing/layering, quote-stuffing, stop-run,
  absorption, momentum-ignition, iceberg, hidden accumulation/distribution,
  stacked-imbalance, and failed-breakout risk indicators,
- venue/route primitives for fill, reject, cancel, latency, route-health,
  venue-liquidity, toxicity, fill-quality, reliability, route-quality, drift,
  and degradation diagnostics,
- cross-asset primitives for rolling correlation, beta, pair divergence,
  thresholded basis pressure, latency-adjusted correlation, cross-venue
  divergence, ETF/component imbalance, and relationship-degradation
  diagnostics,
- derivatives primitives for put/call pressure, volume/open-interest anomaly,
  implied-volatility flow, gamma exposure, IV skew, term structure,
  implied-versus-realized richness, gamma pressure, futures basis, roll
  pressure, funding divergence, and aggregate derivatives stress,
- explicit feature profiles so users can opt into future impact, toxicity,
  volatility, regime, data-quality, feature-vector, resiliency, queue-fill,
  cross-asset, pattern, derivatives, institutional, and ML feature modules
  without forcing all downstream users to compile them.

The crate does not submit orders, manage runtime state, own persistence, or
replace existing `of_core` APIs. It consumes normalized market data and returns
typed snapshots that hosts can wire into runtime, research, or execution
systems.

## Feature Profiles

Default features:

- `market-quality`
- `liquidity`

Reserved additive profiles:

- `impact`
- `toxicity`
- `volatility`
- `regime`
- `data-quality`
- `feature-vector`
- `resiliency`
- `queue-fill`
- `cross-asset`
- `patterns`
- `derivatives`
- `institutional`
- `ml-features`
- `all`

## Public API Meaning

The analytics types are typed calculators and snapshots, not hidden strategy
decisions. Context types such as quote, trade, depth, route, derivative, and
feature inputs carry normalized observations and timestamps. Tracker or
calculator types accumulate a bounded window; snapshot types expose the result
without mutating the input observation. Constructors validate units, capacities,
thresholds, and required metadata before a tracker is used.

The market-quality and execution-quality surfaces explain spread, slippage,
impact, adverse selection, and fill outcomes. Liquidity, queue, resiliency,
toxicity, pattern-risk, volatility, regime, cross-asset, and derivatives
surfaces answer distinct analytical questions rather than producing one
universal signal. Feature vectors and model metadata define stable input
ordering and quality/missing-value semantics for downstream models.

All profiles are additive feature boundaries. A feature flag controls compile
cost and dependency inclusion; it does not silently change the meaning of
existing `of_core` snapshots. These calculations do not place orders, own
persistence, or override `DataQualityFlags`; hosts remain responsible for
quality gating, replay validation, and execution risk.

## Market Quality Example

```rust
use of_analytics::{MarketQualityTracker, QuoteContext, TradeContext};
use of_core::Side;

let mut tracker = MarketQualityTracker::new(1_000_000);
tracker.on_quote(QuoteContext::new(499_975, 500_025, 100, 120, 1_000)?);
let snapshot = tracker.evaluate_trade(
    TradeContext::new(500_050, 10, Side::Ask, 1_500)?,
    Some(500_075),
)?;

assert_eq!(snapshot.quoted_spread(), 50);
assert!(snapshot.effective_spread_bps() > 0);
# Ok::<(), Box<dyn std::error::Error>>(())
```

## Execution Quality Example

```rust
use of_analytics::{ExecutionBenchmark, ExecutionQualityAnalyzer, TradeContext};
use of_core::Side;

let trade = TradeContext::new(101_000, 10, Side::Ask, 1)?;
let benchmark = ExecutionBenchmark::new(
    100_000,
    100_500,
    99_950,
    100_050,
    Some(100_750),
)?;
let snapshot = ExecutionQualityAnalyzer::evaluate(trade, benchmark);

assert!(snapshot.implementation_shortfall_bps() > 0);
assert!(snapshot.trade_through());
# Ok::<(), Box<dyn std::error::Error>>(())
```

## Liquidity Example

```rust
use of_analytics::{
    LiquidityDepthAnalyzer, LiquidityFlowConfig, LiquidityFlowEvent,
    LiquidityFlowTracker,
};
use of_core::BookLevel;
use of_core::Side;

let bids = [
    BookLevel { level: 0, price: 499_975, size: 100 },
    BookLevel { level: 1, price: 499_950, size: 80 },
    BookLevel { level: 2, price: 499_925, size: 70 },
];
let asks = [
    BookLevel { level: 0, price: 500_025, size: 120 },
    BookLevel { level: 1, price: 500_050, size: 90 },
    BookLevel { level: 2, price: 500_075, size: 60 },
];
let snapshot = LiquidityDepthAnalyzer::new(3).analyze(&bids, &asks, 150)?;

assert_eq!(snapshot.bid_depth(), 250);
assert_eq!(snapshot.ask_depth(), 270);
assert!(snapshot.sweepable_buy_qty() >= 120);
assert!(snapshot.book_pressure_bps() < 0);

let mut flow = LiquidityFlowTracker::new(LiquidityFlowConfig::default());
flow.on_event(LiquidityFlowEvent::new(Side::Bid, 100, 0, 0, 1)?);
flow.on_event(LiquidityFlowEvent::new(Side::Ask, 0, 250, 25, 500_000_001)?);
assert!(flow.snapshot().order_flow_imbalance_bps() > 0);
# Ok::<(), Box<dyn std::error::Error>>(())
```

## Impact And Toxicity Example

```rust
use of_analytics::{
    ExpectedImpactEstimator, ExpectedImpactInput, ImpactCalibration,
    ImpactSample, ImpactTracker, ToxicityAnalyzer, ToxicityConfig,
    ToxicityInput, TradeContext, VpinTracker,
};
use of_core::Side;

let mut impact = ImpactTracker::new();
impact.on_sample(ImpactSample::new(500_000, 501_000, 100, 50_000_000)?);
assert!(impact.snapshot().kyle_lambda_ppm() > 0);

let calibration = ImpactCalibration::new(
    1_000_000,
    200,
    10_000,
    500,
    250,
    1_000_000_000,
)?;
let estimate = ExpectedImpactEstimator::estimate(ExpectedImpactInput::new(
    Side::Ask,
    1_000,
    10_000,
    100_000,
    1_000_000_000,
    calibration,
)?);
assert!(estimate.expected_total_impact_bps() > 0);

let mut vpin = VpinTracker::<4>::new(100)?;
vpin.on_trade(TradeContext::new(500_000, 80, Side::Ask, 1)?);
vpin.on_trade(TradeContext::new(500_000, 20, Side::Bid, 2)?);
assert_eq!(vpin.snapshot().bucket_count(), 1);

let toxicity = ToxicityAnalyzer::new(ToxicityConfig::default()).evaluate(
    ToxicityInput::new(
        TradeContext::new(100_000, 10, Side::Ask, 1)?,
        100_500,
        1_000,
        1_000,
        1_000,
        500,
        8_000,
        7_000,
    )?,
);
assert!(toxicity.toxic_flow_burst());
# Ok::<(), Box<dyn std::error::Error>>(())
```

## Volatility And Regime Example

```rust
use of_analytics::{
    CompositeRegimeClassifier, CompositeRegimeInput, OhlcVolatilityEstimator,
    OhlcVolatilityInput, RegimeClassifier, RegimeInput, RegimeKind,
    SessionRegimeKind, TrendRegimeKind, VolatilitySeasonalityTracker,
    VolatilitySignatureEstimator, VolatilityTracker,
};

let mut vol = VolatilityTracker::<8>::new()?;
vol.on_price(100_000)?;
vol.on_price(101_000)?;
vol.on_price(100_500)?;
let snapshot = vol.snapshot();
assert!(snapshot.bipower_vol_bps() > 0);

let regime = RegimeClassifier::default().classify(RegimeInput::new(
    5,
    snapshot.realized_vol_bps(),
    0,
    0,
));

assert!(matches!(regime.kind(), RegimeKind::Normal | RegimeKind::Volatile));

let composite = CompositeRegimeClassifier::default().classify(
    CompositeRegimeInput::new(
        8_000,
        1_000,
        1,
        20,
        2_000,
        3_600_000_000_000,
        3_600_000_000_000,
        false,
        0,
        0,
    )?,
);
assert_eq!(composite.trend(), TrendRegimeKind::Trend);
assert_eq!(composite.session(), SessionRegimeKind::Continuous);

let ohlc = OhlcVolatilityEstimator::estimate(OhlcVolatilityInput::new(
    100_000,
    102_000,
    99_000,
    101_000,
    Some(99_500),
)?);
assert!(ohlc.parkinson_vol_bps() > 0);

let signature = VolatilitySignatureEstimator::estimate(1_000_000, &[10, -10, 20, -20])?;
assert_eq!(signature.noise_ratio_bps(), 10_000);

let mut seasonality = VolatilitySeasonalityTracker::<2>::new(25)?;
seasonality.on_return(0, 10)?;
seasonality.on_return(0, -30)?;
assert_eq!(seasonality.snapshot(0)?.jump_count(), 1);
# Ok::<(), Box<dyn std::error::Error>>(())
```

## Data Quality Example

```rust
use of_analytics::{
    FeedQualityConfig, FeedQualityEvent, FeedQualityFlags, FeedQualityTracker,
    ReplayQualityAnalyzer,
};

let config = FeedQualityConfig::new(10, 20, 1)?;
let mut tracker = FeedQualityTracker::new(config);

tracker.on_event(FeedQualityEvent::new(
    Some(10),
    100,
    105,
    Some(99),
    Some(101),
)?);
let flags = tracker.on_event(FeedQualityEvent::new(
    Some(12),
    110,
    140,
    Some(100),
    Some(100),
)?);

assert!(flags.contains(FeedQualityFlags::SEQUENCE_GAP));
assert!(flags.contains(FeedQualityFlags::LOCKED_BOOK));
assert!(tracker.snapshot().health_score_bps() < 10_000);
let report = ReplayQualityAnalyzer::default().evaluate(tracker.snapshot());
assert!(report.operator_review_required());
# Ok::<(), Box<dyn std::error::Error>>(())
```

## Feature Vector Example

```rust
use of_analytics::{
    FeatureDefinition, FeatureId, FeatureQuality, FeatureSchema, FeatureUnit,
    FeatureVectorWriter, MissingValuePolicy,
};

let mut schema = FeatureSchema::<2>::new()?;
let spread = schema.register(FeatureDefinition::new(
    FeatureId::new(1)?,
    "spread_bps",
    FeatureUnit::BasisPoints,
    1,
    MissingValuePolicy::Sentinel(-1),
)?)?;
schema.register(FeatureDefinition::new(
    FeatureId::new(2)?,
    "quality_bps",
    FeatureUnit::ScoreBasisPoints,
    1,
    MissingValuePolicy::Zero,
)?)?;

let mut writer = FeatureVectorWriter::new(&schema);
writer.set(spread, 25, FeatureQuality::Good)?;
let vector = writer.finish();

assert_eq!(vector.values(), &[25, 0]);
assert_eq!(vector.schema_hash(), schema.schema_hash());
# Ok::<(), Box<dyn std::error::Error>>(())
```

## Resiliency Example

```rust
use of_analytics::{ResiliencyConfig, ResiliencySample, ResiliencyTracker};

let config = ResiliencyConfig::new(5, 1_000, 25, 5_000, 8, 9_000)?;
let mut tracker = ResiliencyTracker::new(config);

tracker.on_sample(ResiliencySample::new(100, 5, 500, 500)?);
let shock = tracker.on_sample(ResiliencySample::new(200, 30, 400, 400)?);
let recovered = tracker.on_sample(ResiliencySample::new(1_000_200, 7, 500, 500)?);

assert!(shock.active_shock());
assert_eq!(recovered.recovery_count(), 1);
assert_eq!(recovered.last_recovery_time_ns(), 1_000_000);
# Ok::<(), Box<dyn std::error::Error>>(())
```

## Queue And Fill Example

```rust
use of_analytics::{
    QueueDecisionAnalyzer, QueueDecisionConfig, QueueDecisionInput,
    QueueFillConfig, QueueFillTracker, QueueFillUpdate, QueuePositionEstimate,
    QueueUpdateKind,
};

let config = QueueFillConfig::new(5_000, 100, 1_000_000_000)?;
let estimate = QueuePositionEstimate::new(100, 50, 200, 1)?;
let mut tracker = QueueFillTracker::new(config, estimate);

let snapshot = tracker.on_update(QueueFillUpdate::new(
    QueueUpdateKind::Trade,
    40,
    160,
    2,
)?);

assert_eq!(snapshot.qty_ahead(), 60);
assert!(snapshot.fill_probability_bps() > 0);

let decision = QueueDecisionAnalyzer::new(
    QueueDecisionConfig::new(5_000, 5_000, 10_000_000_000)?,
)
.evaluate(QueueDecisionInput::new(
    snapshot,
    10,
    5,
    1,
    2,
    1,
    1_000,
    0,
    0,
)?);
assert!(decision.maker_taker_decision_score_bps() > 0);
# Ok::<(), Box<dyn std::error::Error>>(())
```

## Pattern Risk Example

```rust
use of_analytics::{
    PatternDetailAnalyzer, PatternDetailInput, PatternRiskClassifier,
    PatternRiskInput, PatternRiskLiquidity,
};

let classifier = PatternRiskClassifier::default();
let snapshot = classifier.classify(PatternRiskInput::new(
    800,
    900,
    10,
    8_000,
    5,
    PatternRiskLiquidity::new(10, 1_000)?,
    1_000_000,
)?);

assert!(snapshot.spoofing_layering_risk_bps() > 0);
assert!(snapshot.quote_stuffing_risk_bps() > 0);

let detail = PatternDetailAnalyzer::default().evaluate(
    PatternDetailInput::new(8, 4, 1_000, 100, 4, 8_000, 500, 2, 30, 35, 1_000)?,
);
assert!(detail.iceberg_risk_bps() > 0);
assert!(detail.failed_breakout_risk_bps() > 0);
# Ok::<(), Box<dyn std::error::Error>>(())
```

## Venue Route Example

```rust
use of_analytics::{
    VenueRouteEvent, VenueRouteEventKind, VenueRouteQualityAnalyzer,
    VenueRouteQualityInput, VenueRouteTracker,
};

let mut tracker = VenueRouteTracker::new();
tracker.on_event(VenueRouteEvent::new(VenueRouteEventKind::Sent, 100, 0, 10)?);
tracker.on_event(VenueRouteEvent::new(VenueRouteEventKind::Fill, 60, 100, 20)?);
let snapshot = tracker.snapshot();
let quality = VenueRouteQualityAnalyzer::default().evaluate(
    VenueRouteQualityInput::new(snapshot, 9_000, 500, 9_500, 9_500)?,
);

assert_eq!(snapshot.sent(), 1);
assert_eq!(snapshot.fills(), 1);
assert_eq!(snapshot.avg_quote_to_fill_latency_ns(), 100);
assert!(!quality.route_degraded());
# Ok::<(), Box<dyn std::error::Error>>(())
```

## Cross-Asset Example

```rust
use of_analytics::{
    CrossAssetConfig, CrossAssetDiagnosticAnalyzer, CrossAssetDiagnosticInput,
    CrossAssetSample, CrossAssetTracker,
};

let mut tracker = CrossAssetTracker::<8>::new(CrossAssetConfig::default())?;
tracker.on_sample(CrossAssetSample::new(100_000, 200_000, 1)?);
tracker.on_sample(CrossAssetSample::new(101_000, 202_000, 2)?);
tracker.on_sample(CrossAssetSample::new(102_000, 204_000, 3)?);
let snapshot = tracker.snapshot();
let diagnostic = CrossAssetDiagnosticAnalyzer::default().evaluate(
    CrossAssetDiagnosticInput::new(snapshot, 1_000_000, 1_100_000, 5, 100)?,
);

assert!(snapshot.correlation_bps() > 0);
assert!(snapshot.lead_lag_score_bps() > 0);
assert!(diagnostic.synchronization_quality_bps() > 0);
# Ok::<(), Box<dyn std::error::Error>>(())
```

## Derivatives Example

```rust
use of_analytics::{
    DerivativesDiagnosticAnalyzer, DerivativesDiagnosticInput,
    DerivativesVolatilitySurface, FuturesBasisAnalyzer, FuturesBasisInput,
    OptionFlowSample, OptionFlowTracker, OptionKind,
};

let mut options = OptionFlowTracker::new();
options.on_sample(OptionFlowSample::new(
    OptionKind::Call,
    100,
    1_000,
    50_000,
    2_000,
    1_000,
)?);
options.on_sample(OptionFlowSample::new(
    OptionKind::Put,
    200,
    1_500,
    150_000,
    3_000,
    -2_000,
)?);
assert!(options.snapshot().put_call_pressure_bps() > 0);

let basis = FuturesBasisAnalyzer::analyze(FuturesBasisInput::new(
    100_000,
    101_000,
    100_500,
    101_000,
    102_000,
    25,
)?);
let diagnostic = DerivativesDiagnosticAnalyzer::default().evaluate(
    DerivativesDiagnosticInput::new(
        options.snapshot(),
        basis,
        DerivativesVolatilitySurface::new(3_000, 3_500, 2_500, 3_000, 3_250, 2_000)?,
    ),
);
assert!(basis.basis_bps() > 0);
assert!(diagnostic.iv_richness_bps() > 0);
# Ok::<(), Box<dyn std::error::Error>>(())
```

## Low-Latency Principles

- No async runtime dependency.
- No heap allocation in hot update/evaluate methods.
- Borrow existing `of_core` book levels instead of copying snapshots.
- Use integer arithmetic for prices, quantities, spreads, and basis points.
- Keep batch/research features separate from live hot-path trackers.