kraken_async_rs/wss/private/
open_orders_messages.rs

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
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
//! OpenOrder message and sub-types
use crate::request_types::TimeInForce;
use crate::response_types::{BuySell, OrderFlag, OrderStatus, OrderType};
use crate::wss::kraken_wss_types::Sequence;
use rust_decimal::Decimal;
use serde::de::{MapAccess, Visitor};
use serde::{de, Deserialize, Deserializer};
use serde_tuple::Deserialize_tuple;
use serde_with::formats::CommaSeparator;
use serde_with::formats::Strict;
use serde_with::StringWithSeparator;
use serde_with::{serde_as, TimestampSecondsWithFrac};
use std::fmt::Formatter;
use time::OffsetDateTime;

const OPEN_ORDER_FIELDS: &[&str] = &[
    "order_id",
    "ref_id",
    "user_ref",
    "status",
    "open_time",
    "start_time",
    "display_volume",
    "display_volume_remain",
    "expire_time",
    "contingent",
    "order_description",
    "last_updated",
    "volume",
    "executed_volume",
    "cost",
    "fee",
    "average_price",
    "stop_price",
    "limit_price",
    "misc",
    "order_flags",
    "time_in_force",
    "cancel_reason",
    "rate_count",
];

/// Message containing a `Vec<OpenOrder>` of all open orders (or updates to them)
#[derive(Debug, Deserialize_tuple)]
pub struct OpenOrdersMessage {
    pub open_orders: Vec<OpenOrder>,
    #[serde(rename = "channelName")]
    pub channel_name: String,
    pub sequence: Sequence,
}

/// Type to deserialize to, missing the order_id field (Kraken API design)
#[serde_as]
#[derive(Debug, Deserialize, PartialEq)]
struct RawOpenOrder {
    #[serde(rename(deserialize = "refid"))]
    ref_id: Option<String>,
    #[serde(rename(deserialize = "userref"))]
    user_ref: Option<i64>,
    status: Option<OrderStatus>,
    #[serde(rename(deserialize = "opentm"))]
    open_time: Option<String>,
    #[serde(rename(deserialize = "starttm"))]
    start_time: Option<String>,
    display_volume: Option<Decimal>,
    display_volume_remain: Option<Decimal>,
    #[serde(rename(deserialize = "expiretm"))]
    expire_time: Option<String>,
    contingent: Option<OrderContingent>,
    #[serde(rename(deserialize = "descr"))]
    order_description: Option<OrderDescription>,
    #[serde(rename(deserialize = "lastupdated"))]
    last_updated: Option<String>,
    #[serde(rename(deserialize = "vol"))]
    volume: Option<Decimal>,
    #[serde(rename(deserialize = "vol_exec"))]
    executed_volume: Option<Decimal>,
    cost: Option<Decimal>,
    fee: Option<Decimal>,
    #[serde(rename(deserialize = "avg_price"))]
    average_price: Option<Decimal>,
    #[serde(rename(deserialize = "stopprice"))]
    stop_price: Option<Decimal>,
    #[serde(rename(deserialize = "limitprice"))]
    limit_price: Option<Decimal>,
    misc: Option<String>,
    #[serde(rename = "oflags")]
    #[serde_as(as = "Option<StringWithSeparator::<CommaSeparator, OrderFlag>>")]
    pub order_flags: Option<Vec<OrderFlag>>,
    #[serde(rename(deserialize = "timeinforce"))]
    time_in_force: Option<TimeInForce>,
    cancel_reason: Option<String>,
    #[serde(rename(deserialize = "ratecount"))]
    rate_count: Option<String>,
}

impl RawOpenOrder {
    pub fn into_open_order(self, order_id: String) -> OpenOrder {
        OpenOrder {
            order_id,
            ref_id: self.ref_id,
            user_ref: self.user_ref,
            status: self.status,
            open_time: self.open_time,
            start_time: self.start_time,
            display_volume: self.display_volume,
            display_volume_remain: self.display_volume_remain,
            expire_time: self.expire_time,
            contingent: self.contingent,
            order_description: self.order_description,
            last_updated: self.last_updated,
            volume: self.volume,
            executed_volume: self.executed_volume,
            cost: self.cost,
            fee: self.fee,
            average_price: self.average_price,
            stop_price: self.stop_price,
            limit_price: self.limit_price,
            misc: self.misc,
            order_flags: self.order_flags,
            time_in_force: self.time_in_force,
            cancel_reason: self.cancel_reason,
            rate_count: self.rate_count,
        }
    }
}

