Skip to main content

rust_okx/
client.rs

1//! The OKX client and its builder.
2
3use bytes::Bytes;
4use http::Method;
5use http::header::{CONTENT_TYPE, HeaderMap, HeaderName, HeaderValue};
6use serde::Serialize;
7use serde::de::DeserializeOwned;
8
9use crate::OkxRegion;
10use crate::api::account::Account;
11use crate::api::convert::Convert;
12use crate::api::finance::Finance;
13use crate::api::funding::Funding;
14use crate::api::market::Market;
15use crate::api::public_data::PublicData;
16use crate::api::trade::Trade;
17use crate::credentials::Credentials;
18use crate::error::{Error, RestError};
19use crate::model::OkxResponse;
20use crate::signing;
21use crate::transport::{DefaultTransport, Transport};
22
23/// An OKX v5 REST API client, generic over the HTTP [`Transport`].
24///
25/// Construct one with [`OkxClient::builder`] (uses the default
26/// [`ReqwestTransport`](crate::ReqwestTransport)) or [`OkxClient::with_transport`]
27/// for a custom transport. The client is cheap to share behind an `Arc` and all
28/// request methods take `&self`.
29///
30/// API groups are reached through accessor methods: [`market`](Self::market),
31/// [`public_data`](Self::public_data), [`account`](Self::account),
32/// [`funding`](Self::funding), [`convert`](Self::convert),
33/// [`finance`](Self::finance), and [`trade`](Self::trade).
34pub struct OkxClient<T = DefaultTransport> {
35    transport: T,
36    credentials: Option<Credentials>,
37    base_url: String,
38    demo: bool,
39}
40
41#[cfg(feature = "reqwest")]
42impl OkxClient {
43    /// Start building a client backed by the default
44    /// [`ReqwestTransport`](crate::ReqwestTransport).
45    pub fn builder() -> OkxClientBuilder<DefaultTransport> {
46        OkxClientBuilder::from_transport(crate::transport::ReqwestTransport::new())
47    }
48}
49
50impl<T> OkxClient<T> {
51    /// Start building a client around a custom [`Transport`].
52    pub fn with_transport(transport: T) -> OkxClientBuilder<T> {
53        OkxClientBuilder::from_transport(transport)
54    }
55}
56
57impl<T: Transport> OkxClient<T> {
58    /// Access the public market-data endpoints.
59    pub fn market(&self) -> Market<'_, T> {
60        Market::new(self)
61    }
62
63    /// Access the public reference-data endpoints.
64    pub fn public_data(&self) -> PublicData<'_, T> {
65        PublicData::new(self)
66    }
67
68    /// Access the (authenticated) account endpoints.
69    pub fn account(&self) -> Account<'_, T> {
70        Account::new(self)
71    }
72
73    /// Access the (authenticated) funding-account and asset endpoints.
74    pub fn funding(&self) -> Funding<'_, T> {
75        Funding::new(self)
76    }
77
78    /// Access the (authenticated) asset conversion endpoints.
79    pub fn convert(&self) -> Convert<'_, T> {
80        Convert::new(self)
81    }
82
83    /// Access the finance endpoints.
84    pub fn finance(&self) -> Finance<'_, T> {
85        Finance::new(self)
86    }
87
88    /// Access the (authenticated) trading endpoints.
89    pub fn trade(&self) -> Trade<'_, T> {
90        Trade::new(self)
91    }
92
93    /// Send a `GET` request, serializing `query` into the URL query string and
94    /// returning the deserialized `data` array.
95    pub(crate) async fn get<Q, D>(
96        &self,
97        endpoint: &'static str,
98        query: &Q,
99        authenticated: bool,
100    ) -> Result<D, Error>
101    where
102        Q: Serialize,
103        D: DeserializeOwned,
104    {
105        let qs = serde_urlencoded::to_string(query)
106            .map_err(|e| RestError::Encode { source: e.into() })?;
107        let request_path = if qs.is_empty() {
108            endpoint.to_owned()
109        } else {
110            format!("{endpoint}?{qs}")
111        };
112        self.send(endpoint, Method::GET, &request_path, Bytes::new(), authenticated)
113            .await
114    }
115
116    /// Send a `POST` request with `body` serialized as JSON and return the
117    /// deserialized `data` array.
118    pub(crate) async fn post<B, D>(
119        &self,
120        endpoint: &'static str,
121        body: &B,
122        authenticated: bool,
123    ) -> Result<D, Error>
124    where
125        B: Serialize,
126        D: DeserializeOwned,
127    {
128        let body = serde_json::to_vec(body)
129            .map_err(|e| RestError::Encode { source: e.into() })?;
130        self.send(endpoint, Method::POST, endpoint, Bytes::from(body), authenticated)
131            .await
132    }
133
134    async fn send<D>(
135        &self,
136        endpoint: &'static str,
137        method: Method,
138        request_path: &str,
139        body: Bytes,
140        authenticated: bool,
141    ) -> Result<D, Error>
142    where
143        D: DeserializeOwned,
144    {
145        let url = format!("{}{}", self.base_url, request_path);
146        let mut builder = http::Request::builder().method(method.clone()).uri(url);
147
148        let headers = builder
149            .headers_mut()
150            .expect("a freshly constructed request builder has no error");
151        headers.insert(CONTENT_TYPE, HeaderValue::from_static("application/json"));
152        if self.demo {
153            headers.insert(
154                HeaderName::from_static("x-simulated-trading"),
155                HeaderValue::from_static("1"),
156            );
157        }
158        if authenticated {
159            let credentials = self.credentials.as_ref().ok_or_else(|| {
160                RestError::Configuration(
161                    "authenticated endpoint requires credentials".to_owned(),
162                )
163            })?;
164            let timestamp = signing::timestamp();
165            let body_str = std::str::from_utf8(&body).unwrap_or_default();
166            let prehash = signing::pre_hash(&timestamp, method.as_str(), request_path, body_str);
167            let signature = signing::sign(&prehash, credentials.secret_key());
168            insert_header(headers, "ok-access-key", credentials.api_key())?;
169            insert_header(headers, "ok-access-sign", &signature)?;
170            insert_header(headers, "ok-access-timestamp", &timestamp)?;
171            insert_header(headers, "ok-access-passphrase", credentials.passphrase())?;
172        }
173
174        let request = builder
175            .body(body)
176            .map_err(|e| RestError::Encode { source: e.into() })?;
177        let response = self.transport.send(request).await.map_err(RestError::from)?;
178        let status = response.status();
179        let bytes = response.into_body();
180        if !status.is_success() {
181            return Err(RestError::HttpStatus {
182                endpoint,
183                status,
184                body: String::from_utf8_lossy(&bytes).into_owned(),
185            }
186            .into());
187        }
188        let envelope: OkxResponse<D> = serde_json::from_slice(&bytes)
189            .map_err(|e| RestError::Decode { endpoint, source: e })?;
190        if envelope.code != "0" {
191            return Err(RestError::Okx {
192                endpoint,
193                code: envelope.code,
194                message: envelope.msg,
195            }
196            .into());
197        }
198        Ok(envelope.data)
199    }
200}
201
202fn insert_header(headers: &mut HeaderMap, name: &'static str, value: &str) -> Result<(), Error> {
203    let value = HeaderValue::from_str(value).map_err(|e| {
204        RestError::Configuration(format!("invalid header value for {name}: {e}"))
205    })?;
206    headers.insert(HeaderName::from_static(name), value);
207    Ok(())
208}
209
210/// Builder for [`OkxClient`].
211///
212/// Created by [`OkxClient::builder`] or [`OkxClient::with_transport`].
213pub struct OkxClientBuilder<T = DefaultTransport> {
214    transport: T,
215    credentials: Option<Credentials>,
216    base_url: String,
217    demo: bool,
218}
219
220impl<T> OkxClientBuilder<T> {
221    fn from_transport(transport: T) -> Self {
222        Self {
223            transport,
224            credentials: None,
225            base_url: crate::API_URL.to_owned(),
226            demo: false,
227        }
228    }
229
230    /// Set the API credentials used to sign authenticated requests.
231    pub fn credentials(mut self, credentials: Credentials) -> Self {
232        self.credentials = Some(credentials);
233        self
234    }
235
236    /// Select the OKX REST API region.
237    ///
238    /// The default is [`OkxRegion::Global`]. US and AU users registered on
239    /// `app.okx.com` should use [`OkxRegion::Us`]. EU users registered on
240    /// `my.okx.com` should use [`OkxRegion::Eea`].
241    pub fn region(mut self, region: OkxRegion) -> Self {
242        self.base_url = region.api_url().to_owned();
243        self
244    }
245
246    /// Override the API base URL.
247    ///
248    /// This overrides the default global domain and any region selected through
249    /// [`Self::region`].
250    pub fn base_url(mut self, base_url: impl Into<String>) -> Self {
251        self.base_url = base_url.into();
252        self
253    }
254
255    /// Toggle the `x-simulated-trading` header for OKX demo trading.
256    pub fn demo_trading(mut self, demo: bool) -> Self {
257        self.demo = demo;
258        self
259    }
260
261    /// Replace the transport, changing the client's transport type.
262    pub fn transport<U>(self, transport: U) -> OkxClientBuilder<U> {
263        OkxClientBuilder {
264            transport,
265            credentials: self.credentials,
266            base_url: self.base_url,
267            demo: self.demo,
268        }
269    }
270
271    /// Build the [`OkxClient`].
272    pub fn build(self) -> OkxClient<T> {
273        OkxClient {
274            transport: self.transport,
275            credentials: self.credentials,
276            base_url: self.base_url,
277            demo: self.demo,
278        }
279    }
280}
281
282#[cfg(test)]
283mod tests {
284    use crate::error::{Error, RestError};
285    use crate::test_util::MockTransport;
286    use crate::{OkxClient, OkxRegion};
287
288    /// A non-zero OKX response code is surfaced as [`RestError::Okx`] with the
289    /// code and message preserved (offline unit test; network path covered by
290    /// integration tests).
291    #[tokio::test]
292    async fn non_zero_code_is_api_error() {
293        let mock = MockTransport::new(r#"{"code":"51000","msg":"Parameter error","data":[]}"#);
294        let client = OkxClient::with_transport(mock).build();
295        let err = client.market().get_ticker("BAD").await.unwrap_err();
296        match err {
297            Error::Rest(RestError::Okx { code, message, .. }) => {
298                assert_eq!(code, "51000");
299                assert_eq!(message, "Parameter error");
300            }
301            other => panic!("expected Error::Rest(RestError::Okx), got {other:?}"),
302        }
303    }
304
305    #[test]
306    fn okx_region_returns_expected_api_urls() {
307        assert_eq!(OkxRegion::Global.api_url(), "https://www.okx.com");
308        assert_eq!(OkxRegion::Us.api_url(), "https://us.okx.com");
309        assert_eq!(OkxRegion::Eea.api_url(), "https://eea.okx.com");
310    }
311
312    #[tokio::test]
313    async fn region_sets_request_base_url() {
314        let mock = MockTransport::new(r#"{"code":"0","msg":"","data":[]}"#);
315        let client = OkxClient::with_transport(mock.clone())
316            .region(OkxRegion::Us)
317            .build();
318
319        client.market().get_ticker("BTC-USDT").await.unwrap();
320
321        let req = mock.captured();
322        assert!(
323            req.uri
324                .starts_with("https://us.okx.com/api/v5/market/ticker"),
325            "unexpected URI: {}",
326            req.uri
327        );
328    }
329
330    #[tokio::test]
331    async fn base_url_overrides_selected_region() {
332        let mock = MockTransport::new(r#"{"code":"0","msg":"","data":[]}"#);
333        let client = OkxClient::with_transport(mock.clone())
334            .region(OkxRegion::Eea)
335            .base_url("https://example.test")
336            .build();
337
338        client.market().get_ticker("BTC-USDT").await.unwrap();
339
340        let req = mock.captured();
341        assert!(
342            req.uri
343                .starts_with("https://example.test/api/v5/market/ticker"),
344            "unexpected URI: {}",
345            req.uri
346        );
347    }
348}