#[repr(align(64))]pub struct TradeBatch { /* private fields */ }Expand description
Efficient storage for a batch of trades using cache-line alignment and zero-allocation strategies for HFT applications
Implementations§
Source§impl TradeBatch
impl TradeBatch
Sourcepub fn new(instrument_id: InstrumentId) -> Self
pub fn new(instrument_id: InstrumentId) -> Self
Creates a new, empty TradeBatch with pre-allocated capacity
Sourcepub fn with_clock(instrument_id: InstrumentId, clock: Clock) -> Self
pub fn with_clock(instrument_id: InstrumentId, clock: Clock) -> Self
Creates a new TradeBatch with the specified clock
Sourcepub fn add_trade(
&mut self,
price: Decimal,
quantity: Decimal,
direction: OrderSide,
exchange_time_ns: u64,
)
pub fn add_trade( &mut self, price: Decimal, quantity: Decimal, direction: OrderSide, exchange_time_ns: u64, )
Adds a new trade to the batch with minimal allocation
This method creates a new trade and inserts it into the batch in chronological order using binary search to find the correct insertion position. This ensures that trades are always sorted by timestamp, which improves the performance of time-based queries.
§Performance considerations
- Uses binary search for O(log n) insertion position finding
- Maintains chronological order without sorting the entire vector
- Updates the
last_updatetimestamp atomically
Sourcepub fn trades(&self) -> &[MarketTrade]
pub fn trades(&self) -> &[MarketTrade]
Returns a reference to all trades in this batch
Sourcepub const fn instrument_id(&self) -> &InstrumentId
pub const fn instrument_id(&self) -> &InstrumentId
Gets the instrument ID for this trade batch
Sourcepub const fn last_update(&self) -> u64
pub const fn last_update(&self) -> u64
Gets the last update timestamp
Sourcepub fn count_by_direction(&self, direction: OrderSide) -> usize
pub fn count_by_direction(&self, direction: OrderSide) -> usize
Filters trades by a specified direction without allocation Returns a count rather than a collection to avoid allocations
Sourcepub fn iter_by_direction(
&self,
direction: OrderSide,
) -> impl Iterator<Item = &MarketTrade> + '_
pub fn iter_by_direction( &self, direction: OrderSide, ) -> impl Iterator<Item = &MarketTrade> + '_
Returns a filtered iterator for trades with the specified direction
Sourcepub fn iter_after(
&self,
timestamp: Instant,
) -> impl Iterator<Item = &MarketTrade> + '_
pub fn iter_after( &self, timestamp: Instant, ) -> impl Iterator<Item = &MarketTrade> + '_
Filters trades that occurred after a specific timestamp Returns an iterator to avoid allocations
Sourcepub fn iter_before(
&self,
timestamp: Instant,
) -> impl Iterator<Item = &MarketTrade> + '_
pub fn iter_before( &self, timestamp: Instant, ) -> impl Iterator<Item = &MarketTrade> + '_
Filters trades that occurred before a specific timestamp Returns an iterator to avoid allocations
Sourcepub fn total_volume(&self) -> Decimal
pub fn total_volume(&self) -> Decimal
Computes the total volume in the batch
This method is optimized for high-frequency trading using SIMD instructions when available. It extracts quantity values from trades and uses SIMD-accelerated summation for maximum performance.
§Performance considerations
- Uses SIMD instructions for parallel processing when available
- Falls back to scalar operations for small trade counts
- Avoids heap allocations for small to medium-sized batches
- Optimized for both small and large trade batches
Sourcepub fn buy_volume(&self) -> Decimal
pub fn buy_volume(&self) -> Decimal
Computes the buy volume in the batch
This method is optimized for high-frequency trading using SIMD instructions when available. It filters trades by direction and uses SIMD-accelerated summation for maximum performance.
§Performance considerations
- Uses SIMD instructions for parallel processing when available
- Falls back to scalar operations for small trade counts
- Avoids heap allocations for small to medium-sized batches
- Optimized for both small and large trade batches
Sourcepub fn sell_volume(&self) -> Decimal
pub fn sell_volume(&self) -> Decimal
Computes the sell volume in the batch
This method is optimized for high-frequency trading using SIMD instructions when available. It filters trades by direction and uses SIMD-accelerated summation for maximum performance.
§Performance considerations
- Uses SIMD instructions for parallel processing when available
- Falls back to scalar operations for small trade counts
- Avoids heap allocations for small to medium-sized batches
- Optimized for both small and large trade batches
Sourcepub fn volume_imbalance(&self) -> Option<f64>
pub fn volume_imbalance(&self) -> Option<f64>
Computes the volume imbalance ratio (buy_volume - sell_volume) / total_volume
Returns a value between -1.0 and 1.0
This method calculates the imbalance between buy and sell volumes, which is a key indicator of market pressure. A positive value indicates more buying pressure, while a negative value indicates more selling pressure.
§Performance considerations
- Uses the optimized
buy_volumeandsell_volumemethods - Avoids redundant calculations by computing the total directly
- Handles edge cases efficiently (empty batch, zero total volume)
- Uses safe conversion to f64 with fallback
§Returns
- Some(f64): The volume imbalance ratio between -1.0 and 1.0
- None: If the batch is empty or the total volume is zero
Sourcepub fn vwap(&self) -> Option<Decimal>
pub fn vwap(&self) -> Option<Decimal>
Computes the VWAP (Volume Weighted Average Price) for the batch
VWAP is a trading benchmark that gives the average price a security has traded at throughout the period, based on both volume and price. It provides insight into both the trend and value of a security.
§Performance considerations
- Uses SIMD-accelerated dot product for price*quantity calculations
- Uses the optimized
total_volumemethod for quantity sum - Avoids heap allocations for small to medium-sized batches
- Handles edge cases efficiently (empty batch, zero total volume)
- Optimized for both small and large trade batches
§Returns
- Some(Decimal): The volume-weighted average price
- None: If the batch is empty or the total volume is zero
Sourcepub fn vwap_by_direction(&self, direction: OrderSide) -> Option<Decimal>
pub fn vwap_by_direction(&self, direction: OrderSide) -> Option<Decimal>
Computes the VWAP for a specific direction (buy or sell)
This method calculates the Volume Weighted Average Price for trades in a specific direction (buy or sell). This is useful for analyzing price trends separately for buys and sells.
§Performance considerations
- Uses SIMD-accelerated dot product for price*quantity calculations
- Filters trades by direction efficiently
- Avoids heap allocations for small to medium-sized batches
- Handles edge cases efficiently (empty batch, zero total volume)
- Optimized for both small and large trade batches
§Parameters
direction: The trade direction to calculate VWAP for (Buy or Sell)
§Returns
- Some(Decimal): The volume-weighted average price for the specified direction
- None: If there are no trades in the specified direction or the total volume is zero
Sourcepub fn truncate(&mut self, size: usize)
pub fn truncate(&mut self, size: usize)
Truncate the batch to the specified size, keeping only the most recent trades
This method ensures that the batch contains at most size trades, removing
older trades if necessary. Since trades are inserted in chronological order,
this effectively creates a sliding window of the most recent trades.
§Performance considerations
- Uses an optimized approach to minimize memory operations
- For small batches, uses the standard drain method
- For large batches, creates a new
SmallVecwith the most recent trades - Updates the
last_updatetimestamp atomically
§Parameters
size: The maximum number of trades to keep in the batch
Sourcepub fn latest_trade(&self) -> Option<&MarketTrade>
pub fn latest_trade(&self) -> Option<&MarketTrade>
Get the most recent trade
Sourcepub fn average_trade_size(&self) -> Option<Decimal>
pub fn average_trade_size(&self) -> Option<Decimal>
Calculate the average trade size
Sourcepub fn median_price(&self) -> Option<Decimal>
pub fn median_price(&self) -> Option<Decimal>
Calculate the median trade price
The median price is the middle value when all prices are sorted. For an even number of trades, it’s the average of the two middle values. This is a robust measure of central tendency that is less affected by outliers than the mean.
§Performance considerations
- Uses an optimized approach based on the number of trades
- For small batches, uses a simple sort-based approach
- For larger batches, uses a partial sort to find the median efficiently
- Avoids unnecessary allocations and copies where possible
- Handles edge cases efficiently (empty batch, single trade)
§Returns
- Some(Decimal): The median price
- None: If the batch is empty