/// OpenOrder type containing the order's id
#[derive(Debug, PartialEq)]
pub struct OpenOrder {
    pub order_id: String,
    pub ref_id: Option<String>,
    pub user_ref: Option<i64>,
    pub status: Option<OrderStatus>,
    pub open_time: Option<String>,
    pub start_time: Option<String>,
    pub display_volume: Option<Decimal>,
    pub display_volume_remain: Option<Decimal>,
    pub expire_time: Option<String>,
    pub contingent: Option<OrderContingent>,
    pub order_description: Option<OrderDescription>,
    pub last_updated: Option<String>,
    pub volume: Option<Decimal>,
    pub executed_volume: Option<Decimal>,
    pub cost: Option<Decimal>,
    pub fee: Option<Decimal>,
    pub average_price: Option<Decimal>,
    pub stop_price: Option<Decimal>,
    pub limit_price: Option<Decimal>,
    pub misc: Option<String>,
    pub order_flags: Option<Vec<OrderFlag>>,
    pub time_in_force: Option<TimeInForce>,
    pub cancel_reason: Option<String>,
    pub rate_count: Option<String>,
}

impl<'de> Deserialize<'de> for OpenOrder {
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: Deserializer<'de>,
    {
        struct OpenOrderVisitor;

        impl<'de> Visitor<'de> for OpenOrderVisitor {
            type Value = OpenOrder;

            fn expecting(&self, formatter: &mut Formatter) -> std::fmt::Result {
                formatter.write_str("OpenOrder")
            }

            fn visit_map<A>(self, mut map: A) -> Result<Self::Value, A::Error>
            where
                A: MapAccess<'de>,
            {
                if let Some((trade_id, raw_order)) = map.next_entry::<String, RawOpenOrder>()? {
                    Ok(raw_order.into_open_order(trade_id))
                } else {
                    Err(de::Error::invalid_length(0, &self))
                }
            }
        }

        deserializer.deserialize_struct("OpenOrder", OPEN_ORDER_FIELDS, OpenOrderVisitor)
    }
}

/// Contingent leg of an order, e.g. a stop-limit or take-profit
#[serde_as]
#[derive(Debug, Deserialize, PartialEq)]
pub struct OrderContingent {
    #[serde(rename(deserialize = "ordertype"))]
    pub order_type: OrderType,
    pub price: Decimal,
    #[serde(rename(deserialize = "price2"))]
    pub price_2: Decimal,
    #[serde(rename = "oflags")]
    #[serde_as(as = "StringWithSeparator::<CommaSeparator, OrderFlag>")]
    pub order_flags: Vec<OrderFlag>,
}

/// Details of an individual order
#[derive(Debug, Deserialize, PartialEq, Clone)]
pub struct OrderDescription {
    pub pair: String,
    pub position: Option<String>,
    #[serde(rename(deserialize = "type"))]
    pub side: BuySell,
    #[serde(rename(deserialize = "ordertype"))]
    pub order_type: OrderType,
    pub price: Decimal,
    #[serde(rename(deserialize = "price2"))]
    pub price_2: Option<Decimal>,
    pub leverage: Option<Decimal>,
    pub order: String,
    pub close: Option<String>,
}

/// Message for a status change of an order
#[derive(Debug, Deserialize_tuple, PartialEq)]
pub struct OrderStatusMessage {
    pub status_changes: Vec<OrderStatusChange>,
    pub event: String,
    pub sequence: Sequence,
}

/// Order status change to deserialize to, missing order_id due to Kraken API design
#[serde_with::serde_as]
#[derive(Debug, Deserialize, PartialEq)]
struct RawOpenOrderStatusChange {
    status: String,
    #[serde(rename = "userref")]
    user_ref: Option<i64>,
    #[serde(rename = "lastupdated")]
    #[serde_as(as = "Option<TimestampSecondsWithFrac<String, Strict>>")]
    last_updated: Option<OffsetDateTime>,
    #[serde(rename = "vol_exec")]
    volume_executed: Option<Decimal>,
    cost: Option<Decimal>,
    fee: Option<Decimal>,
    #[serde(rename = "avg_price")]
    average_price: Option<Decimal>,
    cancel_reason: Option<String>,
}

impl RawOpenOrderStatusChange {
    fn into_open_order_status_change(self, order_id: String) -> OrderStatusChange {
        OrderStatusChange {
            order_id,
            status: self.status,
            user_ref: self.user_ref,
            last_updated: self.last_updated,
            volume_executed: self.volume_executed,
            cost: self.cost,
            fee: self.fee,
            average_price: self.average_price,
            cancel_reason: self.cancel_reason,
        }
    }
}

