apple-quant-algorithmic 0.4.0

Apple Quant's algorithmic library.
Documentation
use thiserror::Error;

#[derive(Debug, Error)]
pub enum OrderIdError {
	#[error("Invalid: {0:?}.")]
	Invalid(OrderId),

	#[error("Unavailable order id.")]
	Unavailable,
}

/// Numerical identifier of different types of orders assigned by the client.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub enum OrderId {
	Local(LocalOrderId),
	Remote(RemoteOrderId),
}

impl OrderId {
	pub fn err_invalid<
		T,
		E: From<OrderIdError>,
	>(
		self,
	) -> Result<T, E> {
		Err(OrderIdError::Invalid(self).into())
	}
}

impl From<LocalOrderId> for OrderId {
	fn from(
		value: LocalOrderId,
	) -> Self {
		Self::Local(value)
	}
}

impl From<RemoteOrderId> for OrderId {
	fn from(
		value: RemoteOrderId,
	) -> Self {
		Self::Remote(value)
	}
}

impl From<&LocalOrderId> for OrderId {
	fn from(
		value: &LocalOrderId,
	) -> Self {
		Self::Local(*value)
	}
}

impl From<&RemoteOrderId> for OrderId {
	fn from(
		value: &RemoteOrderId,
	) -> Self {
		Self::Remote(*value)
	}
}

#[derive(Debug)]
pub struct OrderIdGenerator {
	local_order_id: u64,
}

impl OrderIdGenerator {
	pub(crate) fn new() -> Self {
		Self { local_order_id: 0 }
	}

	pub fn next_local_order_id(
		&mut self,
	) -> LocalOrderId {
		self.local_order_id += 1;
		LocalOrderId::new_from_u64(self.local_order_id)
	}
}

/// Numerical identifier of an order that will be satisfied locally (eg. stop orders).
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct LocalOrderId(u64);

impl LocalOrderId {
	pub(crate) fn new_from_u64(
		value: u64,
	) -> Self {
		Self(value)
	}

	pub fn err_invalid<
		T,
		E: From<OrderIdError>,
	>(
		self,
	) -> Result<T, E> {
		Err(OrderIdError::Invalid(OrderId::Local(self)).into())
	}

	pub fn as_order_id(
		&self,
	) -> OrderId {
		self.into()
	}

	pub fn into_order_id(
		self,
	) -> OrderId {
		self.into()
	}
}

/// Numerical identifier of an order that will be satisfied remotely (eg. market and limit orders).
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct RemoteOrderId(u64);

impl RemoteOrderId {
	pub(crate) fn new_from_u64(
		value: u64,
	) -> Self {
		Self(value)
	}

	pub fn err_invalid<
		T,
		E: From<OrderIdError>,
	>(
		self,
	) -> Result<T, E> {
		Err(OrderIdError::Invalid(OrderId::Remote(self)).into())
	}

	pub fn as_order_id(
		&self,
	) -> OrderId {
		self.into()
	}

	pub fn into_order_id(
		self,
	) -> OrderId {
		self.into()
	}
}