kiteconnect_async_wasm/models/market_data/
market_depth.rs

1use serde::{Deserialize, Serialize};
2
3/// Market depth represents the order book with buy and sell orders
4#[derive(Debug, Clone, Serialize, Deserialize)]
5pub struct MarketDepthFull {
6    /// Buy orders (bids)
7    pub buy: Vec<DepthLevel>,
8
9    /// Sell orders (asks)
10    pub sell: Vec<DepthLevel>,
11}
12
13/// Individual depth level (price level in the order book)
14#[derive(Debug, Clone, Serialize, Deserialize)]
15pub struct DepthLevel {
16    /// Price level
17    pub price: f64,
18
19    /// Total quantity at this price level
20    pub quantity: u32,
21
22    /// Number of orders at this price level
23    pub orders: u32,
24}
25
26/// Level 2 market data (best bid/ask)
27#[derive(Debug, Clone, Serialize, Deserialize)]
28pub struct Level2Data {
29    /// Best bid price
30    pub bid_price: f64,
31
32    /// Best bid quantity
33    pub bid_quantity: u32,
34
35    /// Best ask price
36    pub ask_price: f64,
37
38    /// Best ask quantity
39    pub ask_quantity: u32,
40
41    /// Timestamp of the data
42    pub timestamp: chrono::DateTime<chrono::Utc>,
43}
44
45impl MarketDepthFull {
46    /// Get the best bid (highest buy price)
47    pub fn best_bid(&self) -> Option<&DepthLevel> {
48        self.buy.first()
49    }
50
51    /// Get the best ask (lowest sell price)
52    pub fn best_ask(&self) -> Option<&DepthLevel> {
53        self.sell.first()
54    }
55
56    /// Get the spread between best bid and ask
57    pub fn spread(&self) -> Option<f64> {
58        match (self.best_bid(), self.best_ask()) {
59            (Some(bid), Some(ask)) => Some(ask.price - bid.price),
60            _ => None,
61        }
62    }
63
64    /// Get the mid price (average of best bid and ask)
65    pub fn mid_price(&self) -> Option<f64> {
66        match (self.best_bid(), self.best_ask()) {
67            (Some(bid), Some(ask)) => Some((bid.price + ask.price) / 2.0),
68            _ => None,
69        }
70    }
71
72    /// Get total bid volume
73    pub fn total_bid_volume(&self) -> u64 {
74        self.buy.iter().map(|level| level.quantity as u64).sum()
75    }
76
77    /// Get total ask volume
78    pub fn total_ask_volume(&self) -> u64 {
79        self.sell.iter().map(|level| level.quantity as u64).sum()
80    }
81}
82
83impl Level2Data {
84    /// Get the spread
85    pub fn spread(&self) -> f64 {
86        self.ask_price - self.bid_price
87    }
88
89    /// Get the mid price
90    pub fn mid_price(&self) -> f64 {
91        (self.bid_price + self.ask_price) / 2.0
92    }
93
94    /// Get the spread percentage
95    pub fn spread_percentage(&self) -> f64 {
96        if self.bid_price > 0.0 {
97            (self.spread() / self.bid_price) * 100.0
98        } else {
99            0.0
100        }
101    }
102}