godark 0.2.0

Rust SDK for GoDark DEX — encrypted trading over WebSocket
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
// Domain types for the public SDK surface.

use std::time::Duration;

use serde::{Deserialize, Serialize};
use uuid::Uuid;

use crate::enums::{CancelReason, OrderStatus, OrderType, OrderUpdateType, Side, TimeInForce};

/// Lifecycle notifications for trading client reconnect (and market data reconnect).
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum ReconnectEvent {
    /// Transport reported disconnect; reconnect may follow if enabled.
    Disconnected,
    /// About to sleep and retry after a disconnect.
    Attempting {
        /// 1-based reconnect attempt counter for this disconnect episode.
        attempt: u32,
        delay: Duration,
    },
    /// Reconnect and HPKE session setup succeeded.
    Reconnected,
    /// A reconnect attempt failed (another attempt may follow).
    Failed { error: String },
}

/// One row from `GET /api/v1/leverage` — per-symbol leverage setting.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct LeverageSetting {
    pub symbol_id: u64,
    pub leverage: u32,
}

/// Cached leverage settings for the authenticated user.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct LeverageSettings {
    #[serde(default)]
    pub settings: Vec<LeverageSetting>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub user_uuid: Option<Uuid>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub server_timestamp: Option<u64>,
}

/// Optional place-order flags mirrored from gdx-web / sequencer `PlaceOrderInput`.
#[derive(Debug, Clone, Copy, PartialEq, Default)]
pub struct PlaceOrderOptions {
    pub reduce_only: bool,
    pub post_only: bool,
    pub stp_mode: crate::enums::StpMode,
    pub peg_offset_bps: Option<i32>,
    pub trigger_price: Option<f64>,
    pub take_profit_price: Option<f64>,
    pub stop_loss_price: Option<f64>,
}

/// RPC reply for amend / cancel TP-SL (`NodeResponse::tpsl_ack`).
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct TpslAck {
    pub parent_order_id: String,
    #[serde(default)]
    pub take_profit: Option<String>,
    #[serde(default)]
    pub stop_loss: Option<String>,
    pub error_code: Option<u32>,
    pub reject_text: Option<String>,
}

/// Ack for account-wide `cancel_all`, `close_all`, or per-symbol `reverse`.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct CountAck {
    pub sequence: String,
    pub count: u32,
    #[serde(default)]
    pub order_ids: Vec<String>,
    pub error_code: Option<u32>,
    pub reject_text: Option<String>,
}

/// Confirmation boundary for high-level [`crate::GodarkClient::place_order`].
///
/// Mirrors the JS SDK `confirmation: "ack" | "book"` option.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum Confirmation {
    /// Return as soon as the sequencer acknowledges the order. Callers must
    /// consume the order-update stream themselves for rejects / fills.
    Ack,
    /// Wait for a definitive order update (`OPEN` / `REJECTED` / fill / cancel)
    /// and surface post-ack rejects as [`crate::GodarkError::Order`]. Default.
    #[default]
    Book,
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct OrderAck {
    pub order_id: String,
    pub success: bool,
    pub sequence: String,
    pub error_code: Option<String>,
    pub error: Option<String>,
}

/// One cancel-replace leg of a mass quote. Mirrors the Python SDK leg dict.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct MassQuoteLegInput {
    pub side: Side,
    pub price: f64,
    pub quantity: f64,
    /// Resting order to cancel-replace. `None`/`0` = pure place (no cancel target).
    #[serde(default)]
    pub cancel_order_id: Option<u64>,
    /// Defaults to GTC when `None`.
    #[serde(default)]
    pub time_in_force: Option<crate::enums::TimeInForce>,
    /// Required when `time_in_force` = GTD (nanoseconds).
    #[serde(default)]
    pub expiry_time: Option<u64>,
}

