kraken_async_rs/wss/v2/
user_data_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
use crate::crypto::secrets::Token;
use crate::request_types::{TimeInForce, TriggerType};
use crate::response_types::{BuySell, OrderStatusV2, OrderType, PositionStatusV2};
use crate::wss::v2::market_data_messages::{
    BookSubscriptionResponse, OhlcSubscriptionResponse, TickerSubscriptionResponse,
    TradeSubscriptionResponse,
};
use crate::wss::v2::trading_messages::{ConditionalParams, FeePreference, PriceType};
use rust_decimal::Decimal;
use serde::{Deserialize, Serialize};
use serde_with::skip_serializing_none;

#[derive(Debug, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum ExecutionResponseType {
    Snapshot,
    Update,
}

#[derive(Debug, Serialize, Deserialize, PartialEq, Eq)]
pub enum MakerTaker {
    #[serde(rename = "m")]
    Maker,
    #[serde(rename = "t")]
    Taker,
}

/// Type of ledger entry in user's ledger
#[derive(Debug, Deserialize, Clone, PartialEq, Eq, Copy)]
#[serde(rename_all = "snake_case")]
pub enum LedgerEntryTypeV2 {
    Trade,
    Credit,
    Deposit,
    Withdrawal,
    Transfer,
    Margin,
    Rollover,
    Settled,
    Adjustment,
    Staking,
    Sale,
    Reserve,
    Conversion,
    Dividend,
    Reward,
    CreatorFee,
}

#[derive(Debug, Deserialize, Clone, PartialEq, Eq, Copy)]
#[serde(rename_all = "lowercase")]
pub enum LedgerEntrySubType {
    SpotFromFutures,
    SpotToFutures,
    StakingFromSpot,
    SpotFromStaking,
    StakingToSpot,
    SpotToStaking,
}

#[derive(Debug, Deserialize, Clone, PartialEq, Eq, Copy)]
#[serde(rename_all = "kebab-case")]
pub enum LedgerCategory {
    Deposit,
    Withdrawal,
    Trade,
    MarginTrade,
    MarginSettled,
    MarginConversion,
    Conversion,
    Credit,
    MarginRollover,
    StakingRewards,
    Instant,
    EquityTrade,
    Airdrop,
    EquityDividend,
    RewardBonus,
    Nft,
    BlockTrade,
}

#[derive(Debug, Serialize, Deserialize, PartialEq, Eq)]
#[serde(rename_all = "lowercase")]
pub enum WalletType {
    Spot,
    Earn,
}

#[derive(Debug, Serialize, Deserialize, PartialEq, Eq)]
#[serde(rename_all = "lowercase")]
pub enum WalletId {
    Main,
    Flex,
    Bonded,
}

#[derive(Debug, Serialize, Deserialize, PartialEq, Eq)]
#[serde(rename_all = "snake_case")]
pub enum ExecutionType {
    PendingNew,
    New,
    Trade,
    Filled,
    Canceled,
    Expired,
    Amended,
    Restated,
    Status,
}

#[derive(Debug, Serialize, Deserialize, PartialEq, Eq)]
#[serde(rename_all = "lowercase")]
pub enum TriggerStatus {
    Triggered,
    Untriggered,
}

#[derive(Debug, Serialize, Clone)]
pub struct SubscriptionRequest<T> {
    pub method: String,
    pub params: T,
    pub req_id: Option<i64>,
}

#[skip_serializing_none]
#[derive(Debug, Serialize, Clone)]
pub struct ExecutionSubscription {
    pub channel: String,
    pub token: Token,
    #[serde(rename = "snap_trades")]
    pub snapshot_trades: Option<bool>,
    #[serde(rename = "snap_orders")]
    pub snapshot_orders: Option<bool>,
    pub rate_counter: Option<bool>,
}

impl ExecutionSubscription {
    pub fn new(token: Token) -> Self {
        ExecutionSubscription {
            channel: "executions".to_string(),
            token,
            snapshot_trades: None,
            snapshot_orders: None,
            rate_counter: None,
        }
    }
}

#[derive(Debug, Deserialize, PartialEq)]
#[serde(deny_unknown_fields)]
pub struct InstrumentSubscriptionResult {
    pub snapshot: Option<bool>,
    pub warnings: Option<Vec<String>>,
}

#[derive(Debug, Deserialize, PartialEq)]
pub struct ExecutionsSubscriptionResult {
    #[serde(rename = "maxratecount")]
    pub max_rate_count: Option<i64>,
    pub snapshot: Option<bool>,
    pub warnings: Option<Vec<String>>,
}

#[derive(Debug, Deserialize, PartialEq)]
pub struct BalanceSubscriptionResult {
    pub snapshot: Option<bool>,
    pub warnings: Option<Vec<String>>,
}

