ndaxrs 0.1.0

Rust client library for the NDAX cryptocurrency exchange API
Documentation
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
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
// Copyright (C) 2026 ndaxrs Art Morozov
// SPDX-License-Identifier: GPL-3.0-only

//! Account-related message types for the NDAX API.
//!
//! This module contains request and response structures for account
//! information, positions, and account event subscriptions including position
//! updates, order state changes, and trade events.

use rust_decimal::Decimal;
use serde::{Deserialize, Serialize};

use super::{OrderState, OrderType, Side};

/// Request structure for GetAccountInfo.
///
/// Retrieves detailed information about a specific account.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct GetAccountInfoRequest {
  /// The Order Management System ID (usually 1)
  pub oms_id:     u64,
  /// The account ID to query
  pub account_id: u64,
}

/// Response structure for GetAccountInfo.
///
/// Contains detailed information about an account.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "PascalCase")]
pub struct AccountInfo {
  /// The Order Management System ID
  #[serde(rename = "OMSID")]
  pub omsid:               u64,
  /// The account ID
  pub account_id:          u64,
  /// Non-unique name assigned by the user
  pub account_name:        String,
  /// Unique user-assigned handle
  pub account_handle:      String,
  /// Trading firm identifier
  pub firm_id:             String,
  /// Trading firm name
  pub firm_name:           String,
  /// Account type (0=Asset, 1=Liability, 2=ProfitLoss)
  pub account_type:        i32,
  /// Fee group identifier
  #[serde(rename = "FeeGroupID")]
  pub fee_group_id:        i64,
  /// Parent account ID (reserved for future use)
  #[serde(rename = "ParentID")]
  pub parent_id:           i64,
  /// Risk type (0=Unknown, 1=Normal, 2=NoRiskCheck, 3=NoTrading)
  pub risk_type:           i32,
  /// Verification level for deposit/withdrawal limits
  pub verification_level:  i32,
  /// Fee product type (0=BaseProduct, 1=SingleProduct)
  pub fee_product_type:    i32,
  /// Preferred fee product ID
  pub fee_product:         i64,
  /// Referrer ID for marketing purposes
  pub referer_id:          i64,
  /// Supported venue IDs
  #[serde(default)]
  pub supported_venue_ids: Vec<i64>,
}

/// Request structure for GetAccountPositions.
///
/// Retrieves a list of positions (balances) for a specific account.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "PascalCase")]
pub struct GetAccountPositionsRequest {
  /// The account ID to query
  pub account_id: u64,
  /// The Order Management System ID (usually 1)
  #[serde(rename = "OMSId")]
  pub oms_id:     u64,
}

/// Response structure representing a single account position.
///
/// Contains balance information for a specific product in an account.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "PascalCase")]
pub struct AccountPosition {
  /// The Order Management System ID
  #[serde(rename = "OMSId")]
  pub oms_id:              u64,
  /// The account ID
  pub account_id:          u64,
  /// Product symbol (e.g., "BTC", "CAD")
  pub product_symbol:      String,
  /// Product ID
  pub product_id:          u64,
  /// Total balance amount
  pub amount:              Decimal,
  /// Amount on hold (available = amount - hold)
  pub hold:                Decimal,
  /// Total pending deposits
  pub pending_deposits:    Decimal,
  /// Total pending withdrawals
  pub pending_withdraws:   Decimal,
  /// Total deposits in current day (UTC)
  pub total_day_deposits:  Decimal,
  /// Total withdrawals in current day (UTC)
  pub total_day_withdraws: Decimal,
}

/// Request structure for SubscribeAccountEvents.
///
/// Subscribes to real-time account event notifications.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "PascalCase")]
pub struct SubscribeAccountEventsRequest {
  /// The account ID to subscribe to
  pub account_id: u64,
  /// The Order Management System ID (usually 1)
  #[serde(rename = "OMSId")]
  pub oms_id:     u64,
}