/// One amend leg of a batch modify. At least one of `new_price`/`new_quantity`
/// must be set.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct BatchModifyLegInput {
    pub order_id: u64,
    #[serde(default)]
    pub new_price: Option<f64>,
    #[serde(default)]
    pub new_quantity: Option<f64>,
}

/// Outcome of one cancel-replace leg in a mass-quote batch.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct MassQuoteLegResult {
    pub leg_index: u32,
    /// "open" | "filled" | "failed" | "unspecified" | "unknown".
    pub status: String,
    /// `None` when no cancel target / cancel failed.
    pub cancelled_order_id: Option<String>,
    /// `None` when the replacement failed.
    pub new_order_id: Option<String>,
    pub error_code: Option<u32>,
    /// Number of taker fills this leg produced in relaxed (`post_only = false`)
    /// mode; 0 for a pure rest or a post-only leg.
    pub fill_count: u32,
}

/// Batch-level result of a mass quote: one entry per submitted leg.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct MassQuoteAck {
    pub success: bool,
    pub sequence: String,
    pub results: Vec<MassQuoteLegResult>,
}

/// Outcome of cancelling one order id in a batch-cancel request.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct BatchCancelLegResult {
    pub order_id: String,
    pub cancelled: bool,
    pub error_code: Option<u32>,
}

/// Batch-level result of a batch cancel: one entry per submitted order id.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct BatchCancelAck {
    pub success: bool,
    pub sequence: String,
    pub results: Vec<BatchCancelLegResult>,
}

/// Outcome of amending one resting order in a batch-modify request.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct BatchModifyLegResult {
    pub order_id: String,
    pub modified: bool,
    pub error_code: Option<u32>,
}

/// Batch-level result of a batch modify: one entry per submitted leg.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct BatchModifyAck {
    pub success: bool,
    pub sequence: String,
    pub results: Vec<BatchModifyLegResult>,
}

#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct OrderUpdate {
    pub order_id: String,
    pub user_uuid: Uuid,
    pub symbol_id: u64,
    pub side: Side,
    pub status: OrderStatus,
    pub update_type: OrderUpdateType,
    pub price: String,
    pub quantity: String,
    pub filled_qty: String,
    pub remaining_qty: String,
    pub cum_fill: String,
    pub cancel_reason: Option<CancelReason>,
    pub reject_reason: Option<String>,
    pub msg: Option<String>,
    pub reduce_only: bool,
    pub post_only: bool,
    pub correlation_id: u128,
    pub timestamp: u64,
}

/// Authenticated user profile (`GET /api/v1/auth/me`, session JWT only).
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct MeProfile {
    #[serde(default, deserialize_with = "deserialize_null_string")]
    pub id: String,
    #[serde(default, deserialize_with = "deserialize_null_string")]
    pub dynamic_user_id: String,
    #[serde(default, deserialize_with = "deserialize_null_string")]
    pub email: String,
    #[serde(default, deserialize_with = "deserialize_null_string")]
    pub wallet_address: String,
    #[serde(default, deserialize_with = "deserialize_null_string")]
    pub referral_code: String,
    #[serde(default, deserialize_with = "deserialize_null_string")]
    pub tier: String,
}

fn deserialize_null_string<'de, D>(deserializer: D) -> std::result::Result<String, D::Error>
where
    D: serde::Deserializer<'de>,
{
    Ok(Option::<String>::deserialize(deserializer)?.unwrap_or_default())
}

/// Sequencer trading-collateral snapshot (`BalanceUpdateMessage`).
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct BalanceUpdate {
    pub user_uuid: Uuid,
    /// Collateral in SPL raw token units (6 dp).
    pub balance_raw: u64,
    pub timestamp: u64,
    /// Human-readable internal USDT collateral.
    pub balance: String,
    pub signed_balance_8dp: i64,
    pub free_collateral_8dp: u64,
}