/// Order status change containing the order's id and changes to status, fees, or volume executed
#[derive(Debug, PartialEq)]
pub struct OrderStatusChange {
    pub order_id: String,
    pub status: String,
    pub user_ref: Option<i64>,
    pub last_updated: Option<OffsetDateTime>,
    pub volume_executed: Option<Decimal>,
    pub cost: Option<Decimal>,
    pub fee: Option<Decimal>,
    pub average_price: Option<Decimal>,
    pub cancel_reason: Option<String>,
}

impl<'de> Deserialize<'de> for OrderStatusChange {
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: Deserializer<'de>,
    {
        struct OrderStatusChangeVisitor;

        impl<'de> Visitor<'de> for OrderStatusChangeVisitor {
            type Value = OrderStatusChange;

            fn expecting(&self, formatter: &mut Formatter) -> std::fmt::Result {
                formatter.write_str("OrderStatusChange")
            }

            fn visit_map<A>(self, mut map: A) -> Result<Self::Value, A::Error>
            where
                A: MapAccess<'de>,
            {
                if let Some((order_id, raw_status)) =
                    map.next_entry::<String, RawOpenOrderStatusChange>()?
                {
                    Ok(raw_status.into_open_order_status_change(order_id))
                } else {
                    Err(de::Error::invalid_length(0, &self))
                }
            }
        }

        const ORDER_STATUS_CHANGE_FIELDS: &[&str] = &["order_id", "status", "user_ref"];

        deserializer.deserialize_struct(
            "OpenOrderStatusChange",
            ORDER_STATUS_CHANGE_FIELDS,
            OrderStatusChangeVisitor,
        )
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use rust_decimal_macros::dec;
    use time::macros::datetime;

    const OPEN_ORDER: &str = "{\
    \"OSJN7R-5G4OK-T2KYTD\":{\"avg_price\":\"0.00000000\",\"cost\":\"0.00000000\",\"descr\":\
    {\"close\":null,\"leverage\":null,\"order\":\"sell 106.53408600 USDC/USD @ limit 1.00150000\",\
    \"ordertype\":\"limit\",\"pair\":\"USDC/USD\",\"price\":\"1.00150000\",\"price2\":\"0.00000000\",\
    \"type\":\"sell\"},\"expiretm\":null,\"fee\":\"0.00000000\",\"limitprice\":\"0.00000000\",\
    \"misc\":\"\",\"oflags\":\"fcib,post\",\"opentm\":\"1697801466.817843\",\"refid\":null,\
    \"starttm\":null,\"status\":\"open\",\"stopprice\":\"0.00000000\",\"timeinforce\":\"GTC\",\
    \"userref\":0,\"vol\":\"106.53408600\",\"vol_exec\":\"0.00000000\"}}";

    const OPEN_CONTINGENT_ORDER: &str = "{\
    \"OBA7Z7-XQVOQ-3NZRDS\":{\"avg_price\":\"0.00000000\",\"cost\":\"0.00000000\",\"descr\":\
    {\"close\":null,\"leverage\":null,\"order\":\
    \"buy 5.00000000 USDC/USD @ take-profit-limit 0.99000000, limit 0.99100000\",\"ordertype\":\
    \"take-profit-limit\",\"pair\":\"USDC/USD\",\"price\":\"0.99000000\",\"price2\":\"0.99100000\",\
    \"type\":\"buy\"},\"expiretm\":null,\"fee\":\"0.00000000\",\"limitprice\":\"0.00000000\",\
    \"misc\":\"\",\"oflags\":\"fciq\",\"opentm\":\"1698761179.336974\",\"refid\":null,\
    \"starttm\":null,\"status\":\"pending\",\"stopprice\":\"0.00000000\",\"timeinforce\":\"GTC\",\
    \"trigger\":\"index\",\"userref\":0,\"vol\":\"5.00000000\",\"vol_exec\":\"0.00000000\"}}";

    const STATUS_CHANGE: &str = r#"{"OBA7Z7-XQVOQ-3NZRDS":{"status":"open","userref":0}}"#;

    const STATUS_CHANGE_USER_CANCEL: &str = "{\"OBA7Z7-XQVOQ-3NZRDS\":{\"lastupdated\":\
    \"1698762486.391070\",\"status\":\"canceled\",\"vol_exec\":\"0.00000000\",\"cost\":\
    \"0.00000000\",\"fee\":\"0.00000000\",\"avg_price\":\"0.00000000\",\"userref\":0,\
    \"cancel_reason\":\"User requested\"}}";

    #[test]
    fn test_deserialize_open_order() {
        let expected_open_order = OpenOrder {
            order_id: "OSJN7R-5G4OK-T2KYTD".to_string(),
            ref_id: None,
            user_ref: Some(0),
            status: Some(OrderStatus::Open),
            open_time: Some("1697801466.817843".to_string()),
            start_time: None,
            display_volume: None,
            display_volume_remain: None,
            expire_time: None,
            contingent: None,
            order_description: Some(OrderDescription {
                pair: "USDC/USD".to_string(),
                position: None,
                side: BuySell::Sell,
                order_type: OrderType::Limit,
                price: dec!(1.0015),
                price_2: Some(dec!(0)),
                leverage: None,
                order: "sell 106.53408600 USDC/USD @ limit 1.00150000".to_string(),
                close: None,
            }),
            last_updated: None,
            volume: Some(dec!(106.53408600)),
            executed_volume: Some(dec!(0)),
            cost: Some(dec!(0)),
            fee: Some(dec!(0)),
            average_price: Some(dec!(0)),
            stop_price: Some(dec!(0)),
            limit_price: Some(dec!(0)),
            misc: Some("".to_string()),
            order_flags: Some(vec![OrderFlag::FeesInBase, OrderFlag::Post]),
            time_in_force: Some(TimeInForce::GTC),
            cancel_reason: None,
            rate_count: None,
        };

        let open_order: OpenOrder = serde_json::from_str(OPEN_ORDER).unwrap();

        assert_eq!(expected_open_order, open_order);
    }

    #[test]
    fn test_deserialize_open_contingent_order() {
        let expected_open_contingent_order = OpenOrder {
            order_id: "OBA7Z7-XQVOQ-3NZRDS".to_string(),
            ref_id: None,
            user_ref: Some(0),
            status: Some(OrderStatus::Pending),
            open_time: Some("1698761179.336974".to_string()),
            start_time: None,
            display_volume: None,
            display_volume_remain: None,
            expire_time: None,
            contingent: None,
            order_description: Some(OrderDescription {
                pair: "USDC/USD".to_string(),
                position: None,
                side: BuySell::Buy,
                order_type: OrderType::TakeProfitLimit,
                price: dec!(0.990),
                price_2: Some(dec!(0.991)),
                leverage: None,
                order: "buy 5.00000000 USDC/USD @ take-profit-limit 0.99000000, limit 0.99100000"
                    .to_string(),
                close: None,
            }),
            last_updated: None,
            volume: Some(dec!(5)),
            executed_volume: Some(dec!(0)),
            cost: Some(dec!(0)),
            fee: Some(dec!(0)),
            average_price: Some(dec!(0)),
            stop_price: Some(dec!(0)),
            limit_price: Some(dec!(0)),
            misc: Some("".to_string()),
            order_flags: Some(vec![OrderFlag::FeesInQuote]),
            time_in_force: Some(TimeInForce::GTC),
            cancel_reason: None,
            rate_count: None,
        };

        let open_order: OpenOrder = serde_json::from_str(OPEN_CONTINGENT_ORDER).unwrap();

        assert_eq!(expected_open_contingent_order, open_order);
    }

    #[test]
    fn test_deserialize_status_change() {
        let expected_open_order_status_change = OrderStatusChange {
            order_id: "OBA7Z7-XQVOQ-3NZRDS".to_string(),
            user_ref: Some(0),
            last_updated: None,
            volume_executed: None,
            cost: None,
            fee: None,
            average_price: None,
            status: "open".to_string(),
            cancel_reason: None,
        };

        let status_change: OrderStatusChange = serde_json::from_str(STATUS_CHANGE).unwrap();

        assert_eq!(expected_open_order_status_change, status_change);
    }

    #[test]
    fn test_deserialize_user_cancel_status_change() {
        let expected_open_order_status_change = OrderStatusChange {
            order_id: "OBA7Z7-XQVOQ-3NZRDS".to_string(),
            user_ref: Some(0),
            last_updated: Some(datetime!(2023-10-31 14:28:06.39107 UTC)),
            volume_executed: Some(dec!(0)),
            cost: Some(dec!(0)),
            fee: Some(dec!(0)),
            average_price: Some(dec!(0)),
            status: "canceled".to_string(),
            cancel_reason: Some("User requested".to_string()),
        };

        let status_change: OrderStatusChange =
            serde_json::from_str(STATUS_CHANGE_USER_CANCEL).unwrap();

        assert_eq!(expected_open_order_status_change, status_change);
    }
}