/// Response structure for SubscribeAccountEvents.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "PascalCase")]
pub struct SubscribeAccountEventsResponse {
  /// Whether the subscription was successful
  #[serde(alias = "Subscribe")]
  pub subscribed: bool,
}

/// Account position event received via WebSocket subscription.
///
/// Sent when the balance in your account changes.
/// Same structure as AccountPosition.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "PascalCase")]
pub struct AccountPositionEvent {
  /// The Order Management System ID
  #[serde(rename = "OMSId")]
  pub oms_id:              u64,
  /// The account ID
  pub account_id:          u64,
  /// Product symbol (e.g., "BTC", "CAD")
  pub product_symbol:      String,
  /// Product ID
  pub product_id:          u64,
  /// Total balance amount
  pub amount:              Decimal,
  /// Amount on hold (available = amount - hold)
  pub hold:                Decimal,
  /// Total pending deposits
  pub pending_deposits:    Decimal,
  /// Total pending withdrawals
  pub pending_withdraws:   Decimal,
  /// Total deposits in current day (UTC)
  pub total_day_deposits:  Decimal,
  /// Total withdrawals in current day (UTC)
  pub total_day_withdraws: Decimal,
}

/// Order state event received via WebSocket subscription.
///
/// Sent when the status changes for an order associated with your account.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "PascalCase")]
pub struct OrderStateEvent {
  /// Order side (Buy, Sell, Short)
  pub side:              Side,
  /// Server-assigned order ID
  pub order_id:          u64,
  /// Order price
  pub price:             Decimal,
  /// Remaining quantity
  pub quantity:          Decimal,
  /// Instrument ID
  pub instrument:        u64,
  /// Account ID
  pub account:           u64,
  /// Order type
  pub order_type:        OrderType,
  /// Client-assigned order ID
  pub client_order_id:   u64,
  /// Current state of the order
  pub order_state:       OrderState,
  /// Timestamp when order was received (POSIX or ISO format)
  pub receive_time:      serde_json::Value,
  /// Original quantity
  pub orig_quantity:     Decimal,
  /// Total executed quantity
  pub quantity_executed: Decimal,
  /// Average executed price
  pub avg_price:         Decimal,
  /// Reason for the order state change
  pub change_reason:     serde_json::Value,
}

/// Order trade event received via WebSocket subscription.
///
/// Sent when an order associated with your account results in a trade.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "PascalCase")]
pub struct OrderTradeEvent {
  /// The Order Management System ID
  #[serde(rename = "OMSId")]
  pub oms_id:               u64,
  /// Trade ID
  pub trade_id:             u64,
  /// Order ID
  pub order_id:             u64,
  /// Account ID
  pub account_id:           u64,
  /// Client-assigned order ID
  pub client_order_id:      u64,
  /// Instrument ID
  pub instrument_id:        u64,
  /// Trade side (Buy, Sell, Short)
  pub side:                 Side,
  /// Trade quantity
  pub quantity:             Decimal,
  /// Trade price
  pub price:                Decimal,
  /// Trade value (quantity * price)
  pub value:                Decimal,
  /// Trade timestamp
  pub trade_time:           serde_json::Value,
  /// Counterparty account ID (usually the clearing account)
  #[serde(default)]
  pub contra_acct_id:       Option<u64>,
  /// Order trade revision number
  #[serde(default)]
  pub order_trade_revision: Option<u64>,
  /// Price direction (Uptick, Downtick, NoChange)
  #[serde(default)]
  pub direction:            Option<String>,
  /// Trade fee
  #[serde(default)]
  pub fee:                  Option<Decimal>,
  /// Fee product ID
  #[serde(default)]
  pub fee_product_id:       Option<u64>,
}

/// New order rejection event received via WebSocket subscription.
///
/// Sent when an order associated with your account is rejected.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "PascalCase")]
pub struct NewOrderRejectEvent {
  /// The Order Management System ID
  #[serde(rename = "OMSId")]
  pub oms_id:          u64,
  /// Account ID
  pub account_id:      u64,
  /// Client-assigned order ID
  pub client_order_id: u64,
  /// Status (always "Rejected")
  pub status:          String,
  /// Reason for rejection
  pub reject_reason:   String,
}

