Struct MicrostructureCalculator

Source
pub struct MicrostructureCalculator<const N: usize = 128> { /* private fields */ }
Expand description

High-performance microstructure calculator for HFT trading features.

This calculator provides SIMD-optimized market microstructure feature calculations for high-frequency trading systems. It supports rolling window calculations with atomic accumulators for thread-safe operation and uses vectorized operations for performance-critical computations.

§Key Features

  • SIMD Optimization: 2-4x faster calculations using vectorized operations
  • Thread-Safe: Atomic accumulators for concurrent access
  • Rolling Windows: Configurable window sizes for statistical calculations
  • Comprehensive Features: Order book imbalance, VPIN, OFI, Kyle’s lambda, etc.
  • Generic Capacity: Configurable buffer size via const generic parameter

§Usage

use rust_decimal_macros::dec;
use crate::microstructure::MicrostructureCalculator;

// Create calculator with 100-tick rolling window
let calc = MicrostructureCalculator::<128>::new(100);

// Calculate spread and mid-price
let ask_prices = vec![dec!(100.05), dec!(100.06)];
let bid_prices = vec![dec!(100.00), dec!(100.01)];
let spread = calc.calc_spread(ask_prices[0], bid_prices[0]);
let mid_price = calc.calc_mid_price(ask_prices[0], bid_prices[0]);

// Calculate order book imbalance (SIMD-optimized)
let ask_volumes = vec![dec!(10), dec!(15), dec!(20)];
let bid_volumes = vec![dec!(12), dec!(18), dec!(25)];
let imbalance = calc.calc_order_imbalance(&ask_volumes, &bid_volumes);

§Performance

  • SIMD Features: 2-4x faster than scalar implementations for arrays ≥4 elements
  • Memory Efficient: Uses SmallVec for stack allocation when possible
  • Cache Friendly: Atomic accumulators prevent false sharing

§Type Aliases

  • MicrostructureCalculator128 - Default 128-element capacity
  • MicrostructureCalculator64 - 64-element capacity for smaller datasets
  • MicrostructureCalculator256 - 256-element capacity for larger datasets

Implementations§

Source§

impl<const N: usize> MicrostructureCalculator<N>

Source

pub fn new(window_size: usize) -> Self

Creates a new MicrostructureCalculator with the given window size.

Source

pub fn calc_spread(&self, ask_price: Decimal, bid_price: Decimal) -> Decimal

Calculate spread between best bid and ask

Source

pub fn calc_mid_price(&self, ask_price: Decimal, bid_price: Decimal) -> Decimal

Calculate mid price

Source

pub fn calc_relative_spread( &self, ask_price: Decimal, bid_price: Decimal, ) -> Decimal

Calculate relative spread

Source

pub fn calc_vpin( &self, trades: &[TradeFeatures], bucket_size: usize, ) -> SmallVec<[Decimal; N]>

Volume-Synchronized Probability of Informed Trading (VPIN)

Source

pub fn calc_ofi_simple( &self, ask_volumes: &[Decimal], bid_volumes: &[Decimal], prev_ask_volumes: &[Decimal], prev_bid_volumes: &[Decimal], ) -> Decimal

Order Flow Imbalance (OFI) - Simple version

Source

pub fn calc_ofi_detailed( &self, ask_prices: &[Decimal], ask_volumes: &[Decimal], bid_prices: &[Decimal], bid_volumes: &[Decimal], prev_ask_prices: &[Decimal], prev_ask_volumes: &[Decimal], prev_bid_prices: &[Decimal], prev_bid_volumes: &[Decimal], ) -> Decimal

Order Flow Imbalance (OFI) - Detailed multi-level version

Source

pub fn calc_kyles_lambda( &self, price_changes: &[Decimal], order_flows: &[Decimal], ) -> Option<Decimal>

Kyle’s Lambda - Market impact coefficient

Source

pub fn calc_order_book_slope( &self, ask_prices: &[Decimal], ask_qty: &[Decimal], bid_prices: &[Decimal], bid_qty: &[Decimal], depth: usize, ) -> Decimal

