use crate::common::errors::{ConnectorError, ErrorCode, ValueError};
use crate::common::ids::{AccountId, OrderId, PositionId};
use crate::open_api::client::OpenApiClient;
use crate::open_api::messages::{ProtoOaExecutionEvent, ProtoOaOrderErrorEvent};
use crate::open_api::stream::Feed;
use crate::open_api::trading::Execution;
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub struct OrderError {
pub account: AccountId,
pub code: ErrorCode,
pub order: Option<OrderId>,
pub position: Option<PositionId>,
pub description: Option<String>,
}
impl TryFrom<ProtoOaOrderErrorEvent> for OrderError {
type Error = ValueError;
fn try_from(event: ProtoOaOrderErrorEvent) -> Result<Self, Self::Error> {
Ok(Self {
account: AccountId::new(event.ctid_trader_account_id)?,
code: ErrorCode::from_wire(&event.error_code),
order: event.order_id.map(OrderId::new).transpose()?,
position: event.position_id.map(PositionId::new).transpose()?,
description: event.description,
})
}
}
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum TradeEvent {
Execution(Box<Execution>),
OrderError(OrderError),
}
impl TradeEvent {
#[must_use]
pub fn execution(&self) -> Option<&Execution> {
match self {
Self::Execution(execution) => Some(execution),
Self::OrderError(_) => None,
}
}
#[must_use]
pub fn order(&self) -> Option<OrderId> {
match self {
Self::Execution(execution) => execution.order.as_ref().map(|order| order.id),
Self::OrderError(error) => error.order,
}
}
}
#[derive(Debug)]
pub struct ExecutionStream {
feed: Feed,
account: AccountId,
}
impl ExecutionStream {
#[must_use]
pub const fn account(&self) -> AccountId {
self.account
}
pub async fn next(&mut self) -> Result<TradeEvent, ConnectorError> {
loop {
let event = self.feed.next().await?;
if let Some(execution) = event.decode::<ProtoOaExecutionEvent>() {
if execution.ctid_trader_account_id == self.account.get() {
let execution = Execution::try_from(execution)?;
return Ok(TradeEvent::Execution(Box::new(execution)));
}
} else if let Some(error) = event.decode::<ProtoOaOrderErrorEvent>() {
if error.ctid_trader_account_id == self.account.get() {
return Ok(TradeEvent::OrderError(OrderError::try_from(error)?));
}
}
}
}
}
impl OpenApiClient {
#[must_use]
pub fn executions(&self, account: AccountId) -> ExecutionStream {
ExecutionStream {
feed: Feed::new(self.connection(), account),
account,
}
}
}