Struct TradeBatch

Source
#[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

Source

pub fn new(instrument_id: InstrumentId) -> Self

Creates a new, empty TradeBatch with pre-allocated capacity

Source

pub fn with_clock(instrument_id: InstrumentId, clock: Clock) -> Self

Creates a new TradeBatch with the specified clock

Source

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_update timestamp atomically
Source

pub fn trades(&self) -> &[MarketTrade]

Returns a reference to all trades in this batch

Source

pub fn len(&self) -> usize

Returns the number of trades in this batch

Source

pub fn is_empty(&self) -> bool

Returns true if this batch is empty

Source

pub const fn instrument_id(&self) -> &InstrumentId

Gets the instrument ID for this trade batch

Source

pub const fn last_update(&self) -> u64

Gets the last update timestamp

Source

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

Source

pub fn iter_by_direction( &self, direction: OrderSide, ) -> impl Iterator<Item = &MarketTrade> + '_

Returns a filtered iterator for trades with the specified direction

Source

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

Source

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

Source

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
Source

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
Source

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
Source

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_volume and sell_volume methods
  • 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
Source

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_volume method 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
Source

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
Source

pub fn clear(&mut self)

Clear all trades but retain allocated memory

Source

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 SmallVec with the most recent trades
  • Updates the last_update timestamp atomically
§Parameters
  • size: The maximum number of trades to keep in the batch
Source

pub fn latest_trade(&self) -> Option<&MarketTrade>

Get the most recent trade

Source

pub fn average_trade_size(&self) -> Option<Decimal>

Calculate the average trade size

Source

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

Trait Implementations§

Source§

impl Debug for TradeBatch

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more

Auto Trait Implementations§

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,