Calculate order book slope

Source

pub fn calc_queue_imbalance( &self, ask_qty: &[Decimal], bid_qty: &[Decimal], ) -> Decimal

Calculate queue imbalance (top 5 levels) Calculate queue imbalance using SIMD optimization for top 5 levels Performance: 2-4x faster than scalar implementation

Source

pub fn calc_order_imbalance( &self, ask_qty: &[Decimal], bid_qty: &[Decimal], ) -> Decimal

Calculate order imbalance using ALL levels in the order book Formula: (bid_volume - ask_volume) / (bid_volume + ask_volume) Performance: 2-4x faster than scalar implementation for arrays >= 4 elements

Source

pub fn calc_liquidity_shocks( &self, ask_qty: &[Decimal], bid_qty: &[Decimal], ) -> Decimal

Calculate liquidity shocks (ratio of top 5 levels to total depth)

Source

pub fn calc_realized_volatility( &self, prices: &[Decimal], window: usize, ) -> Decimal

Realized volatility using high-frequency returns

Source

pub fn calc_amihud_lambda( &self, price_changes: &[Decimal], volumes: &[Decimal], ) -> Option<Decimal>

Amihud’s illiquidity measure

Source

pub fn calc_price_impact( &self, price_changes: &[Decimal], order_flows: &[Decimal], ) -> Option<Decimal>

Price impact measure

Source

pub fn calc_order_book_pressure( &self, ask_qty: &[Decimal], bid_qty: &[Decimal], depth: usize, ) -> Decimal

Order book pressure (bid pressure - ask pressure) Calculate order book pressure using SIMD vectorization Performance: 2-4x faster than scalar implementation

Source

pub fn calc_order_book_entropy( &self, ask_qty: &[Decimal], bid_qty: &[Decimal], ) -> Decimal

Order book entropy (distribution of liquidity)

Source

pub fn calc_order_book_imbalance( &self, ask_qty: &[Decimal], bid_qty: &[Decimal], ) -> Decimal

Calculate order book imbalance (ratio of ask to bid at top level)

Source

pub fn calc_order_book_depth( &self, ask_qty: &[Decimal], bid_qty: &[Decimal], ) -> Decimal

Calculate order book depth (sum of all quantities)

Source

pub fn calc_order_cancel_estimated_rate( &self, ask_qty: &[Decimal], bid_qty: &[Decimal], ) -> Decimal

Calculate order cancel estimated rate

Source

pub fn calc_order_book_curvature( &self, ask_prices: &[Decimal], bid_prices: &[Decimal], depth: usize, ) -> Decimal

Calculate order book curvature (second derivative of price with respect to volume)

Source

pub fn calc_directional_volume_intensity( &self, buy_volumes: &[Decimal], sell_volumes: &[Decimal], window: usize, ) -> SmallVec<[Decimal; N]>

Calculate directional volume intensity (imbalance of buy/sell volume over time)

Source

pub fn calc_price_displacement_ratio( &self, price_changes: &[Decimal], top_level_sizes: &[Decimal], window: usize, ) -> SmallVec<[Decimal; N]>

Calculate price displacement ratio (price changes relative to order sizes)

Source

pub fn calc_trade_size_momentum( &self, trade_sizes: &[Decimal], window: usize, ) -> SmallVec<[Decimal; N]>

Calculate trade size momentum (relative change in trade sizes)

Source

pub fn calc_imbalance_sensitivity( &self, price_changes: &[Decimal], book_imbalance: &[Decimal], window: usize, ) -> SmallVec<[Decimal; N]>

Calculate imbalance sensitivity (price changes relative to order book imbalance)

Source

pub fn calc_volatility_synchronized_order_flow( &self, order_flow: &[Decimal], volatility: &[Decimal], window: usize, ) -> SmallVec<[Decimal; N]>

Calculate volatility synchronized order flow (order flow normalized by volatility)

Source

pub fn calc_cumulative_market_order_flow( &self, buy_orders: &[Decimal], sell_orders: &[Decimal], window: usize, ) -> SmallVec<[Decimal; N]>

