Expand description
§of_core
of_core defines the canonical data model and analytics primitives used across the Orderflow stack.
It is provider-agnostic and intentionally lightweight so every binding (C, Python, Java) can rely on
the same normalized semantics.
§What This Crate Contains
- Market identity:
SymbolId - Event model:
TradePrint,BookUpdate,BookLevel,BookSnapshot,Side,BookAction - Quality flags:
DataQualityFlags - Runtime outputs:
AnalyticsSnapshot,DerivedAnalyticsSnapshot,SessionCandleSnapshot,IntervalCandleSnapshot,SignalSnapshot,SignalState - Deterministic analytics engine:
AnalyticsAccumulator
§New In 0.4.0
0.4.0 keeps the established of_core analytics contracts stable while the
larger Orderflow release adds execution and OMS capabilities around them.
Existing users of AnalyticsAccumulator, AnalyticsSnapshot,
BookSnapshot, candle snapshots, quality flags, and tickbar aggregation do
not need to rename or rewrite code.
What changes for of_core users:
of_coreremains the canonical market-data and analytics schema for the project.- execution types intentionally live in the new
of_execution_corecrate, so order-management concerns do not pollute the market-data accumulator. - strategies can now combine
of_coreanalytics withof_executionsimulated order flow, but the integration is at the application layer. - tickbar APIs remain optional behind the
tickbarfeature and are still additive. DataQualityFlagsremain the bridge between market-data correctness and strategy/execution gating.
Version policy:
- established analytics crates publish as
0.4.0; - new execution crates publish as
0.1.0; - this split is intentional because execution has a newer public trait surface
while
of_corecontinues its existing compatibility line.
§Public API Inventory
Public types:
SymbolIdSideBookActionBookUpdateBookLevelBookSnapshotTradePrintAnalyticsSnapshotDerivedAnalyticsSnapshotSessionCandleSnapshotIntervalCandleSnapshotSignalStateSignalSnapshotDataQualityFlagsCompletedBarAnalyticsAccumulator
Public DataQualityFlags methods:
NONESTALE_FEEDSEQUENCE_GAPCLOCK_SKEWDEPTH_TRUNCATEDOUT_OF_ORDERADAPTER_DEGRADEDDataQualityFlags::bitsDataQualityFlags::from_bits_truncateDataQualityFlags::intersects
Public AnalyticsAccumulator methods:
AnalyticsAccumulator::on_tradeAnalyticsAccumulator::reset_session_deltaAnalyticsAccumulator::reset_sessionAnalyticsAccumulator::snapshotAnalyticsAccumulator::derived_snapshotAnalyticsAccumulator::session_candle_snapshotAnalyticsAccumulator::interval_candle_snapshotAnalyticsAccumulator::with_tickbar(requirestickbarfeature)AnalyticsAccumulator::bar_series(requirestickbarfeature)AnalyticsAccumulator::reset_tickbar(requirestickbarfeature)
§Design Principles
- Deterministic arithmetic: prices and sizes are integer values, avoiding float drift in replay/backtests.
- Stable schema: types are designed for cross-language transport and long-lived storage.
- Minimal dependencies: this crate stays small so it can be embedded broadly.
§Type Semantics Reference
§Market identity and direction
SymbolIdis the canonical identity key used everywhere in the project.venueshould be the normalized venue name andsymbolshould remain stable for the life of a stream.SideusesBidandAskfor both book updates and trade aggressor direction.BookActionusesUpsertfor insert-or-replace semantics andDeletefor level removal.
§Book event types
BookUpdaterepresents a single level mutation.levelis the depth index from top of book.priceandsizeare integer-normalized values.sequence,ts_exchange_ns, andts_recv_nspreserve replay ordering and latency analysis.BookLevelis the materialized view of one price level after runtime consolidation.BookSnapshotis the full reconstructed book for one symbol at one point in time.bidsandasksare level-ordered arrays.last_sequenceis the sequence of the last applied update.ts_exchange_nsandts_recv_nsare copied from that last applied update.
§Trade event types
TradePrintrepresents one normalized trade.priceandsizeare integer-normalized.aggressor_sideis the trade direction used by the analytics engine.sequencemay be zero when a source does not provide a venue sequence.
§Analytics and signal output types
AnalyticsSnapshotis the base session analytics payload. It includes directional volume, delta, cumulative delta, POC, value area, and the active quality flags.DerivedAnalyticsSnapshotadds additive session totals that were intentionally kept out of the original analytics payload so older consumers would not break.SessionCandleSnapshotis a session-wide candle view derived from ingested trades.IntervalCandleSnapshotis a rolling-window candle view computed on demand from recent trades for a caller-suppliedwindow_ns.SignalStateis the stable directional state machine used across the runtime and bindings.SignalSnapshotpackages state, confidence, reason text, and quality flags for downstream consumers.
§AnalyticsAccumulator Contract
AnalyticsAccumulator is session-oriented.
AnalyticsAccumulator::on_trademutates all session analytics state from one trade.AnalyticsAccumulator::reset_session_deltaclears directional volume and delta state but keeps longer-lived session context that is not explicitly reset.AnalyticsAccumulator::reset_sessionclears the full session state, including candle and derived totals.AnalyticsAccumulator::snapshotreturns the base analytics payload.AnalyticsAccumulator::derived_snapshotreturns additive totals such asvwapandaverage_trade_size.AnalyticsAccumulator::session_candle_snapshotreturns the session candle built from all trades seen since the last session reset.AnalyticsAccumulator::interval_candle_snapshotcomputes a rolling candle over the recent trade window without mutating session state.
Important behavior:
- No book data is required for
AnalyticsAccumulator; it is trade-driven. - All price and size arithmetic uses integer math at ingest time and converts only where a derived floating result is needed, such as
vwap. point_of_controlis volume-based, not quote-based.- Value area fields are derived from traded-volume distribution, not full order-book depth.
§Quick Start
use of_core::{AnalyticsAccumulator, Side, SymbolId, TradePrint};
let symbol = SymbolId {
venue: "CME".to_string(),
symbol: "ESM6".to_string(),
};
let mut acc = AnalyticsAccumulator::default();
acc.on_trade(&TradePrint {
symbol,
price: 505_000,
size: 10,
aggressor_side: Side::Ask,
sequence: 1,
ts_exchange_ns: 1,
ts_recv_ns: 2,
});
let snap = acc.snapshot();
assert_eq!(snap.buy_volume, 10);
assert_eq!(snap.delta, 10);§Quality Flags
DataQualityFlags is a bitset used to express data-health issues such as stale feed, sequence gaps,
and out-of-order events. Signals and runtime gating can use these flags to block unsafe decisions.
use of_core::DataQualityFlags;
let q = DataQualityFlags::STALE_FEED | DataQualityFlags::SEQUENCE_GAP;
assert!(q.intersects(DataQualityFlags::STALE_FEED));
assert_eq!(q.bits() & DataQualityFlags::SEQUENCE_GAP.bits(), DataQualityFlags::SEQUENCE_GAP.bits());§Analytics Model Notes
deltatracks current session directional imbalance.cumulative_deltaretains directional accumulation over time.point_of_controlis computed as highest-volume price level.value_area_low/value_area_highapproximate the high-volume range around POC.DerivedAnalyticsSnapshotadds session totals such astotal_volume,trade_count,vwap,average_trade_size, andimbalance_bpswithout changing the original analytics payload.SessionCandleSnapshotadds a candle-style session view withopen,high,low,close,trade_count, and first/last exchange timestamps.IntervalCandleSnapshotadds a parameterized rolling-window candle view withwindow_ns,open,high,low,close,trade_count,total_volume,vwap, and first/last exchange timestamps.
For full orchestration and adapter integration, see of_runtime.
§Book Snapshot Model
BookSnapshot materializes the latest known order book for one symbol:
bids: bid-side levels ordered bylevelasks: ask-side levels ordered bylevellast_sequence: sequence number of the most recent applied book eventts_exchange_ns/ts_recv_ns: timestamps from the most recent applied book event
This snapshot model is used by the runtime and exposed through the FFI and bindings.
§Choosing the Right Snapshot Type
- Use
AnalyticsSnapshotwhen you want the original compact analytics contract. - Use
DerivedAnalyticsSnapshotwhen you need totals such astrade_countorvwap. - Use
SessionCandleSnapshotwhen you want one candle for the entire active session. - Use
IntervalCandleSnapshotwhen you want a rolling lookback window. - Use
BookSnapshotwhen you need reconstructed depth instead of raw incremental updates.
§Real-World Use Cases
§1. Offline research and replay analytics
Use AnalyticsAccumulator directly when you already have normalized trade
data and want deterministic session analytics without the full runtime.
Typical use cases:
- replaying one session from a CSV/JSONL converter
- validating a strategy hypothesis before wiring live adapters
- generating session summaries for dashboards or reports
§2. Shared schema between components
Use of_core as the common contract when writing:
- custom adapters that emit normalized
BookUpdateandTradePrint - custom signal modules that consume
AnalyticsSnapshot - persistence or replay tools that must stay aligned with runtime semantics
§3. Strategy prototyping before runtime integration
For early-stage ideas, it is often faster to work only with TradePrint,
AnalyticsAccumulator, and the output snapshot types before integrating with
of_runtime.
§Detailed Example: Build Session Analytics From Trades
use of_core::{AnalyticsAccumulator, Side, SymbolId, TradePrint};
fn main() {
let symbol = SymbolId {
venue: "CME".to_string(),
symbol: "ESM6".to_string(),
};
let trades = vec![
TradePrint {
symbol: symbol.clone(),
price: 505_000,
size: 8,
aggressor_side: Side::Ask,
sequence: 1,
ts_exchange_ns: 1_000,
ts_recv_ns: 1_100,
},
TradePrint {
symbol: symbol.clone(),
price: 505_025,
size: 4,
aggressor_side: Side::Ask,
sequence: 2,
ts_exchange_ns: 2_000,
ts_recv_ns: 2_100,
},
TradePrint {
symbol,
price: 505_000,
size: 6,
aggressor_side: Side::Bid,
sequence: 3,
ts_exchange_ns: 3_000,
ts_recv_ns: 3_100,
},
];
let mut acc = AnalyticsAccumulator::default();
for trade in &trades {
acc.on_trade(trade);
}
let analytics = acc.snapshot();
let derived = acc.derived_snapshot();
let session_candle = acc.session_candle_snapshot();
let interval_candle = acc.interval_candle_snapshot(5_000);
println!(
"delta={} poc={} total_volume={} vwap={:.2}",
analytics.delta,
analytics.point_of_control,
derived.total_volume,
derived.vwap
);
println!(
"session ohlc=({}, {}, {}, {}) trades={}",
session_candle.open,
session_candle.high,
session_candle.low,
session_candle.close,
session_candle.trade_count
);
println!(
"interval close={} interval_vwap={:.2}",
interval_candle.close,
interval_candle.vwap
);
}§Strategy-Prototyping Pattern
A common progression is:
- use
TradePrintandAnalyticsAccumulatorto compute deterministic features - test threshold logic over
AnalyticsSnapshotandDerivedAnalyticsSnapshot - once stable, move the logic into an
of_signals::SignalModule - finally run it inside
of_runtimefor live or replay orchestration
Structs§
- ACDModel
- Tracks trade durations and estimates ACD(1,1).
- ACDSnapshot
- ACD(1,1) model for trade duration.
- Agent
Type Detector - Infers agent types from trade and book patterns.
- Agent
Type Snapshot - Agent-type identification snapshot.
- Alert
Rule - Configurable real-time alert switches.
- Almgren
Chriss - Tracks volume and price changes for impact estimation.
- Almgren
Chriss Snapshot - Almgren-Chriss market impact model.
- Amihud
Snapshot - Snapshot of Amihud illiquidity.
- Amihud
Tracker - Tracks Amihud Illiquidity:
|return| / dollar_volumeper bar. - Analytics
Accumulator - In-memory accumulator that updates analytics state from normalized trades.
- Analytics
Config - Configurable analytics thresholds and buffer sizes. All fields have sensible defaults suitable for typical US equity/crypto markets. Pass an instance to the runtime engine config setter or the C ABI setter to override.
- Analytics
Snapshot - Aggregated analytics for a symbol/session.
- Book
Analytics Snapshot - Snapshot of book-derived analytics computed from an order book snapshot.
- Book
Event Analytics Snapshot - A snapshot of book-event analytics.
- Book
Event Sample - A single book update event for analytics.
- Book
Event Tracker - Tracks order-book update events for rate and size-distribution analytics.
- Book
Level - One normalized price level in a materialized book snapshot.
- Book
Snapshot - Materialized order-book snapshot for a symbol.
- Book
Update - Level-2 order book update.
- Classifier
Weights - Weights for the consensus voting classifier.
- Completed
Bar - A completed fixed-interval OHLCV bar.
- Crypto
Snapshot - Snapshot of crypto-market flow analytics.
- CvdEnhancement
Snapshot - Snapshot of CVD enhancement metrics.
- CvdEnhancements
- Tracks CVD (Cumulative Volume Delta) enhancements: ratio, z-score, divergence.
- Dark
LitCorrelation Snapshot - Snapshot of dark-lit imbalance correlation.
- Dark
LitCorrelator - Tracks rolling dark-lit imbalance correlation.
- Dark
Pool Snapshot - Dark pool analytics snapshot.
- Dark
Pool Tracker - Tracks dark pool volume alongside lit volume.
- Data
Quality Flags - Bitset wrapper for feed-quality flags.
- Derived
Analytics Snapshot - Additive derived analytics computed from the current session accumulator state.
- FXSnapshot
- Snapshot of FX-specific flow analytics.
- Fixed
Income Snapshot - Snapshot of fixed-income flow analytics.
- Futures
Snapshot - Futures analytics snapshot.
- Futures
Tracker - Tracker for futures contract roll and basis.
- Hasbrouck
Snapshot - Hasbrouck bivariate VAR(1) for price impact decomposition.
- HasbrouckVAR
- Tracks returns and signed volume for Hasbrouck VAR.
- Institutional
Flow Snapshot - Snapshot of institutional-flow classification.
- Institutional
Flow Tracker - Tracks large trades for institutional-flow classification.
- Interval
Candle Snapshot - Rolling interval candle-style summary derived from recent session trades.
- Kinetic
Energy Snapshot - Kinetic energy of order book activity.
- Kinetic
Energy Tracker - Tracks book changes to compute kinetic energy analogues.
- Kyle
Lambda Snapshot - Snapshot of Kyle’s Lambda estimation.
- Kyle
Lambda Tracker - Tracks Kyle’s Lambda:
ΔP = α + λ * signed_volume + εover a rolling window. - LOBFeature
Snapshot - 40+ hand-crafted LOB features for ML models.
- Microstructure
Noise - Tracks price returns for noise estimation.
- Noise
Snapshot - Microstructure noise estimate and signal-to-noise ratio.
- OIAnalysis
Snapshot - Snapshot of open-interest analysis.
- OIAnalyzer
- Tracks open interest and price for divergence analysis.
- Options
Flow Snapshot - Options flow snapshot.
- Options
Flow Tracker - Tracks options trade flow.
- Pattern
Detector - Detects practitioner orderflow patterns from book and trade data.
- Pattern
Snapshot - All detected practitioner patterns in one snapshot. Snapshot of all detected practitioner patterns.
- Regime
Detector - Classifies market regime from spread, volatility, and VPIN.
- Regime
Snapshot - Snapshot of market-regime classification metrics.
- Resiliency
Sample - Book depth around a single trade.
- Resiliency
Snapshot - A snapshot of book resiliency metrics for the most recent trade.
- Resiliency
Tracker - Tracks book depth before and after trades for resiliency metrics.
- Session
Candle Snapshot - Session candle-style summary derived from the current analytics session.
- Signal
Snapshot - Snapshot of a signal module evaluation.
- Spread
Decomposition - Tracks spreads for Huang-Stoll decomposition.
- Spread
Decomposition Snapshot - Huang-Stoll spread decomposition.
- Spread
Sample - One recorded trade for spread tracking.
- Spread
Tracker - Tracks effective and realised spread for recent trades.
- Symbol
Id - Canonical market symbol identifier used across venues.
- Trade
Classifier - Classifies trades using multiple methods: tick rule, quote rule, Lee-Ready, and consensus.
- Trade
Print - Last-trade print/tick.
- Volatility
Estimator - Tracks OHLC prices per bar for volatility estimation.
- Volatility
Signature - Computes volatility signature from return series.
- Volatility
Signature Point - Volatility signature result at a specific lag.
- Volatility
Signature Snapshot - Volatility signature plot: RV at multiple lags.
- Volatility
Snapshot - Realised volatility estimators: Classic, Parkinson, Garman-Klass, Yang-Zhang.
- Vpin
Snapshot - A single VPIN snapshot.
- Vpin
Tracker - Tracks Volume-Synchronized Probability of Informed Trading (VPIN).
Enums§
- Book
Action - Book mutation kind.
- Classification
Vote - Result of a single trade classification method.
- Regime
- Market regime classification.
- Side
- Trade or book side.
- Signal
State - Output state emitted by signal modules.
Traits§
- State
Checkpoint - Trait for state serialization.
Functions§
- compute_
book_ analytics - Computes book-derived analytics from a materialized order book snapshot.
- compute_
depth_ slope - Computes the depth slope — average volume decay per level away from the top of book.
- compute_
effective_ spread_ bps - Computes effective spread in basis points for a single trade.
- compute_
lob_ features - Computes LOB features from book snapshot and trade flow.
- compute_
mid_ price - Returns the mid price from a book snapshot, or
Noneif either side is empty. - compute_
realised_ spread_ bps - Computes realised spread in basis points.
- compute_
weighted_ average_ price - Computes the weighted average price for an order of
qtyshares walking the book.