barter_execution/
trade.rs

1use crate::order::id::{OrderId, StrategyId};
2use barter_instrument::{Side, asset::QuoteAsset};
3use chrono::{DateTime, Utc};
4use derive_more::{Constructor, From};
5use rust_decimal::Decimal;
6use serde::{Deserialize, Serialize};
7use smol_str::SmolStr;
8use std::fmt::{Display, Formatter};
9
10#[derive(Debug, Clone, Eq, PartialEq, Ord, PartialOrd, Hash, Deserialize, Serialize, From)]
11pub struct TradeId<T = SmolStr>(pub T);
12
13impl TradeId {
14    pub fn new<S: AsRef<str>>(id: S) -> Self {
15        Self(SmolStr::new(id))
16    }
17}
18
19#[derive(
20    Debug, Clone, Eq, PartialEq, Ord, PartialOrd, Hash, Deserialize, Serialize, Constructor,
21)]
22pub struct Trade<AssetKey, InstrumentKey> {
23    pub id: TradeId,
24    pub order_id: OrderId,
25    pub instrument: InstrumentKey,
26    pub strategy: StrategyId,
27    pub time_exchange: DateTime<Utc>,
28    pub side: Side,
29    pub price: Decimal,
30    pub quantity: Decimal,
31    pub fees: AssetFees<AssetKey>,
32}
33
34impl<AssetKey, InstrumentKey> Trade<AssetKey, InstrumentKey> {
35    pub fn value_quote(&self) -> Decimal {
36        self.price * self.quantity.abs()
37    }
38}
39
40impl<AssetKey, InstrumentKey> Display for Trade<AssetKey, InstrumentKey>
41where
42    AssetKey: Display,
43    InstrumentKey: Display,
44{
45    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
46        write!(
47            f,
48            "{{ instrument: {}, side: {}, price: {}, quantity: {}, time: {} }}",
49            self.instrument, self.side, self.price, self.quantity, self.time_exchange
50        )
51    }
52}
53
54#[derive(
55    Debug, Clone, Eq, PartialEq, Ord, PartialOrd, Hash, Deserialize, Serialize, Constructor,
56)]
57pub struct AssetFees<AssetKey> {
58    pub asset: AssetKey,
59    pub fees: Decimal,
60}
61
62impl AssetFees<QuoteAsset> {
63    pub fn quote_fees(fees: Decimal) -> Self {
64        Self {
65            asset: QuoteAsset,
66            fees,
67        }
68    }
69}
70
71impl Default for AssetFees<QuoteAsset> {
72    fn default() -> Self {
73        Self {
74            asset: QuoteAsset,
75            fees: Decimal::ZERO,
76        }
77    }
78}
79
80impl<AssetKey> Default for AssetFees<Option<AssetKey>> {
81    fn default() -> Self {
82        Self {
83            asset: None,
84            fees: Decimal::ZERO,
85        }
86    }
87}