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
// Copyright (C) 2026 ndaxrs Art Morozov
// SPDX-License-Identifier: GPL-3.0-only

//! Order-related message types for the NDAX API.
//!
//! This module contains request and response structures for managing orders,
//! including sending, canceling, and querying order status.

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

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

/// Request structure for sending a new order.
///
/// Used with the "SendOrder" API endpoint.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "PascalCase")]
pub struct SendOrderRequest {
  /// The instrument being traded
  pub instrument_id:        u64,
  /// The Order Management System ID (usually 1)
  #[serde(rename = "OMSId")]
  pub oms_id:               u64,
  /// The account placing the order
  pub account_id:           u64,
  /// How long the order remains active
  pub time_in_force:        TimeInForce,
  /// Client-assigned order ID for tracking
  pub client_order_id:      u64,
  /// Order ID for One-Cancels-Other orders (0 if not used)
  #[serde(rename = "OrderIdOCO")]
  pub order_id_oco:         u64,
  /// Whether to use display quantity for iceberg orders
  pub use_display_quantity: bool,
  /// Buy or sell
  pub side:                 Side,
  /// Order quantity
  pub quantity:             Decimal,
  /// Type of order (Market, Limit, etc.)
  pub order_type:           OrderType,
  /// Peg price type for pegged orders (1=Last, 2=Bid, 3=Ask, 4=Midpoint)
  pub peg_price_type:       u8,
  /// Limit price for limit orders
  pub limit_price:          Decimal,
  /// Stop price for stop orders
  #[serde(skip_serializing_if = "Option::is_none")]
  pub stop_price:           Option<Decimal>,
  /// Display quantity for iceberg orders
  #[serde(skip_serializing_if = "Option::is_none")]
  pub display_quantity:     Option<Decimal>,
}

/// Response structure for a SendOrder request.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct SendOrderResponse {
  /// Status of the order submission ("Accepted", "Rejected", etc.)
  pub status:   String,
  /// Error message if the order was rejected
  pub errormsg: Option<String>,
  /// Order ID assigned by the exchange if accepted
  #[serde(rename = "OrderId")]
  pub order_id: Option<u64>,
}

/// Request structure for canceling an order.
///
/// Either `order_id` or `client_order_id` must be provided.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "PascalCase")]
pub struct CancelOrderRequest {
  /// The Order Management System ID (usually 1)
  #[serde(rename = "OMSId")]
  pub oms_id:          u64,
  /// The account that placed the order
  pub account_id:      u64,
  /// Exchange-assigned order ID
  #[serde(skip_serializing_if = "Option::is_none")]
  pub order_id:        Option<u64>,
  /// Client-assigned order ID
  #[serde(skip_serializing_if = "Option::is_none")]
  pub client_order_id: Option<u64>,
}

/// Request structure for canceling all orders on an account.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "PascalCase")]
pub struct CancelAllOrdersRequest {
  /// The Order Management System ID (usually 1)
  #[serde(rename = "OMSId")]
  pub oms_id:     u64,
  /// The account whose orders should be canceled
  pub account_id: u64,
}

/// Request structure for modifying an existing order.
///
/// This atomically cancels the existing order and creates a new one.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "PascalCase")]
pub struct CancelReplaceOrderRequest {
  /// The Order Management System ID (usually 1)
  #[serde(rename = "OMSId")]
  pub oms_id:                  u64,
  /// Exchange-assigned order ID of the order to modify
  pub order_id:                u64,
  /// The instrument being traded
  pub instrument_id:           u64,
  /// Revision number of the order being replaced
  pub previous_order_revision: u64,
  /// New order quantity
  pub quantity:                Decimal,
  /// New limit price
  pub limit_price:             Decimal,
}

/// Request structure for getting all open orders on an account.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "PascalCase")]
pub struct GetOpenOrdersRequest {
  /// The Order Management System ID (usually 1)
  #[serde(rename = "OMSId")]
  pub oms_id:     u64,
  /// The account to query
  pub account_id: u64,
}