#[derive(Debug, Deserialize, PartialEq)]
#[serde(tag = "channel")]
pub enum SubscriptionResult {
    #[serde(rename = "level3")]
    L3(BookSubscriptionResponse),
    #[serde(rename = "book")]
    Book(BookSubscriptionResponse),
    #[serde(rename = "ticker")]
    Ticker(TickerSubscriptionResponse),
    #[serde(rename = "ohlc")]
    Ohlc(OhlcSubscriptionResponse),
    #[serde(rename = "trade")]
    Trade(TradeSubscriptionResponse),
    #[serde(rename = "executions")]
    Execution(ExecutionsSubscriptionResult),
    #[serde(rename = "balances")]
    Balance(BalanceSubscriptionResult),
    #[serde(rename = "instrument")]
    Instrument(InstrumentSubscriptionResult),
}

#[derive(Debug, Deserialize)]
pub struct ExecutionResponse {
    pub channel: String,
    #[serde(rename = "type")]
    pub execution_response_type: ExecutionResponseType,
}

#[derive(Debug, Deserialize, PartialEq)]
pub struct Fee {
    pub asset: String,
    #[serde(rename = "qty")]
    pub quantity: Decimal,
}

#[derive(Debug, Deserialize, PartialEq)]
pub struct TriggerDescription {
    pub reference: TriggerType,
    pub price: Decimal,
    pub price_type: PriceType,
    pub actual_price: Option<Decimal>,
    pub peak_price: Option<Decimal>,
    pub last_price: Option<Decimal>,
    pub status: TriggerStatus,
    pub timestamp: Option<String>,
}

#[derive(Debug, Deserialize, PartialEq)]
pub struct ExecutionResult {
    pub amended: Option<bool>,
    #[serde(rename = "exec_type")]
    pub execution_type: ExecutionType,
    #[serde(rename = "cash_order_qty")]
    pub cash_order_quantity: Option<Decimal>,
    #[serde(rename = "cl_ord_id")]
    pub client_order_id: Option<String>,
    pub contingent: Option<ConditionalParams>,
    pub cost: Option<Decimal>,
    #[serde(rename = "exec_id")]
    pub execution_id: Option<String>,
    pub fees: Option<Vec<Fee>>,
    #[serde(rename = "liquidity_ind")]
    pub liquidity_indicator: Option<MakerTaker>,
    pub last_price: Option<Decimal>,
    #[serde(rename = "last_qty")]
    pub last_quantity: Option<Decimal>,
    #[serde(rename = "avg_price")]
    pub average_price: Option<Decimal>,
    pub reason: Option<String>,
    #[serde(rename = "cum_cost")]
    pub cumulative_cost: Option<Decimal>,
    #[serde(rename = "cum_qty")]
    pub cumulative_quantity: Option<Decimal>,
    #[serde(rename = "display_qty")]
    pub display_quantity: Option<Decimal>,
    pub effective_time: Option<String>,
    pub expire_time: Option<String>,
    pub ext_ord_id: Option<String>,
    pub ext_exec_id: Option<String>,
    #[serde(rename = "fee_ccy_pref")]
    pub fee_preference: Option<FeePreference>,
    #[serde(rename = "fee_usd_equiv")]
    pub fee_usd_equivalent: Option<Decimal>,
    pub limit_price: Option<Decimal>,
    pub limit_price_type: Option<PriceType>,
    pub liquidated: Option<bool>,
    pub margin: Option<bool>,
    pub margin_borrow: Option<bool>,
    #[serde(rename = "no_mpp")]
    pub no_market_price_protection: Option<bool>,
    #[serde(rename = "ord_ref_id")]
    pub order_ref_id: Option<i64>,
    pub order_id: String,
    #[serde(rename = "order_qty")]
    pub order_quantity: Option<Decimal>,
    pub order_type: Option<OrderType>,
    pub order_status: OrderStatusV2,
    #[serde(rename = "order_userref")]
    pub order_user_ref: Option<i64>,
    pub post_only: Option<bool>,
    pub position_status: Option<PositionStatusV2>,
    pub reduce_only: Option<bool>,
    pub sender_sub_id: Option<String>,
    pub side: Option<BuySell>,
    pub symbol: Option<String>,
    pub time_in_force: Option<TimeInForce>,
    pub timestamp: String,
    pub trade_id: Option<i64>,
    pub triggers: Option<TriggerDescription>,
}

#[skip_serializing_none]
#[derive(Debug, Serialize, Clone)]
pub struct BalancesSubscription {
    pub channel: String,
    pub token: Token,
    pub snapshot: Option<bool>,
}

impl BalancesSubscription {
    pub fn new(token: Token) -> Self {
        BalancesSubscription {
            channel: "balances".to_string(),
            token,
            snapshot: None,
        }
    }
}

#[derive(Debug, Deserialize, PartialEq)]
pub struct Wallet {
    pub balance: Decimal,
    #[serde(rename = "type")]
    pub wallet_type: WalletType,
    pub id: WalletId,
}

#[derive(Debug, Deserialize, PartialEq)]
#[serde(untagged)]
pub enum BalanceResponse {
    Update(Vec<LedgerUpdate>),
    Snapshot(Vec<Balance>),
}

