use std::collections::{BTreeMap, BTreeSet};
use crate::common::decimals::{PRICE_SCALE, Price};
use crate::common::errors::{ConnectorError, ValueError};
use crate::common::ids::{AccountId, SymbolId};
use crate::common::time::Timestamp;
use crate::open_api::client::OpenApiClient;
use crate::open_api::messages::ProtoOaSpotEvent;
use crate::open_api::stream::{Feed, starts_replay};
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
pub enum QuoteSide {
Bid,
Ask,
}
pub(crate) fn wire_price(raw: u64) -> Result<Price, ValueError> {
Price::from_wire(raw, PRICE_SCALE)
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub struct Quote {
pub symbol: SymbolId,
pub bid: Option<Price>,
pub ask: Option<Price>,
pub timestamp: Option<Timestamp>,
}
impl Quote {
#[must_use]
pub const fn price(&self, side: QuoteSide) -> Option<Price> {
match side {
QuoteSide::Bid => self.bid,
QuoteSide::Ask => self.ask,
}
}
pub(crate) fn updated(
previous: Option<&Self>,
symbol: SymbolId,
spot: &ProtoOaSpotEvent,
) -> Result<Self, ValueError> {
let bid = spot.bid.map(wire_price).transpose()?;
let ask = spot.ask.map(wire_price).transpose()?;
Ok(Self {
symbol,
bid: bid.or(previous.and_then(|quote| quote.bid)),
ask: ask.or(previous.and_then(|quote| quote.ask)),
timestamp: spot.timestamp.map(Timestamp::from_millis).transpose()?,
})
}
}
#[derive(Debug)]
pub struct QuoteStream {
client: OpenApiClient,
feed: Feed,
account: AccountId,
symbols: BTreeSet<SymbolId>,
last: BTreeMap<SymbolId, Quote>,
}
impl QuoteStream {
fn new(client: &OpenApiClient, account: AccountId, symbols: &[SymbolId]) -> Self {
Self {
client: client.clone(),
feed: Feed::new(client.connection(), account),
account,
symbols: symbols.iter().copied().collect(),
last: BTreeMap::new(),
}
}
#[must_use]
pub const fn account(&self) -> AccountId {
self.account
}
pub fn symbols(&self) -> impl Iterator<Item = SymbolId> + '_ {
self.symbols.iter().copied()
}
#[must_use]
pub fn last(&self, symbol: SymbolId) -> Option<&Quote> {
self.last.get(&symbol)
}
pub async fn next(&mut self) -> Result<Quote, ConnectorError> {
loop {
let event = match self.feed.next().await {
Ok(event) => event,
Err(error) => {
if matches!(error, ConnectorError::Lagged { .. }) {
self.last.clear();
}
return Err(error);
}
};
if starts_replay(&event) {
self.last.clear();
continue;
}
let Some(spot) = event.decode::<ProtoOaSpotEvent>() else {
continue;
};
if spot.ctid_trader_account_id != self.account.get()
|| (spot.bid.is_none() && spot.ask.is_none())
{
continue;
}
let Some(symbol) = self
.symbols
.iter()
.copied()
.find(|symbol| symbol.get() == spot.symbol_id)
else {
continue;
};
let quote = Quote::updated(self.last.get(&symbol), symbol, &spot)?;
self.last.insert(symbol, quote);
return Ok(quote);
}
}
pub async fn unsubscribe(self) -> Result<(), ConnectorError> {
let symbols: Vec<SymbolId> = self.symbols.into_iter().collect();
self.client.unsubscribe_spots(self.account, &symbols).await
}
}
impl OpenApiClient {
pub async fn subscribe_quotes(
&self,
account: AccountId,
symbols: &[SymbolId],
) -> Result<QuoteStream, ConnectorError> {
let stream = QuoteStream::new(self, account, symbols);
self.subscribe_spots(account, symbols).await?;
Ok(stream)
}
#[must_use]
pub fn quotes(&self, account: AccountId, symbols: &[SymbolId]) -> QuoteStream {
QuoteStream::new(self, account, symbols)
}
}
#[cfg(test)]
mod tests {
use super::{Quote, QuoteSide};
use crate::common::errors::ValueError;
use crate::common::ids::SymbolId;
use crate::common::time::Timestamp;
use crate::open_api::messages::ProtoOaSpotEvent;
fn spot(bid: Option<u64>, ask: Option<u64>, timestamp: Option<i64>) -> ProtoOaSpotEvent {
ProtoOaSpotEvent {
ctid_trader_account_id: 7,
symbol_id: 1,
bid,
ask,
timestamp,
..ProtoOaSpotEvent::default()
}
}
fn text(quote: &Quote, side: QuoteSide) -> Option<String> {
quote.price(side).map(|price| price.to_string())
}
#[test]
fn a_side_the_event_leaves_out_keeps_its_last_known_price() {
let symbol = SymbolId::new(1).expect("symbol id");
let first =
Quote::updated(None, symbol, &spot(Some(108_512), None, Some(1_000))).expect("quote");
assert_eq!(first.symbol, symbol);
assert_eq!(text(&first, QuoteSide::Bid).as_deref(), Some("1.08512"));
assert_eq!(first.ask, None);
assert_eq!(first.timestamp.map(Timestamp::as_millis), Some(1_000));
let second =
Quote::updated(Some(&first), symbol, &spot(None, Some(108_520), None)).expect("quote");
assert_eq!(text(&second, QuoteSide::Bid).as_deref(), Some("1.08512"));
assert_eq!(text(&second, QuoteSide::Ask).as_deref(), Some("1.08520"));
assert_eq!(second.timestamp, None);
let third =
Quote::updated(Some(&second), symbol, &spot(Some(108_500), None, None)).expect("quote");
assert_eq!(text(&third, QuoteSide::Bid).as_deref(), Some("1.08500"));
assert_eq!(text(&third, QuoteSide::Ask).as_deref(), Some("1.08520"));
}
#[test]
fn values_out_of_range_are_rejected() {
let symbol = SymbolId::new(1).expect("symbol id");
assert_eq!(
Quote::updated(None, symbol, &spot(Some(1), None, Some(-1))),
Err(ValueError::OutOfRange { kind: "timestamp" })
);
assert!(Quote::updated(None, symbol, &spot(Some(u64::MAX), None, None)).is_ok());
}
}