1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
use exc_core::{Asset, ExchangeError};
use rust_decimal::Decimal;
use serde::Deserialize;
use serde_with::serde_as;

use crate::{
    http::error::RestError,
    types::trading::{OrderSide, OrderType, PositionSide, Status, TimeInForce},
};

use super::Data;

/// Order.
#[derive(Debug, Clone, Deserialize)]
#[serde(untagged)]
pub enum Order {
    /// Usd-Margin Futures.
    UsdMarginFutures(UsdMarginFuturesOrder),
    /// Spot.
    Spot(SpotOrder),
}

impl Order {
    /// Get order id.
    pub fn id(&self) -> i64 {
        match self {
            Self::UsdMarginFutures(order) => order.order_id,
            Self::Spot(order) => order.ack.order_id,
        }
    }

    /// Get symbol.
    pub fn symbol(&self) -> &str {
        match self {
            Self::UsdMarginFutures(order) => order.symbol.as_str(),
            Self::Spot(order) => order.ack.symbol.as_str(),
        }
    }

    /// Get client order id.
    pub fn client_id(&self) -> &str {
        tracing::debug!("get client id; {self:?}");
        match self {
            Self::UsdMarginFutures(order) => order.client_order_id.as_str(),
            Self::Spot(order) => order.ack.client_order_id(),
        }
    }

    /// Get updated time.
    pub fn updated(&self) -> Option<i64> {
        match self {
            Self::UsdMarginFutures(order) => Some(order.update_time),
            Self::Spot(order) => order.ack.transact_time,
        }
    }
}

impl TryFrom<Data> for Order {
    type Error = RestError;

    fn try_from(value: Data) -> Result<Self, Self::Error> {
        match value {
            Data::Order(order) => Ok(order),
            Data::Error(msg) => match msg.code {
                -2013 => Err(RestError::Exchange(ExchangeError::OrderNotFound)),
                _ => Err(RestError::Exchange(ExchangeError::Api(anyhow::anyhow!(
                    "{msg:?}"
                )))),
            },
            _ => Err(RestError::UnexpectedResponseType(anyhow::anyhow!(
                "{value:?}"
            ))),
        }
    }
}

/// Usd-Margin Futures Order.
#[derive(Debug, Clone, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct UsdMarginFuturesOrder {
    /// Client id.
    pub client_order_id: String,
    /// FIXME: what is this?
    pub cum_qty: Option<Decimal>,
    /// FIXME: what is this?
    pub cum_quote: Option<Decimal>,
    /// Filled size.
    pub executed_qty: Decimal,
    /// Order id.
    pub order_id: i64,
    /// Cost.
    pub avg_price: Decimal,
    /// Size.
    pub orig_qty: Decimal,
    /// Price.
    pub price: Decimal,
    /// Reduce only.
    pub reduce_only: bool,
    /// Order side.
    pub side: OrderSide,
    /// Position side.
    pub position_side: PositionSide,
    /// Status.
    pub status: Status,
    /// Stop price.
    pub stop_price: Decimal,
    /// Is close position.
    pub close_position: bool,
    /// Symbol.
    pub symbol: String,
    /// Time-In-Force.
    pub time_in_force: TimeInForce,
    /// Order type.
    #[serde(rename = "type")]
    pub order_type: OrderType,
    /// Active price.
    pub activate_price: Option<Decimal>,
    /// Price rate.
    pub price_rate: Option<Decimal>,
    /// Update timestamp.
    pub update_time: i64,
    /// Working type.
    pub working_type: String,
    /// Price protect.
    pub price_protect: bool,
}

/// Spot Ack.
#[serde_as]
#[derive(Debug, Clone, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct SpotAck {
    /// Symbol.
    pub symbol: String,
    /// Order id.
    #[serde_as(as = "serde_with::PickFirst<(_, serde_with::DisplayFromStr)>")]
    pub order_id: i64,
    /// Orignal client order id.
    orig_client_order_id: Option<String>,
    /// Client id.
    client_order_id: String,
    /// Update timestamp.
    #[serde(alias = "updateTime")]
    pub transact_time: Option<i64>,
}

impl SpotAck {
    /// Client order id.
    pub fn client_order_id(&self) -> &str {
        match &self.orig_client_order_id {
            Some(id) => id.as_str(),
            None => self.client_order_id.as_str(),
        }
    }
}

/// Spot Result.
#[derive(Debug, Clone, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct SpotResult {
    /// Price.
    pub price: Decimal,
    /// Size.
    pub orig_qty: Decimal,
    /// Filled size.
    pub executed_qty: Decimal,
    /// Filled quote size.
    pub cummulative_quote_qty: Decimal,
    /// Status.
    pub status: Status,
    /// Time-In-Force.
    pub time_in_force: TimeInForce,
    /// Order type.
    #[serde(rename = "type")]
    pub order_type: OrderType,
    /// Order side.
    pub side: OrderSide,
}

/// Spot Order.
#[derive(Debug, Clone, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct SpotOrder {
    /// Ack.
    #[serde(flatten)]
    pub ack: SpotAck,

    /// Result.
    #[serde(flatten)]
    pub result: Option<SpotResult>,

    /// Fills.
    #[serde(default)]
    pub fills: Vec<SpotFill>,
}

/// Spot fill.
#[derive(Debug, Clone, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct SpotFill {
    /// Price.
    pub price: Decimal,
    /// Size.
    pub qty: Decimal,
    /// Fee.
    pub commission: Decimal,
    /// Fee asset.
    pub commission_asset: Asset,
    /// Trade id.
    pub trade_id: i64,
}