#[derive(Debug, Deserialize, PartialEq)]
pub struct Balance {
    pub asset: String,
    pub balance: Decimal,
    pub wallets: Vec<Wallet>,
}

#[derive(Debug, Deserialize, PartialEq)]
pub struct LedgerUpdate {
    pub asset: String,
    pub amount: Decimal,
    pub balance: Decimal,
    pub fee: Decimal,
    pub ledger_id: String,
    pub ref_id: String,
    pub timestamp: String,
    pub asset_class: String,
    #[serde(rename = "type")]
    pub ledger_type: LedgerEntryTypeV2,
    pub sub_type: Option<LedgerEntrySubType>,
    pub category: LedgerCategory,
    pub wallet_type: WalletType,
    pub wallet_id: WalletId,
}

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

    #[test]
    fn test_deserializing_execution_trade() {
        let message = r#"{"order_id":"O7IBL5-O2V6X-EEXY4U","exec_id":"TJE7HC-DKBTI-5BFVKE","exec_type":"trade","ext_ord_id":"some-uuid","ext_exec_id":"another-uuid","trade_id":365573,"symbol":"KAR/USD","side":"buy","last_qty":105.02014889,"last_price":0.121,"liquidity_ind":"t","cost":12.70744,"order_status":"filled","order_type":"limit","timestamp":"2024-05-18T05:41:33.480251Z","fee_usd_equiv":0.05083,"fees":[{"asset":"USD","qty":0.05083}]}"#;
        let expected = ExecutionResult {
            amended: None,
            execution_type: ExecutionType::Trade,
            cash_order_quantity: None,
            contingent: None,
            cost: Some(dec!(12.70744)),
            execution_id: Some("TJE7HC-DKBTI-5BFVKE".to_string()),
            fees: Some(vec![Fee {
                asset: "USD".to_string(),
                quantity: dec!(0.05083),
            }]),
            liquidity_indicator: Some(MakerTaker::Taker),
            last_price: Some(dec!(0.121)),
            last_quantity: Some(dec!(105.02014889)),
            average_price: None,
            reason: None,
            cumulative_cost: None,
            cumulative_quantity: None,
            display_quantity: None,
            effective_time: None,
            expire_time: None,
            ext_ord_id: Some("some-uuid".to_string()),
            ext_exec_id: Some("another-uuid".to_string()),
            fee_preference: None,
            fee_usd_equivalent: Some(dec!(0.05083)),
            limit_price: None,
            limit_price_type: None,
            liquidated: None,
            margin: None,
            margin_borrow: None,
            no_market_price_protection: None,
            order_ref_id: None,
            order_id: "O7IBL5-O2V6X-EEXY4U".to_string(),
            order_quantity: None,
            order_type: Some(OrderType::Limit),
            order_status: OrderStatusV2::Filled,
            order_user_ref: None,
            post_only: None,
            position_status: None,
            reduce_only: None,
            sender_sub_id: None,
            side: Some(BuySell::Buy),
            symbol: Some("KAR/USD".to_string()),
            time_in_force: None,
            timestamp: "2024-05-18T05:41:33.480251Z".to_string(),
            trade_id: Some(365573),
            triggers: None,
            client_order_id: None,
        };
        let parsed: ExecutionResult = serde_json::from_str(message).unwrap();

        assert_eq!(expected, parsed);
    }

    #[test]
    fn test_deserializing_execution_new_update() {
        let message = r#"{"timestamp":"2024-05-18T11:00:37.240691Z","order_status":"new","exec_type":"new","order_userref":0,"order_id":"OLADEP-E5D5S-IKEHMF"}"#;
        let expected = ExecutionResult {
            amended: None,
            execution_type: ExecutionType::New,
            cash_order_quantity: None,
            contingent: None,
            cost: None,
            execution_id: None,
            fees: None,
            liquidity_indicator: None,
            last_price: None,
            last_quantity: None,
            average_price: None,
            reason: None,
            cumulative_cost: None,
            cumulative_quantity: None,
            display_quantity: None,
            effective_time: None,
            expire_time: None,
            ext_ord_id: None,
            ext_exec_id: None,
            fee_preference: None,
            fee_usd_equivalent: None,
            limit_price: None,
            limit_price_type: None,
            liquidated: None,
            margin: None,
            margin_borrow: None,
            no_market_price_protection: None,
            order_ref_id: None,
            order_id: "OLADEP-E5D5S-IKEHMF".to_string(),
            order_quantity: None,
            order_type: None,
            order_status: OrderStatusV2::New,
            order_user_ref: Some(0),
            post_only: None,
            position_status: None,
            reduce_only: None,
            sender_sub_id: None,
            side: None,
            symbol: None,
            time_in_force: None,
            timestamp: "2024-05-18T11:00:37.240691Z".to_string(),
            trade_id: None,
            triggers: None,
            client_order_id: None,
        };
        let parsed: ExecutionResult = serde_json::from_str(message).unwrap();

        assert_eq!(expected, parsed);
    }
}