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
use exc::ExchangeError;
use http::Request;
use hyper::Body;
use serde::Serialize;

use crate::key::Key;

use self::history_candles::HistoryCandles;
use self::trading::Order;

/// History candles.
pub mod history_candles;

/// Trading.
pub mod trading;

/// Okx HTTP API request types.
#[derive(Debug, Clone)]
pub enum HttpRequest {
    /// Get (public requests).
    Get(Get),
    /// Private Get.
    PrivateGet(PrivateGet),
}

/// Okx HTTP API get request types.
#[derive(Debug, Serialize, Clone)]
#[serde(untagged)]
pub enum Get {
    /// History candles.
    HistoryCandles(HistoryCandles),
}

impl Get {
    pub(crate) fn uri(&self) -> &'static str {
        match self {
            Self::HistoryCandles(_) => "/api/v5/market/history-candles",
        }
    }
}

/// Okx HTTP API get request types.
#[derive(Debug, Serialize, Clone)]
#[serde(untagged)]
pub enum PrivateGet {
    /// Order.
    Order(Order),
}

impl PrivateGet {
    pub(crate) fn uri(&self) -> &'static str {
        match self {
            Self::Order(_) => "/api/v5/trade/order",
        }
    }

    pub(crate) fn to_request(&self, host: &str, key: &Key) -> Result<Request<Body>, ExchangeError> {
        serde_qs::to_string(self)
            .map_err(|err| ExchangeError::Other(err.into()))
            .and_then(|q| {
                let uri = format!("{}?{q}", self.uri());
                let sign = key
                    .sign_now("GET", &uri, false)
                    .map_err(|e| ExchangeError::KeyError(anyhow::anyhow!("{e}")))?;
                Request::get(format!("{host}{uri}"))
                    .header("OK-ACCESS-KEY", &key.apikey)
                    .header("OK-ACCESS-SIGN", sign.signature)
                    .header("OK-ACCESS-TIMESTAMP", sign.timestamp)
                    .header("OK-ACCESS-PASSPHRASE", &key.passphrase)
                    .body(Body::empty())
                    .map_err(|err| ExchangeError::Other(err.into()))
            })
    }
}