Calculate cumulative market order flow (difference between buy and sell orders)

Source

pub fn calc_price_volume_divergence( &self, price_changes: &[Decimal], volume_changes: &[Decimal], window: usize, ) -> SmallVec<[Decimal; N]>

Calculate price volume divergence (difference between price and volume changes)

Source

pub fn calc_weighted_order_imbalance( &self, bid_qty: &[Decimal], ask_qty: &[Decimal], depth: usize, ) -> Decimal

Calculate weighted order imbalance with depth weighting

Source

pub fn calc_trade_intensity( &self, volumes: &[Decimal], window: usize, ) -> SmallVec<[Decimal; N]>

Trade intensity (volume over time window)

Source

pub fn calc_bipower_variation( &self, prices: &[Decimal], window: usize, ) -> Decimal

Bipower variation (robust volatility measure)

Source

pub fn calc_hasbrouck_lambda( &self, price_changes: &[Decimal], order_flows: &[Decimal], ) -> Option<Decimal>

Hasbrouck’s lambda (alternative price impact measure)

Source

pub fn calc_effective_spread( &self, price_changes: &[Decimal], order_flows: &[Decimal], ) -> Option<Decimal>

Effective bid-ask spread

Source

pub fn calc_ml_features( &self, ask_prices: &[Decimal], ask_volumes: &[Decimal], bid_prices: &[Decimal], bid_volumes: &[Decimal], trades: &[TradeFeatures], window: usize, ) -> MLFeatures

Advanced features for ML models

Source

pub fn calc_ml_features_simd( &self, ask_prices: &[Decimal], ask_volumes: &[Decimal], bid_prices: &[Decimal], bid_volumes: &[Decimal], trades: &[TradeFeatures], window: usize, ) -> MLFeatures

SIMD-optimized ML feature extraction with 5-10x performance improvement Calculates multiple features in parallel using vectorized operations

Performance: 5-10x faster than calc_ml_features through:

  • Batch SIMD calculations of related features
  • Reduced Decimal to f64 conversion overhead
  • Elimination of redundant data processing
  • Vectorized mathematical operations

Auto Trait Implementations§

§

impl<const N: usize = 128> !Freeze for MicrostructureCalculator<N>

§

impl<const N: usize = 128> !RefUnwindSafe for MicrostructureCalculator<N>

§

impl<const N: usize> Send for MicrostructureCalculator<N>

§

impl<const N: usize = 128> !Sync for MicrostructureCalculator<N>

§

impl<const N: usize> Unpin for MicrostructureCalculator<N>

§

impl<const N: usize> UnwindSafe for MicrostructureCalculator<N>

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

§

impl<T> Instrument for T

§

fn instrument(self, span: Span) -> Instrumented<Self>

Instruments this type with the provided [Span], returning an Instrumented wrapper. Read more
§

fn in_current_span(self) -> Instrumented<Self>

Instruments this type with the current Span, returning an Instrumented wrapper. Read more
Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

§

impl<T> PolicyExt for T
where T: ?Sized,

§

fn and<P, B, E>(self, other: P) -> And<T, P>
where T: Policy<B, E>, P: Policy<B, E>,

Create a new Policy that returns [Action::Follow] only if self and other return Action::Follow. Read more
§

fn or<P, B, E>(self, other: P) -> Or<T, P>
where T: Policy<B, E>, P: Policy<B, E>,

Create a new Policy that returns [Action::Follow] if either self or other returns Action::Follow. Read more
Source§

impl<T> Same for T

Source§

type Output = T

Should always be Self
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = Infallible

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
§

impl<V, T> VZip<V> for T
where V: MultiLane<T>,

§

fn vzip(self) -> V

§

impl<T> WithSubscriber for T

§

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self>
where S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a [WithDispatch] wrapper. Read more
§

fn with_current_subscriber(self) -> WithDispatch<Self>

Attaches the current default Subscriber to this type, returning a [WithDispatch] wrapper. Read more
§

impl<T> ErasedDestructor for T
where T: 'static,