1use std::collections::BTreeMap;
32
33use tokio::sync::broadcast;
34use tokio::sync::broadcast::error::RecvError;
35use tokio::time::timeout;
36
37use crate::common::decimals::{Price, Volume};
38use crate::common::errors::{ConnectorError, FixError, TransportError};
39use crate::common::ids::SymbolId;
40use crate::fix::client::FixClient;
41use crate::fix::messages::{
42 BookSide, BookUpdate, MarketDataRequest, MarketDataSnapshot, MarketDepth, Message,
43};
44use crate::fix::session::Event;
45
46const REQUEST_PREFIX: &str = "md";
47
48#[derive(Debug, Clone, Copy, PartialEq, Eq)]
50pub struct SpotQuote {
51 pub symbol: SymbolId,
53 pub bid: Option<Price>,
55 pub offer: Option<Price>,
57}
58
59#[derive(Debug, Clone, PartialEq, Eq)]
61pub struct BookEntry {
62 pub id: String,
64 pub side: BookSide,
66 pub price: Price,
68 pub size: Option<Volume>,
70}
71
72#[derive(Debug, Clone, PartialEq, Eq)]
74pub struct Book {
75 symbol: SymbolId,
76 entries: BTreeMap<String, BookEntry>,
77}
78
79impl Book {
80 #[must_use]
82 pub const fn new(symbol: SymbolId) -> Self {
83 Self {
84 symbol,
85 entries: BTreeMap::new(),
86 }
87 }
88
89 #[must_use]
91 pub const fn symbol(&self) -> SymbolId {
92 self.symbol
93 }
94
95 #[must_use]
97 pub fn len(&self) -> usize {
98 self.entries.len()
99 }
100
101 #[must_use]
103 pub fn is_empty(&self) -> bool {
104 self.entries.is_empty()
105 }
106
107 #[must_use]
109 pub fn bids(&self) -> Vec<&BookEntry> {
110 let mut bids = self.side(BookSide::Bid);
111 bids.sort_by(|a, b| b.price.cmp(&a.price));
112 bids
113 }
114
115 #[must_use]
117 pub fn offers(&self) -> Vec<&BookEntry> {
118 let mut offers = self.side(BookSide::Offer);
119 offers.sort_by(|a, b| a.price.cmp(&b.price));
120 offers
121 }
122
123 fn side(&self, side: BookSide) -> Vec<&BookEntry> {
124 self.entries
125 .values()
126 .filter(|entry| entry.side == side)
127 .collect()
128 }
129
130 pub fn replace(&mut self, snapshot: &MarketDataSnapshot) {
133 if snapshot.symbol != self.symbol {
134 return;
135 }
136 self.entries.clear();
137 for (position, entry) in snapshot.entries.iter().enumerate() {
138 let id = entry
139 .id
140 .clone()
141 .unwrap_or_else(|| format!("{}{position}", entry.side.as_str()));
142 self.entries.insert(
143 id.clone(),
144 BookEntry {
145 id,
146 side: entry.side,
147 price: entry.price,
148 size: entry.size,
149 },
150 );
151 }
152 }
153
154 pub fn apply(&mut self, update: &BookUpdate) {
156 match update {
157 BookUpdate::New {
158 side,
159 id,
160 symbol,
161 price,
162 size,
163 } if *symbol == self.symbol => {
164 self.entries.insert(
165 id.clone(),
166 BookEntry {
167 id: id.clone(),
168 side: *side,
169 price: *price,
170 size: *size,
171 },
172 );
173 }
174 BookUpdate::Delete { id, symbol } if *symbol == self.symbol => {
175 self.entries.remove(id);
176 }
177 _ => {}
178 }
179 }
180}
181
182enum Step {
183 Snapshot(MarketDataSnapshot),
184 Changes(Vec<BookUpdate>),
185}
186
187#[derive(Debug)]
188struct Feed {
189 client: FixClient,
190 events: broadcast::Receiver<Event>,
191 md_req_id: String,
192 symbol: SymbolId,
193 depth: MarketDepth,
194 seq: u64,
195 ended: bool,
196}
197
198impl Feed {
199 fn request(&self, subscribe: bool) -> Message {
200 MarketDataRequest {
201 md_req_id: self.md_req_id.clone(),
202 subscribe,
203 depth: self.depth,
204 symbols: vec![self.symbol],
205 sides: vec![BookSide::Bid, BookSide::Offer],
206 }
207 .into()
208 }
209
210 async fn open(
211 client: &FixClient,
212 symbol: SymbolId,
213 depth: MarketDepth,
214 ) -> Result<Self, ConnectorError> {
215 let mut feed = Self {
216 client: client.clone(),
217 events: client.events(),
218 md_req_id: client.next_id(REQUEST_PREFIX),
219 symbol,
220 depth,
221 seq: 0,
222 ended: false,
223 };
224 feed.seq = client.send(feed.request(true)).await?;
225 Ok(feed)
226 }
227
228 fn mine(&self, md_req_id: Option<&str>) -> bool {
229 md_req_id == Some(self.md_req_id.as_str())
230 }
231
232 async fn step(&mut self) -> Result<Step, ConnectorError> {
233 if self.ended {
234 return Err(ConnectorError::Closed);
235 }
236 loop {
237 let inbound = match self.events.recv().await {
238 Ok(Event::Message(inbound)) => inbound,
239 Ok(Event::Disconnected(error)) => return Err(error.into()),
240 Ok(Event::LoggedOut { .. } | Event::Ended) | Err(RecvError::Closed) => {
241 self.ended = true;
242 return Err(TransportError::Closed.into());
243 }
244 Ok(Event::Reconnected { .. }) => {
245 self.seq = self.client.send(self.request(true)).await?;
246 continue;
247 }
248 Ok(_) => continue,
249 Err(RecvError::Lagged(skipped)) => {
250 return Err(ConnectorError::Lagged { skipped });
251 }
252 };
253 match inbound.message {
254 Message::MarketDataSnapshot(snapshot)
255 if self.mine(snapshot.md_req_id.as_deref())
256 && snapshot.symbol == self.symbol =>
257 {
258 return Ok(Step::Snapshot(snapshot));
259 }
260 Message::MarketDataIncremental(changes)
261 if self.mine(changes.md_req_id.as_deref()) =>
262 {
263 return Ok(Step::Changes(changes.entries));
264 }
265 Message::MarketDataReject(reject) if reject.md_req_id == self.md_req_id => {
266 return Err(FixError::MarketDataRejected {
267 reason: reject.reason,
268 text: reject.text,
269 }
270 .into());
271 }
272 Message::Reject(reject) if reject.ref_seq_num == self.seq => {
273 return Err(FixError::Rejected {
274 ref_seq_num: self.seq,
275 tag: reject.ref_tag_id,
276 reason: reject.reason,
277 text: reject.text,
278 }
279 .into());
280 }
281 Message::BusinessReject(reject)
282 if reject.ref_seq_num == Some(self.seq)
283 || reject.ref_id.as_deref() == Some(self.md_req_id.as_str()) =>
284 {
285 return Err(FixError::BusinessRejected {
286 ref_id: reject.ref_id,
287 reason: reject.reason,
288 text: reject.text,
289 }
290 .into());
291 }
292 _ => {}
293 }
294 }
295 }
296
297 async fn first(&mut self) -> Result<Step, ConnectorError> {
298 let limit = self.client.timeout();
299 timeout(limit, self.step())
300 .await
301 .map_err(|_| ConnectorError::Timeout(limit))?
302 }
303
304 async fn close(&self) -> Result<(), ConnectorError> {
305 self.client.send(self.request(false)).await.map(|_| ())
306 }
307}
308
309#[derive(Debug)]
311pub struct SpotStream {
312 feed: Feed,
313 last: SpotQuote,
314}
315
316impl SpotStream {
317 #[must_use]
319 pub const fn symbol(&self) -> SymbolId {
320 self.feed.symbol
321 }
322
323 #[must_use]
325 pub const fn last(&self) -> SpotQuote {
326 self.last
327 }
328
329 fn take(&mut self, step: Step) -> Option<SpotQuote> {
330 let Step::Snapshot(snapshot) = step else {
331 return None;
332 };
333 let best = |side: BookSide| {
334 snapshot
335 .entries
336 .iter()
337 .find(|entry| entry.side == side)
338 .map(|entry| entry.price)
339 };
340 self.last = SpotQuote {
341 symbol: snapshot.symbol,
342 bid: best(BookSide::Bid),
343 offer: best(BookSide::Offer),
344 };
345 Some(self.last)
346 }
347
348 pub async fn next(&mut self) -> Result<SpotQuote, ConnectorError> {
361 loop {
362 let step = self.feed.step().await?;
363 if let Some(quote) = self.take(step) {
364 return Ok(quote);
365 }
366 }
367 }
368
369 pub async fn unsubscribe(self) -> Result<(), ConnectorError> {
376 self.feed.close().await
377 }
378}
379
380#[derive(Debug)]
382pub struct DepthStream {
383 feed: Feed,
384 book: Book,
385}
386
387impl DepthStream {
388 #[must_use]
390 pub const fn symbol(&self) -> SymbolId {
391 self.feed.symbol
392 }
393
394 #[must_use]
396 pub const fn book(&self) -> &Book {
397 &self.book
398 }
399
400 fn take(&mut self, step: &Step) {
401 match step {
402 Step::Snapshot(snapshot) => self.book.replace(snapshot),
403 Step::Changes(changes) => {
404 for change in changes {
405 self.book.apply(change);
406 }
407 }
408 }
409 }
410
411 pub async fn next(&mut self) -> Result<&Book, ConnectorError> {
425 let step = self.feed.step().await?;
426 self.take(&step);
427 Ok(&self.book)
428 }
429
430 pub async fn unsubscribe(self) -> Result<(), ConnectorError> {
437 self.feed.close().await
438 }
439}
440
441impl FixClient {
442 pub async fn subscribe_spot(&self, symbol: SymbolId) -> Result<SpotStream, ConnectorError> {
450 let mut stream = SpotStream {
451 feed: Feed::open(self, symbol, MarketDepth::Spot).await?,
452 last: SpotQuote {
453 symbol,
454 bid: None,
455 offer: None,
456 },
457 };
458 loop {
459 let step = stream.feed.first().await?;
460 if stream.take(step).is_some() {
461 return Ok(stream);
462 }
463 }
464 }
465
466 pub async fn subscribe_depth(&self, symbol: SymbolId) -> Result<DepthStream, ConnectorError> {
473 let mut stream = DepthStream {
474 feed: Feed::open(self, symbol, MarketDepth::Full).await?,
475 book: Book::new(symbol),
476 };
477 let step = stream.feed.first().await?;
478 stream.take(&step);
479 Ok(stream)
480 }
481}