/// Request structure for getting the status of a specific order.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "PascalCase")]
pub struct GetOrderStatusRequest {
  /// The Order Management System ID (usually 1)
  #[serde(rename = "OMSId")]
  pub oms_id:     u64,
  /// The account that placed the order
  pub account_id: u64,
  /// Exchange-assigned order ID
  pub order_id:   u64,
}

/// Detailed information about an order.
///
/// Returned by GetOpenOrders, GetOrderStatus, and order event subscriptions.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "PascalCase")]
pub struct OrderInfo {
  /// Buy or sell
  pub side:               Side,
  /// Exchange-assigned order ID
  pub order_id:           u64,
  /// Order price (limit price for limit orders)
  pub price:              Decimal,
  /// Remaining quantity
  pub quantity:           Decimal,
  /// Display quantity for iceberg orders
  pub display_quantity:   Decimal,
  /// Instrument ID
  pub instrument:         u64,
  /// Account ID
  pub account:            u64,
  /// Type of order
  pub order_type:         OrderType,
  /// Client-assigned order ID
  pub client_order_id:    u64,
  /// Current state of the order
  pub order_state:        OrderState,
  /// Time the order was received (ISO 8601)
  pub receive_time:       Option<String>,
  /// Time the order was received (ticks since epoch)
  #[serde(default)]
  pub receive_time_ticks: Option<u64>,
  /// Original order quantity
  pub orig_quantity:      Decimal,
  /// Quantity that has been executed
  pub quantity_executed:  Decimal,
  /// Average execution price
  pub avg_price:          Decimal,
  /// Counter party ID (for matched trades)
  #[serde(default)]
  pub counter_party_id:   Option<u64>,
  /// Reason for the last change to the order
  #[serde(default)]
  pub change_reason:      Option<String>,
  /// Original order ID (for replaced orders)
  #[serde(default)]
  pub orig_order_id:      Option<u64>,
  /// Original client order ID (for replaced orders)
  #[serde(default)]
  pub orig_cl_ord_id:     Option<u64>,
  /// User who entered the order
  #[serde(default)]
  pub entered_by:         Option<u64>,
  /// Whether this is a quote
  #[serde(default)]
  pub is_quote:           Option<bool>,
  /// Best ask price at order time
  #[serde(default)]
  pub inside_ask:         Option<Decimal>,
  /// Best bid price at order time
  #[serde(default)]
  pub inside_bid:         Option<Decimal>,
  /// Last trade price at order time
  #[serde(default)]
  pub last_trade_price:   Option<Decimal>,
  /// Rejection reason if order was rejected
  #[serde(default)]
  pub reject_reason:      Option<String>,
  /// Whether the order is locked in
  #[serde(default)]
  pub is_locked_in:       Option<bool>,
  /// Cancellation reason if order was canceled
  #[serde(default)]
  pub cancel_reason:      Option<String>,
  /// The Order Management System ID
  #[serde(rename = "OMSId")]
  pub oms_id:             u64,
}

/// Creates a limit order request.
///
/// This is a convenience function that sets sensible defaults for a simple
/// limit order (GTC, no display quantity, no OCO).
///
/// # Arguments
///
/// * `instrument_id` - The instrument to trade
/// * `account_id` - The trading account ID
/// * `side` - Buy or Sell
/// * `quantity` - Order quantity
/// * `price` - Limit price
///
/// # Example
///
/// ```
/// use ndaxrs::{messages::orders::create_limit_order, Side};
/// use rust_decimal_macros::dec;
///
/// let order =
///   create_limit_order(1, 12345, Side::Buy, dec!(0.001), dec!(50000.00));
/// assert_eq!(order.instrument_id, 1);
/// assert_eq!(order.side, Side::Buy);
/// ```
pub fn create_limit_order(
  instrument_id: u64,
  account_id: u64,
  side: Side,
  quantity: Decimal,
  price: Decimal,
) -> SendOrderRequest {
  SendOrderRequest {
    instrument_id,
    oms_id: 1,
    account_id,
    time_in_force: TimeInForce::GTC,
    client_order_id: 0,
    order_id_oco: 0,
    use_display_quantity: false,
    side,
    quantity,
    order_type: OrderType::Limit,
    peg_price_type: 1,
    limit_price: price,
    stop_price: None,
    display_quantity: None,
  }
}