/// Why a [`PositionsSnapshot`] was emitted by the sequencer.
///
/// Mirrors `gdx.common.v1.PositionsSnapshotSource`.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub enum PositionsSnapshotSource {
    Unspecified,
    /// First snapshot delivered after `SubscribePositions`.
    Initial,
    /// Background periodic sweep (default 5s cadence).
    Periodic,
    /// Position-changing fill / flip / close (debounced on the sequencer).
    Event,
}

/// One row of a [`PositionsSnapshot`] — a single open position with the
/// sequencer's mark price and unrealized PnL at snapshot time.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct PositionRow {
    pub symbol_id: u64,
    pub side: Side,
    pub size: String,
    pub entry_price: String,
    pub leverage: u32,
    /// Server-computed mark price (Pyth Hermes). `None` when no Pyth tick
    /// has been observed yet for this symbol.
    pub mark_price: Option<String>,
    /// Sign-preserved unrealized PnL at `2 * decimal_places`. Absent iff
    /// `mark_price` is absent.
    pub unrealized_pnl: Option<String>,
    /// Notional (`|size| * mark_price`). Absent iff `mark_price` is absent.
    pub notional: Option<String>,
    /// Pyth `publish_time` for `mark_price` (seconds since epoch).
    pub mark_publish_time_sec: Option<u64>,
}

/// Full per-user positions batch sent by the sequencer (initial /
/// periodic / event-triggered).
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct PositionsSnapshot {
    pub user_uuid: Uuid,
    pub rows: Vec<PositionRow>,
    /// Sequencer wall-clock (ns) when the batch was assembled.
    pub server_timestamp: u64,
    pub source: PositionsSnapshotSource,
    /// Echoed from the original `SubscribePositions` request — present on
    /// `Initial` snapshots only.
    pub correlation_id: Option<u128>,
}

/// Unified component health report routed via the trading WS.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct SystemHealthUpdate {
    pub component_id: String,
    pub state: i32,
    pub serving: bool,
    pub cause: String,
    pub updated_at_nanos: u64,
    pub sequence: u64,
    pub schema_version: u32,
}

/// Funding rate tick for a symbol.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct FundingRateUpdate {
    pub symbol_id: u64,
    /// In-progress hourly rate (TWAP / 8), decimal fraction.
    pub funding_rate: String,
    /// Wall-clock emission time (ns since epoch).
    pub timestamp: u64,
    /// Last applied hourly rate, decimal fraction.
    pub last_funding_rate: String,
}

/// One working order from a [`OpenOrdersSnapshot`].
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct OpenOrderRow {
    pub order_id: String,
    pub symbol_id: u64,
    pub side: Side,
    pub order_type: OrderType,
    pub price: String,
    pub quantity: String,
    pub filled_qty: String,
    pub remaining_qty: String,
    pub order_status: OrderStatus,
    pub time_in_force: TimeInForce,
    pub leverage: u32,
    pub timestamp: u64,
    pub correlation_id: u128,
    pub expiry_time: Option<u64>,
    pub reduce_only: bool,
    pub post_only: bool,
    pub take_profit: Option<String>,
    pub stop_loss: Option<String>,
}

/// Reply to encrypted `POST /api/v1/openOrders` (`GetOpenOrders`).
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct OpenOrdersSnapshot {
    pub rows: Vec<OpenOrderRow>,
    pub server_timestamp: u64,
    pub correlation_id: u128,
}

/// Authoritative account-level margin summary. All amounts are decimal strings.
/// `free_collateral` is the server-computed amount available to open new orders
/// (already deducts margin reserved by resting orders), so render it directly
/// rather than recomputing it.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct AccountMarginSummary {
    pub total_collateral: String,
    pub position_margin: String,
    pub reserved_order_margin: String,
    pub free_collateral: String,
    /// Isolated cash locks (no UPL).
    pub isolated_margin: String,
    /// Isolated cash + isolated UPL, floored per position.
    pub isolated_equity: String,
    /// Cross position IM (no order holds).
    pub cross_im: String,
}