/// Cancel order rejection event received via WebSocket subscription.
///
/// Sent when a cancel request is rejected.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "PascalCase")]
pub struct CancelOrderRejectEvent {
  /// The Order Management System ID
  #[serde(rename = "OMSId")]
  pub oms_id:         u64,
  /// Account ID
  pub account_id:     u64,
  /// Order ID from the cancel request
  pub order_id:       u64,
  /// Order revision number
  pub order_revision: u64,
  /// Order type
  pub order_type:     OrderType,
  /// Instrument ID
  pub instrument_id:  u64,
  /// Status (always "Rejected")
  pub status:         String,
  /// Reason for rejection
  pub reject_reason:  String,
}

/// Enum to identify account event types from frame names.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum AccountEventType {
  /// Position balance update
  Position,
  /// Order state change
  OrderState,
  /// Order trade execution
  OrderTrade,
  /// New order rejection
  NewOrderReject,
  /// Cancel order rejection
  CancelOrderReject,
}

impl AccountEventType {
  /// Create an AccountEventType from a frame name string.
  ///
  /// Returns `None` if the frame name is not recognized as an account event.
  pub fn from_name(name: &str) -> Option<Self> {
    match name {
      "AccountPositionEvent" => Some(AccountEventType::Position),
      "OrderStateEvent" => Some(AccountEventType::OrderState),
      "OrderTradeEvent" => Some(AccountEventType::OrderTrade),
      "NewOrderRejectEvent" => Some(AccountEventType::NewOrderReject),
      "CancelOrderRejectEvent" => Some(AccountEventType::CancelOrderReject),
      _ => None,
    }
  }
}

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

  #[test]
  fn test_account_position_deserialize() {
    let json = r#"[
            {"OMSId":1,"AccountId":12345,"ProductSymbol":"BTC","ProductId":1,"Amount":1.5,"Hold":0.1,"PendingDeposits":0,"PendingWithdraws":0,"TotalDayDeposits":0,"TotalDayWithdraws":0},
            {"OMSId":1,"AccountId":12345,"ProductSymbol":"CAD","ProductId":2,"Amount":50000.00,"Hold":1000.00,"PendingDeposits":500,"PendingWithdraws":0,"TotalDayDeposits":100,"TotalDayWithdraws":50}
        ]"#;

    let positions: Vec<AccountPosition> = serde_json::from_str(json).unwrap();
    assert_eq!(positions.len(), 2);

    assert_eq!(positions[0].oms_id, 1);
    assert_eq!(positions[0].account_id, 12345);
    assert_eq!(positions[0].product_symbol, "BTC");
    assert_eq!(positions[0].product_id, 1);
    assert_eq!(positions[0].amount, Decimal::new(15, 1));
    assert_eq!(positions[0].hold, Decimal::new(1, 1));

    assert_eq!(positions[1].product_symbol, "CAD");
    assert_eq!(positions[1].amount, Decimal::new(5000000, 2));
    assert_eq!(positions[1].hold, Decimal::new(100000, 2));
  }

  #[test]
  fn test_order_state_event_deserialize() {
    let json = r#"{
            "Side":0,
            "OrderId":98765,
            "Price":50000.00,
            "Quantity":0.001,
            "Instrument":1,
            "Account":12345,
            "OrderType":2,
            "ClientOrderId":0,
            "OrderState":0,
            "ReceiveTime":"2024-01-15T10:30:00Z",
            "OrigQuantity":0.001,
            "QuantityExecuted":0,
            "AvgPrice":0,
            "ChangeReason":"NewInputAccepted"
        }"#;

    let event: OrderStateEvent = serde_json::from_str(json).unwrap();
    assert_eq!(event.side, Side::Buy);
    assert_eq!(event.order_id, 98765);
    assert_eq!(event.price, Decimal::new(5000000, 2));
    assert_eq!(event.quantity, Decimal::new(1, 3));
    assert_eq!(event.instrument, 1);
    assert_eq!(event.account, 12345);
    assert_eq!(event.order_type, OrderType::Limit);
    assert_eq!(event.client_order_id, 0);
    assert_eq!(event.order_state, OrderState::Working);
    assert_eq!(event.orig_quantity, Decimal::new(1, 3));
    assert_eq!(event.quantity_executed, Decimal::ZERO);
    assert_eq!(event.avg_price, Decimal::ZERO);
  }

  #[test]
  fn test_order_trade_event_deserialize() {
    let json = r#"{
            "OMSId":1,
            "TradeId":11111,
            "OrderId":98765,
            "AccountId":12345,
            "ClientOrderId":0,
            "InstrumentId":1,
            "Side":0,
            "Quantity":0.001,
            "Price":50000.00,
            "Value":50.00,
            "TradeTime":"2024-01-15T10:30:05Z",
            "Fee":0.25,
            "FeeProductId":2
        }"#;

    let event: OrderTradeEvent = serde_json::from_str(json).unwrap();
    assert_eq!(event.oms_id, 1);
    assert_eq!(event.trade_id, 11111);
    assert_eq!(event.order_id, 98765);
    assert_eq!(event.account_id, 12345);
    assert_eq!(event.client_order_id, 0);
    assert_eq!(event.instrument_id, 1);
    assert_eq!(event.side, Side::Buy);
    assert_eq!(event.quantity, Decimal::new(1, 3));
    assert_eq!(event.price, Decimal::new(5000000, 2));
    assert_eq!(event.value, Decimal::new(5000, 2));
    assert_eq!(event.fee, Some(Decimal::new(25, 2)));
    assert_eq!(event.fee_product_id, Some(2));
  }

  #[test]
  fn test_account_event_type_from_name() {
    assert_eq!(
      AccountEventType::from_name("AccountPositionEvent"),
      Some(AccountEventType::Position)
    );
    assert_eq!(
      AccountEventType::from_name("OrderStateEvent"),
      Some(AccountEventType::OrderState)
    );
    assert_eq!(
      AccountEventType::from_name("OrderTradeEvent"),
      Some(AccountEventType::OrderTrade)
    );
    assert_eq!(
      AccountEventType::from_name("NewOrderRejectEvent"),
      Some(AccountEventType::NewOrderReject)
    );
    assert_eq!(
      AccountEventType::from_name("CancelOrderRejectEvent"),
      Some(AccountEventType::CancelOrderReject)
    );
    assert_eq!(AccountEventType::from_name("UnknownEvent"), None);
  }

  #[test]
  fn test_get_account_info_request_serialize() {
    let request = GetAccountInfoRequest {
      oms_id:     1,
      account_id: 12345,
    };
    let json = serde_json::to_string(&request).unwrap();
    assert!(json.contains("\"omsId\":1"));
    assert!(json.contains("\"accountId\":12345"));
  }

  #[test]
  fn test_get_account_positions_request_serialize() {
    let request = GetAccountPositionsRequest {
      account_id: 12345,
      oms_id:     1,
    };
    let json = serde_json::to_string(&request).unwrap();
    assert!(json.contains("\"AccountId\":12345"));
    assert!(json.contains("\"OMSId\":1"));
  }

  #[test]
  fn test_subscribe_account_events_request_serialize() {
    let request = SubscribeAccountEventsRequest {
      account_id: 12345,
      oms_id:     1,
    };
    let json = serde_json::to_string(&request).unwrap();
    assert!(json.contains("\"AccountId\":12345"));
    assert!(json.contains("\"OMSId\":1"));
  }

  #[test]
  fn test_subscribe_account_events_response_deserialize() {
    let json = r#"{"Subscribe": true}"#;
    let response: SubscribeAccountEventsResponse =
      serde_json::from_str(json).unwrap();
    assert!(response.subscribed);

    let json2 = r#"{"Subscribed": false}"#;
    let response2: SubscribeAccountEventsResponse =
      serde_json::from_str(json2).unwrap();
    assert!(!response2.subscribed);
  }

  #[test]
  fn test_new_order_reject_event_deserialize() {
    let json = r#"{
            "OMSId": 1,
            "AccountId": 12345,
            "ClientOrderId": 9999,
            "Status": "Rejected",
            "RejectReason": "No More Market"
        }"#;

    let event: NewOrderRejectEvent = serde_json::from_str(json).unwrap();
    assert_eq!(event.oms_id, 1);
    assert_eq!(event.account_id, 12345);
    assert_eq!(event.client_order_id, 9999);
    assert_eq!(event.status, "Rejected");
    assert_eq!(event.reject_reason, "No More Market");
  }

  #[test]
  fn test_cancel_order_reject_event_deserialize() {
    let json = r#"{
            "OMSId": 1,
            "AccountId": 12345,
            "OrderId": 9876,
            "OrderRevision": 1,
            "OrderType": 2,
            "InstrumentId": 1,
            "Status": "Rejected",
            "RejectReason": "Order Not Found"
        }"#;

    let event: CancelOrderRejectEvent = serde_json::from_str(json).unwrap();
    assert_eq!(event.oms_id, 1);
    assert_eq!(event.account_id, 12345);
    assert_eq!(event.order_id, 9876);
    assert_eq!(event.order_revision, 1);
    assert_eq!(event.order_type, OrderType::Limit);
    assert_eq!(event.instrument_id, 1);
    assert_eq!(event.status, "Rejected");
    assert_eq!(event.reject_reason, "Order Not Found");
  }

  #[test]
  fn test_account_position_event_deserialize() {
    let json = r#"{
            "OMSId":1,
            "AccountId":12345,
            "ProductSymbol":"CAD",
            "ProductId":2,
            "Amount":50000.00,
            "Hold":1000.00,
            "PendingDeposits":0,
            "PendingWithdraws":0,
            "TotalDayDeposits":0,
            "TotalDayWithdraws":0
        }"#;

    let event: AccountPositionEvent = serde_json::from_str(json).unwrap();
    assert_eq!(event.oms_id, 1);
    assert_eq!(event.account_id, 12345);
    assert_eq!(event.product_symbol, "CAD");
    assert_eq!(event.product_id, 2);
    assert_eq!(event.amount, Decimal::new(5000000, 2));
    assert_eq!(event.hold, Decimal::new(100000, 2));
  }

  #[test]
  fn test_account_info_deserialize() {
    let json = r#"{
            "OMSID": 1,
            "AccountId": 12345,
            "AccountName": "Test Account",
            "AccountHandle": "test_handle",
            "FirmId": "FIRM1",
            "FirmName": "Test Firm",
            "AccountType": 0,
            "FeeGroupID": 1,
            "ParentID": 0,
            "RiskType": 1,
            "VerificationLevel": 3,
            "FeeProductType": 0,
            "FeeProduct": 2,
            "RefererId": 0,
            "SupportedVenueIds": [1, 2, 3]
        }"#;

    let info: AccountInfo = serde_json::from_str(json).unwrap();
    assert_eq!(info.omsid, 1);
    assert_eq!(info.account_id, 12345);
    assert_eq!(info.account_name, "Test Account");
    assert_eq!(info.account_handle, "test_handle");
    assert_eq!(info.firm_id, "FIRM1");
    assert_eq!(info.firm_name, "Test Firm");
    assert_eq!(info.account_type, 0);
    assert_eq!(info.fee_group_id, 1);
    assert_eq!(info.parent_id, 0);
    assert_eq!(info.risk_type, 1);
    assert_eq!(info.verification_level, 3);
    assert_eq!(info.fee_product_type, 0);
    assert_eq!(info.fee_product, 2);
    assert_eq!(info.referer_id, 0);
    assert_eq!(info.supported_venue_ids, vec![1, 2, 3]);
  }
}