Skip to main content

OpenDeviationBar

Struct OpenDeviationBar 

Source
pub struct OpenDeviationBar {
Show 70 fields pub open_time: i64, pub close_time: i64, pub open: FixedPoint, pub high: FixedPoint, pub low: FixedPoint, pub close: FixedPoint, pub volume: i128, pub turnover: i128, pub buy_volume: i128, pub sell_volume: i128, pub buy_turnover: i128, pub sell_turnover: i128, pub first_trade_id: i64, pub last_trade_id: i64, pub first_agg_trade_id: i64, pub last_agg_trade_id: i64, pub individual_trade_count: u32, pub agg_record_count: u32, pub buy_trade_count: u32, pub sell_trade_count: u32, pub vwap: FixedPoint, pub data_source: DataSource, pub duration_us: i64, pub ofi: f64, pub vwap_close_deviation: f64, pub price_impact: f64, pub kyle_lambda_proxy: f64, pub trade_intensity: f64, pub volume_per_trade: f64, pub aggression_ratio: f64, pub aggregation_density_f64: f64, pub turnover_imbalance: f64, pub lookback_trade_count: Option<u32>, pub lookback_ofi: Option<f64>, pub lookback_duration_us: Option<i64>, pub lookback_intensity: Option<f64>, pub lookback_vwap_raw: Option<i64>, pub lookback_vwap_position: Option<f64>, pub lookback_count_imbalance: Option<f64>, pub lookback_kyle_lambda: Option<f64>, pub lookback_burstiness: Option<f64>, pub lookback_volume_skew: Option<f64>, pub lookback_volume_kurt: Option<f64>, pub lookback_price_range: Option<f64>, pub lookback_kaufman_er: Option<f64>, pub lookback_garman_klass_vol: Option<f64>, pub lookback_hurst: Option<f64>, pub lookback_permutation_entropy: Option<f64>, pub intra_bull_epoch_density: Option<f64>, pub intra_bear_epoch_density: Option<f64>, pub intra_bull_excess_gain: Option<f64>, pub intra_bear_excess_gain: Option<f64>, pub intra_bull_cv: Option<f64>, pub intra_bear_cv: Option<f64>, pub intra_max_drawdown: Option<f64>, pub intra_max_runup: Option<f64>, pub intra_trade_count: Option<u32>, pub intra_ofi: Option<f64>, pub intra_duration_us: Option<i64>, pub intra_intensity: Option<f64>, pub intra_vwap_position: Option<f64>, pub intra_count_imbalance: Option<f64>, pub intra_kyle_lambda: Option<f64>, pub intra_burstiness: Option<f64>, pub intra_volume_skew: Option<f64>, pub intra_volume_kurt: Option<f64>, pub intra_kaufman_er: Option<f64>, pub intra_garman_klass_vol: Option<f64>, pub intra_hurst: Option<f64>, pub intra_permutation_entropy: Option<f64>,
}
Expand description

Open deviation bar with OHLCV data and market microstructure enhancements