/// Dedicated account-margin push for a user. Emitted whenever collateral,
/// positions, or resting-order holds change.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct AccountMarginUpdate {
    pub user_uuid: Uuid,
    /// Sequencer wall-clock timestamp when the summary was computed, ns.
    pub server_timestamp: u64,
    /// Absent if the sequencer did not include a summary.
    pub account: Option<AccountMarginSummary>,
}

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

    #[test]
    fn test_order_ack_construction() {
        let ack = OrderAck {
            order_id: "oid-1".to_string(),
            success: true,
            sequence: "seq-42".to_string(),
            error_code: Some("E1".to_string()),
            error: Some("oops".to_string()),
        };
        assert_eq!(ack.order_id, "oid-1");
        assert!(ack.success);
        assert_eq!(ack.sequence, "seq-42");
        assert_eq!(ack.error_code.as_deref(), Some("E1"));
        assert_eq!(ack.error.as_deref(), Some("oops"));
    }

    #[test]
    fn test_order_update_all_fields() {
        let u = OrderUpdate {
            order_id: "o1".to_string(),
            user_uuid: Uuid::nil(),
            symbol_id: 200,
            side: Side::Sell,
            status: OrderStatus::PartiallyFilled,
            update_type: OrderUpdateType::PartiallyFilled,
            price: "1.5".to_string(),
            quantity: "10".to_string(),
            filled_qty: "3".to_string(),
            remaining_qty: "7".to_string(),
            cum_fill: "4.5".to_string(),
            cancel_reason: Some(CancelReason::UserRequested),
            reject_reason: Some("bad".to_string()),
            msg: Some("detail".to_string()),
            reduce_only: true,
            post_only: false,
            correlation_id: 999,
            timestamp: 1_700_000_000,
        };
        assert_eq!(u.order_id, "o1");
        assert_eq!(u.user_uuid, Uuid::nil());
        assert_eq!(u.symbol_id, 200);
        assert_eq!(u.side, Side::Sell);
        assert_eq!(u.status, OrderStatus::PartiallyFilled);
        assert_eq!(u.update_type, OrderUpdateType::PartiallyFilled);
        assert_eq!(u.price, "1.5");
        assert_eq!(u.quantity, "10");
        assert_eq!(u.filled_qty, "3");
        assert_eq!(u.remaining_qty, "7");
        assert_eq!(u.cum_fill, "4.5");
        assert_eq!(u.cancel_reason, Some(CancelReason::UserRequested));
        assert_eq!(u.reject_reason.as_deref(), Some("bad"));
        assert_eq!(u.correlation_id, 999);
        assert_eq!(u.timestamp, 1_700_000_000);
    }

    #[test]
    fn test_types_clone_and_debug() {
        let ack = OrderAck {
            order_id: "a".into(),
            success: false,
            sequence: "s".into(),
            error_code: None,
            error: None,
        };
        let _ = ack.clone();
        let _ = format!("{:?}", ack);

        let ou = OrderUpdate {
            order_id: "o".into(),
            user_uuid: Uuid::nil(),
            symbol_id: 0,
            side: Side::Buy,
            status: OrderStatus::New,
            update_type: OrderUpdateType::Open,
            price: "0".into(),
            quantity: "0".into(),
            filled_qty: "0".into(),
            remaining_qty: "0".into(),
            cum_fill: "0".into(),
            cancel_reason: None,
            reject_reason: None,
            msg: None,
            reduce_only: false,
            post_only: false,
            correlation_id: 0,
            timestamp: 0,
        };
        let _ = ou.clone();
        let _ = format!("{:?}", ou);
    }

    #[test]
    fn test_types_serde_roundtrip() {
        let ack = OrderAck {
            order_id: "ord".into(),
            success: true,
            sequence: "1".into(),
            error_code: Some("ec".into()),
            error: Some("e".into()),
        };
        let json = serde_json::to_string(&ack).expect("serialize");
        let back: OrderAck = serde_json::from_str(&json).expect("deserialize");
        assert_eq!(back, ack);
    }
}