godark 0.2.0

Rust SDK for GoDark DEX — encrypted trading over WebSocket
Documentation
//! GoDark SDK — Quickstart example
//!
//! ```text
//! cargo run --example quickstart
//! ```
//!
//! Set `GODARK_API_KEY_ID`, `GODARK_API_SECRET`, and `GODARK_PASSPHRASE`.
//! Optional: `GODARK_EDGE_URL`, `GDX_HPKE_STATIC_PUBLIC_KEY`.

#[path = "../shared/example_util.rs"]
mod example_util;

use std::time::Duration;

use example_util::{cancel_with_retry, local_trading_config};
use godark::{GodarkClient, GodarkError, OrderType, Side, TimeInForce, TransportConfig};

#[tokio::main]
async fn main() -> Result<(), GodarkError> {
    let transport = TransportConfig::default();
    let config = local_trading_config(transport).await?;
    let mut client = GodarkClient::new(config);

    // Take the order-update channel before connecting (one receiver per client).
    let mut order_rx = client
        .take_order_receiver()
        .ok_or_else(|| GodarkError::Config("order update receiver was already taken".into()))?;

    // Connect: WebSocket, authenticate, HPKE session.
    client.connect().await?;

    // Subscribe to order and position streams (matches Python `subscribe(["orders", "positions"])`.
    client.subscribe(&["orders", "positions"]).await?;

    // Place a resting limit buy near the configured mark.
    let mark = std::env::var("GODARK_E2E_PRICE")
        .or_else(|_| std::env::var("GDX_E2E_PRICE"))
        .ok()
        .and_then(|value| value.parse::<f64>().ok())
        .unwrap_or(68_000.0);
    let price = mark * 0.97;
    let ack = client
        .place_order(
            "BTC-USDC-PERP",
            Side::Buy,
            OrderType::Limit,
            0.001,
            Some(price),
            TimeInForce::Gtc,
            false,
            None,
            None,
        )
        .await?;

    println!(
        "Order placed: order_id={} sequence={}",
        ack.order_id, ack.sequence
    );

    // Print a few order updates as they arrive (non-blocking with overall timeout).
    const MAX_UPDATES: usize = 8;
    const UPDATES_WAIT: Duration = Duration::from_secs(15);

    let updates_deadline = tokio::time::Instant::now() + UPDATES_WAIT;
    let mut count = 0usize;

    while count < MAX_UPDATES && tokio::time::Instant::now() < updates_deadline {
        let remaining = updates_deadline.saturating_duration_since(tokio::time::Instant::now());
        match tokio::time::timeout(remaining, order_rx.recv()).await {
            Ok(Some(update)) => {
                println!(
                    "[{:?}] order={} status={:?} filled_qty={}",
                    update.update_type, update.order_id, update.status, update.filled_qty
                );
                count += 1;
            }
            Ok(None) => {
                println!("Order update channel closed.");
                break;
            }
            Err(_) => {
                println!("No further order updates within timeout; continuing to cancel.");
                break;
            }
        }
    }

    // Cancel the resting order.
    let cancel_ack = cancel_with_retry(&mut client, &ack.order_id, "BTC-USDC-PERP").await?;
    println!(
        "Cancel ack: order_id={} sequence={}",
        cancel_ack.order_id, cancel_ack.sequence
    );

    // Clean shutdown: stop background tasks and close the socket.
    client.disconnect().await;

    Ok(())
}