/// Creates a market order request.
///
/// This is a convenience function that sets sensible defaults for a simple
/// market order (IOC, no display quantity, no OCO).
///
/// # Arguments
///
/// * `instrument_id` - The instrument to trade
/// * `account_id` - The trading account ID
/// * `side` - Buy or Sell
/// * `quantity` - Order quantity
///
/// # Example
///
/// ```
/// use ndaxrs::{messages::orders::create_market_order, Side};
/// use rust_decimal_macros::dec;
///
/// let order = create_market_order(1, 12345, Side::Sell, dec!(0.5));
/// assert_eq!(order.instrument_id, 1);
/// assert_eq!(order.side, Side::Sell);
/// ```
pub fn create_market_order(
  instrument_id: u64,
  account_id: u64,
  side: Side,
  quantity: Decimal,
) -> SendOrderRequest {
  SendOrderRequest {
    instrument_id,
    oms_id: 1,
    account_id,
    time_in_force: TimeInForce::IOC,
    client_order_id: 0,
    order_id_oco: 0,
    use_display_quantity: false,
    side,
    quantity,
    order_type: OrderType::Market,
    peg_price_type: 1,
    limit_price: Decimal::ZERO,
    stop_price: None,
    display_quantity: None,
  }
}

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

  use super::*;

  #[test]
  fn test_send_order_request_serialize() {
    let order = SendOrderRequest {
      instrument_id:        1,
      oms_id:               1,
      account_id:           12345,
      time_in_force:        TimeInForce::GTC,
      client_order_id:      0,
      order_id_oco:         0,
      use_display_quantity: false,
      side:                 Side::Buy,
      quantity:             dec!(0.001),
      order_type:           OrderType::Limit,
      peg_price_type:       1,
      limit_price:          dec!(50000.00),
      stop_price:           None,
      display_quantity:     None,
    };

    let json = serde_json::to_string(&order).unwrap();
    let parsed: serde_json::Value = serde_json::from_str(&json).unwrap();

    assert_eq!(parsed["InstrumentId"], 1);
    assert_eq!(parsed["OMSId"], 1);
    assert_eq!(parsed["AccountId"], 12345);
    assert_eq!(parsed["TimeInForce"], 1); // GTC
    assert_eq!(parsed["Side"], 0); // Buy
    assert_eq!(parsed["OrderType"], 2); // Limit
    assert_eq!(parsed["UseDisplayQuantity"], false);
  }

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

    let info: OrderInfo = serde_json::from_str(json).unwrap();

    assert_eq!(info.side, Side::Buy);
    assert_eq!(info.order_id, 98765);
    assert_eq!(info.price, dec!(50000.00));
    assert_eq!(info.quantity, dec!(0.001));
    assert_eq!(info.instrument, 1);
    assert_eq!(info.account, 12345);
    assert_eq!(info.order_type, OrderType::Limit);
    assert_eq!(info.order_state, OrderState::Working);
    assert_eq!(info.oms_id, 1);
  }

  #[test]
  fn test_create_limit_order() {
    let order =
      create_limit_order(1, 12345, Side::Buy, dec!(0.001), dec!(50000.00));

    assert_eq!(order.instrument_id, 1);
    assert_eq!(order.account_id, 12345);
    assert_eq!(order.side, Side::Buy);
    assert_eq!(order.quantity, dec!(0.001));
    assert_eq!(order.limit_price, dec!(50000.00));
    assert_eq!(order.order_type, OrderType::Limit);
    assert_eq!(order.time_in_force, TimeInForce::GTC);
    assert_eq!(order.oms_id, 1);
    assert!(!order.use_display_quantity);
  }

  #[test]
  fn test_cancel_replace_request_serialize() {
    let request = CancelReplaceOrderRequest {
      oms_id:                  1,
      order_id:                98765,
      instrument_id:           1,
      previous_order_revision: 0,
      quantity:                dec!(0.002),
      limit_price:             dec!(51000.00),
    };

    let json = serde_json::to_string(&request).unwrap();
    let parsed: serde_json::Value = serde_json::from_str(&json).unwrap();

    assert_eq!(parsed["OMSId"], 1);
    assert_eq!(parsed["OrderId"], 98765);
    assert_eq!(parsed["InstrumentId"], 1);
    assert_eq!(parsed["PreviousOrderRevision"], 0);
  }

  #[test]
  fn test_create_market_order() {
    let order = create_market_order(1, 12345, Side::Sell, dec!(0.5));

    assert_eq!(order.instrument_id, 1);
    assert_eq!(order.account_id, 12345);
    assert_eq!(order.side, Side::Sell);
    assert_eq!(order.quantity, dec!(0.5));
    assert_eq!(order.order_type, OrderType::Market);
    assert_eq!(order.time_in_force, TimeInForce::IOC);
    assert_eq!(order.limit_price, Decimal::ZERO);
  }

  #[test]
  fn test_send_order_response_accepted() {
    let json = r#"{"status":"Accepted","errormsg":"","OrderId":98765}"#;
    let response: SendOrderResponse = serde_json::from_str(json).unwrap();

    assert_eq!(response.status, "Accepted");
    assert_eq!(response.order_id, Some(98765));
  }

  #[test]
  fn test_send_order_response_rejected() {
    let json =
      r#"{"status":"Rejected","errormsg":"Insufficient funds","OrderId":null}"#;
    let response: SendOrderResponse = serde_json::from_str(json).unwrap();

    assert_eq!(response.status, "Rejected");
    assert_eq!(response.errormsg, Some("Insufficient funds".to_string()));
    assert!(response.order_id.is_none());
  }

  #[test]
  fn test_cancel_order_request_by_order_id() {
    let request = CancelOrderRequest {
      oms_id:          1,
      account_id:      12345,
      order_id:        Some(98765),
      client_order_id: None,
    };

    let json = serde_json::to_string(&request).unwrap();
    let parsed: serde_json::Value = serde_json::from_str(&json).unwrap();

    assert_eq!(parsed["OMSId"], 1);
    assert_eq!(parsed["AccountId"], 12345);
    assert_eq!(parsed["OrderId"], 98765);
    assert!(parsed.get("ClientOrderId").is_none());
  }

  #[test]
  fn test_cancel_all_orders_request() {
    let request = CancelAllOrdersRequest {
      oms_id:     1,
      account_id: 12345,
    };

    let json = serde_json::to_string(&request).unwrap();
    let parsed: serde_json::Value = serde_json::from_str(&json).unwrap();

    assert_eq!(parsed["OMSId"], 1);
    assert_eq!(parsed["AccountId"], 12345);
  }

  #[test]
  fn test_get_open_orders_request() {
    let request = GetOpenOrdersRequest {
      oms_id:     1,
      account_id: 12345,
    };

    let json = serde_json::to_string(&request).unwrap();
    let parsed: serde_json::Value = serde_json::from_str(&json).unwrap();

    assert_eq!(parsed["OMSId"], 1);
    assert_eq!(parsed["AccountId"], 12345);
  }

  #[test]
  fn test_get_order_status_request() {
    let request = GetOrderStatusRequest {
      oms_id:     1,
      account_id: 12345,
      order_id:   98765,
    };

    let json = serde_json::to_string(&request).unwrap();
    let parsed: serde_json::Value = serde_json::from_str(&json).unwrap();

    assert_eq!(parsed["OMSId"], 1);
    assert_eq!(parsed["AccountId"], 12345);
    assert_eq!(parsed["OrderId"], 98765);
  }
}