Field ordering optimized for cache locality (Issue #96 Task #85):

  • Tier 1: OHLCV Core (48B, 1 CL)
  • Tier 2: Volume Accumulators (96B, 1.5 CL)
  • Tier 3: Trade Tracking (48B, 1 CL)
  • Tier 4: Price Context (24B, partial CL)
  • Tier 5: Microstructure (80B, 1.25 CL)
  • Tier 6-7: Inter-Bar & Intra-Bar Features

Fields§

§open_time: i64

Opening timestamp in microseconds (first trade)

§close_time: i64

Closing timestamp in microseconds (last trade)

§open: FixedPoint

Opening price (first trade price)

§high: FixedPoint

Highest price in bar

§low: FixedPoint

Lowest price in bar

§close: FixedPoint

Closing price (breach trade price)

§volume: i128

Total volume (i128 accumulator to prevent overflow, Issue #88)

§turnover: i128

Total turnover (sum of price * volume)

§buy_volume: i128

Volume from buy-side trades (is_buyer_maker = false) Represents aggressive buying pressure (i128 accumulator, Issue #88)

§sell_volume: i128

Volume from sell-side trades (is_buyer_maker = true) Represents aggressive selling pressure (i128 accumulator, Issue #88)

§buy_turnover: i128

Turnover from buy-side trades (buy pressure)

§sell_turnover: i128

Turnover from sell-side trades (sell pressure)

§first_trade_id: i64

First individual trade ID in this open deviation bar

§last_trade_id: i64

Last individual trade ID in this open deviation bar

§first_agg_trade_id: i64

First aggregate trade ID in this open deviation bar (Issue #72) Tracks the first AggTrade record that opened this bar

§last_agg_trade_id: i64

Last aggregate trade ID in this open deviation bar (Issue #72) Tracks the last AggTrade record processed in this bar

§individual_trade_count: u32

Total number of individual exchange trades in this open deviation bar Sum of individual_trade_count() from all processed AggTrade records

§agg_record_count: u32

Number of AggTrade records processed to create this open deviation bar NEW: Enables tracking of aggregation efficiency

§buy_trade_count: u32

Number of individual buy-side trades (aggressive buying)

§sell_trade_count: u32

Number of individual sell-side trades (aggressive selling)

§vwap: FixedPoint

Volume Weighted Average Price for the bar Calculated incrementally as: sum(price * volume) / sum(volume)

§data_source: DataSource

Data source this open deviation bar was created from

§duration_us: i64

Bar duration in microseconds (close_time - open_time) Reference: Easley et al. (2012) “Volume Clock”

§ofi: f64

Order Flow Imbalance: (buy_vol - sell_vol) / (buy_vol + sell_vol) Range: [-1.0, +1.0], Reference: Chordia et al. (2002)

§vwap_close_deviation: f64

VWAP-Close Deviation: (close - vwap) / (high - low) Measures intra-bar momentum, Reference: Berkowitz et al. (1988)

§price_impact: f64

Price Impact (Amihud-style): abs(close - open) / volume Reference: Amihud (2002) illiquidity ratio

§kyle_lambda_proxy: f64

Kyle’s Lambda Proxy: (close - open) / (buy_vol - sell_vol) Market depth measure, Reference: Kyle (1985)

§trade_intensity: f64

Trade Intensity: individual_trade_count / duration_seconds Reference: Engle & Russell (1998) ACD models

§volume_per_trade: f64

Average trade size: volume / individual_trade_count Reference: Barclay & Warner (1993) stealth trading

§aggression_ratio: f64

Aggression Ratio: buy_trade_count / sell_trade_count Capped at 100.0, Reference: Lee & Ready (1991)

§aggregation_density_f64: f64

Aggregation Density: individual_trade_count / agg_record_count Average number of individual trades per AggTrade record (Issue #32 rename) Higher values = more fragmented trades; Lower values = more consolidated orders

§turnover_imbalance: f64

Turnover Imbalance: (buy_turnover - sell_turnover) / total_turnover Dollar-weighted OFI, Range: [-1.0, +1.0]

§lookback_trade_count: Option<u32>

Number of trades in lookback window before bar opened

§lookback_ofi: Option<f64>

Order Flow Imbalance from lookback window: [-1, 1]

§lookback_duration_us: Option<i64>

Duration of lookback window in microseconds

§lookback_intensity: Option<f64>

Trade intensity in lookback: trades per second

§lookback_vwap_raw: Option<i64>

VWAP from lookback window (stored as FixedPoint raw value for serialization)

§lookback_vwap_position: Option<f64>

VWAP position within price range: [0, 1]

§lookback_count_imbalance: Option<f64>

Count imbalance: (buy_count - sell_count) / total_count, [-1, 1]

§lookback_kyle_lambda: Option<f64>

Kyle’s Lambda proxy from lookback (normalized)

§lookback_burstiness: Option<f64>

Burstiness (Goh-Barabasi): [-1, 1]

§lookback_volume_skew: Option<f64>

Volume skewness (Fisher-Pearson coefficient)

§lookback_volume_kurt: Option<f64>

Excess kurtosis of volume distribution

§lookback_price_range: Option<f64>

Price range normalized by first price

§lookback_kaufman_er: Option<f64>

Kaufman Efficiency Ratio: [0, 1]

§lookback_garman_klass_vol: Option<f64>

Garman-Klass volatility estimator

§lookback_hurst: Option<f64>

Hurst exponent via DFA, soft-clamped to [0, 1]

§lookback_permutation_entropy: Option<f64>

Permutation entropy (normalized): [0, 1]

§intra_bull_epoch_density: Option<f64>

Bull epoch density: sigmoid(epochs/trade_count, 0.5, 10)

§intra_bear_epoch_density: Option<f64>

Bear epoch density: sigmoid(epochs/trade_count, 0.5, 10)

§intra_bull_excess_gain: Option<f64>

Bull excess gain (sum): tanh-normalized to [0, 1]

§intra_bear_excess_gain: Option<f64>

Bear excess gain (sum): tanh-normalized to [0, 1]

§intra_bull_cv: Option<f64>

Bull intervals CV: sigmoid-normalized to [0, 1]

§intra_bear_cv: Option<f64>

Bear intervals CV: sigmoid-normalized to [0, 1]

§intra_max_drawdown: Option<f64>

Max drawdown within bar: [0, 1]

§intra_max_runup: Option<f64>

Max runup within bar: [0, 1]

§intra_trade_count: Option<u32>

Number of trades within the bar

§intra_ofi: Option<f64>

Order Flow Imbalance within bar: [-1, 1]

§intra_duration_us: Option<i64>

Duration of bar in microseconds

§intra_intensity: Option<f64>

Trade intensity: trades per second

§intra_vwap_position: Option<f64>

VWAP position within price range: [0, 1]

§intra_count_imbalance: Option<f64>

Count imbalance: (buy_count - sell_count) / total_count, [-1, 1]

§intra_kyle_lambda: Option<f64>

Kyle’s Lambda proxy (normalized)

§intra_burstiness: Option<f64>

Burstiness (Goh-Barabasi): [-1, 1]

§intra_volume_skew: Option<f64>

Volume skewness

§intra_volume_kurt: Option<f64>

Volume excess kurtosis

§intra_kaufman_er: Option<f64>

Kaufman Efficiency Ratio: [0, 1]

§intra_garman_klass_vol: Option<f64>

Garman-Klass volatility estimator

§intra_hurst: Option<f64>

Hurst exponent via DFA (requires >= 64 trades): [0, 1]

§intra_permutation_entropy: Option<f64>

Permutation entropy (requires >= 60 trades): [0, 1]

Implementations§

Source§

impl OpenDeviationBar

Source

pub fn new(trade: &AggTrade) -> OpenDeviationBar

Create new open deviation bar from opening AggTrade record Issue #96: #[inline] for bar-open hot path

Source

pub fn is_valid_range(&self, threshold_ratio: i64, multiplier: i64) -> bool

Issue #112: Check if bar’s price range stays within N * threshold.

Note: With open-anchored breach detection, bars can legitimately exceed 1x threshold through bidirectional movement (price dips then breaches in the opposite direction). This function is used in tests only — it is NOT a correctness invariant of the algorithm.

§Arguments
  • threshold_ratio - Pre-computed threshold ratio from OpenDeviationBarProcessor
  • multiplier - Multiplier for the check (2 in tests)
Source

pub fn aggregation_density(&self) -> f64

Average number of individual trades per AggTrade record (aggregation density)

Source

pub fn update_with_trade(&mut self, trade: &AggTrade)

Update bar with new AggTrade record (always call before checking breach) Maintains market microstructure metrics incrementally Issue #96: #[inline] for per-trade hot path (called on every non-opening trade)

Source

pub fn compute_microstructure_features(&mut self)

Compute all microstructure features at bar finalization (Issue #25)

This method computes 10 derived features from the accumulated bar state. All features use only data with timestamps <= bar.close_time (no lookahead).

§Features Computed
FeatureFormulaAcademic Reference
duration_usclose_time - open_timeEasley et al. (2012)
ofi(buy_vol - sell_vol) / totalChordia et al. (2002)
vwap_close_deviation(close - vwap) / (high - low)Berkowitz et al. (1988)
price_impactabs(close - open) / volumeAmihud (2002)
kyle_lambda_proxy(close - open) / (buy_vol - sell_vol)Kyle (1985)
trade_intensitytrade_count / duration_secondsEngle & Russell (1998)
volume_per_tradevolume / trade_countBarclay & Warner (1993)
aggression_ratiobuy_trades / sell_tradesLee & Ready (1991)
aggregation_density_f64trade_count / agg_count(proxy)
turnover_imbalance(buy_turn - sell_turn) / total_turn(proxy)
Source

pub fn is_breach( &self, price: FixedPoint, upper_threshold: FixedPoint, lower_threshold: FixedPoint, ) -> bool

Check if price breaches the range thresholds

§Arguments
  • price - Current price to check
  • upper_threshold - Upper breach threshold (from bar open)
  • lower_threshold - Lower breach threshold (from bar open)
§Returns

true if price breaches either threshold Issue #96: #[inline] for per-trade hot path

Source

pub fn set_inter_bar_features(&mut self, features: &InterBarFeatures)

Set inter-bar features from computed InterBarFeatures struct (Issue #59)

This method is called when a bar is finalized with inter-bar feature computation enabled. The features are computed from trades that occurred BEFORE the bar opened, ensuring no lookahead bias. Issue #96 Task #90: #[inline] — per-bar field assignment at finalization

Source

pub fn set_intra_bar_features(&mut self, features: &IntraBarFeatures)

Set intra-bar features from computed IntraBarFeatures struct (Issue #59)

This method is called when a bar is finalized with intra-bar feature computation enabled. The features are computed from trades WITHIN the bar, from open_time to close_time. Issue #96 Task #90: #[inline] — per-bar field assignment at finalization

Trait Implementations§

Source§

impl Clone for OpenDeviationBar

Source§

fn clone(&self) -> OpenDeviationBar

Returns a duplicate of the value. Read more
1.0.0 · Source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
Source§

impl Debug for OpenDeviationBar

Source§

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

Formats the value using the given formatter. Read more
Source§

impl Default for OpenDeviationBar

Source§

fn default() -> OpenDeviationBar

Returns the “default value” for a type. Read more
Source§

impl<'de> Deserialize<'de> for OpenDeviationBar

Source§

fn deserialize<__D>( __deserializer: __D, ) -> Result<OpenDeviationBar, <__D as Deserializer<'de>>::Error>
where __D: Deserializer<'de>,

Deserialize this value from the given Serde deserializer. Read more
Source§

impl Serialize for OpenDeviationBar

Source§

fn serialize<__S>( &self, __serializer: __S, ) -> Result<<__S as Serializer>::Ok, <__S as Serializer>::Error>
where __S: Serializer,

Serialize this value into the given Serde serializer. 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> CloneToUninit for T
where T: Clone,

Source§

unsafe fn clone_to_uninit(&self, dest: *mut u8)

🔬This is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dest. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

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.

Source§

impl<T> IntoEither for T

Source§

fn into_either(self, into_left: bool) -> Either<Self, Self>

Converts self into a Left variant of Either<Self, Self> if into_left is true. Converts self into a Right variant of Either<Self, Self> otherwise. Read more
Source§

fn into_either_with<F>(self, into_left: F) -> Either<Self, Self>
where F: FnOnce(&Self) -> bool,

Converts self into a Left variant of Either<Self, Self> if into_left(&self) returns true. Converts self into a Right variant of Either<Self, Self> otherwise. Read more
Source§

impl<T> Pointable for T

Source§

const ALIGN: usize

The alignment of pointer.
Source§

type Init = T

The type for initializers.
Source§

unsafe fn init(init: <T as Pointable>::Init) -> usize

Initializes a with the given initializer. Read more
Source§

unsafe fn deref<'a>(ptr: usize) -> &'a T

Dereferences the given pointer. Read more
Source§

unsafe fn deref_mut<'a>(ptr: usize) -> &'a mut T

Mutably dereferences the given pointer. Read more
Source§

unsafe fn drop(ptr: usize)

Drops the object pointed to by the given pointer. Read more
Source§

impl<T> ToOwned for T
where T: Clone,

Source§

type Owned = T

The resulting type after obtaining ownership.
Source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
Source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
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.
Source§

impl<T> DeserializeOwned for T
where T: for<'de> Deserialize<'de>,