Skip to main content

bitvavo_api_client/
rest.rs

1//! REST API client.
2//!
3//! Endpoint reference: <https://docs.bitvavo.com/>.
4
5use crate::ClientConfig;
6use crate::auth;
7use crate::error::{Error, Result};
8use crate::types::*;
9use reqwest::Method;
10use serde::de::DeserializeOwned;
11use serde::{Deserialize, Serialize};
12use std::sync::atomic::{AtomicI64, Ordering};
13
14/// Error payload returned by the API.
15#[derive(Debug, Deserialize)]
16struct ApiErrorBody {
17    #[serde(rename = "errorCode")]
18    error_code: i64,
19    error: String,
20}
21
22/// Parameters for trade listing endpoints.
23#[derive(Debug, Clone, Default, Serialize)]
24#[serde(rename_all = "camelCase")]
25pub struct TradesParams {
26    #[serde(skip_serializing_if = "Option::is_none")]
27    pub limit: Option<u32>,
28    #[serde(skip_serializing_if = "Option::is_none")]
29    pub start: Option<u64>,
30    #[serde(skip_serializing_if = "Option::is_none")]
31    pub end: Option<u64>,
32    #[serde(skip_serializing_if = "Option::is_none")]
33    pub trade_id_from: Option<String>,
34    #[serde(skip_serializing_if = "Option::is_none")]
35    pub trade_id_to: Option<String>,
36}
37
38impl TradesParams {
39    pub fn new() -> Self {
40        Self::default()
41    }
42
43    pub fn limit(mut self, limit: u32) -> Self {
44        self.limit = Some(limit);
45        self
46    }
47
48    pub fn start(mut self, start_ms: u64) -> Self {
49        self.start = Some(start_ms);
50        self
51    }
52
53    pub fn end(mut self, end_ms: u64) -> Self {
54        self.end = Some(end_ms);
55        self
56    }
57
58    pub fn trade_id_from(mut self, id: impl Into<String>) -> Self {
59        self.trade_id_from = Some(id.into());
60        self
61    }
62
63    pub fn trade_id_to(mut self, id: impl Into<String>) -> Self {
64        self.trade_id_to = Some(id.into());
65        self
66    }
67}
68
69/// Parameters for `GET /{market}/candles`.
70#[derive(Debug, Clone, Default, Serialize)]
71pub struct CandlesParams {
72    #[serde(skip_serializing_if = "Option::is_none")]
73    pub limit: Option<u32>,
74    #[serde(skip_serializing_if = "Option::is_none")]
75    pub start: Option<u64>,
76    #[serde(skip_serializing_if = "Option::is_none")]
77    pub end: Option<u64>,
78}
79
80impl CandlesParams {
81    pub fn new() -> Self {
82        Self::default()
83    }
84
85    pub fn limit(mut self, limit: u32) -> Self {
86        self.limit = Some(limit);
87        self
88    }
89
90    pub fn start(mut self, start_ms: u64) -> Self {
91        self.start = Some(start_ms);
92        self
93    }
94
95    pub fn end(mut self, end_ms: u64) -> Self {
96        self.end = Some(end_ms);
97        self
98    }
99}
100
101/// Parameters for `GET /orders`.
102#[derive(Debug, Clone, Default, Serialize)]
103#[serde(rename_all = "camelCase")]
104pub struct OrdersParams {
105    #[serde(skip_serializing_if = "Option::is_none")]
106    pub limit: Option<u32>,
107    #[serde(skip_serializing_if = "Option::is_none")]
108    pub start: Option<u64>,
109    #[serde(skip_serializing_if = "Option::is_none")]
110    pub end: Option<u64>,
111    #[serde(skip_serializing_if = "Option::is_none")]
112    pub order_id_from: Option<String>,
113    #[serde(skip_serializing_if = "Option::is_none")]
114    pub order_id_to: Option<String>,
115}
116
117impl OrdersParams {
118    pub fn new() -> Self {
119        Self::default()
120    }
121
122    pub fn limit(mut self, limit: u32) -> Self {
123        self.limit = Some(limit);
124        self
125    }
126
127    pub fn start(mut self, start_ms: u64) -> Self {
128        self.start = Some(start_ms);
129        self
130    }
131
132    pub fn end(mut self, end_ms: u64) -> Self {
133        self.end = Some(end_ms);
134        self
135    }
136
137    pub fn order_id_from(mut self, id: impl Into<String>) -> Self {
138        self.order_id_from = Some(id.into());
139        self
140    }
141
142    pub fn order_id_to(mut self, id: impl Into<String>) -> Self {
143        self.order_id_to = Some(id.into());
144        self
145    }
146}
147
148/// Parameters for deposit and withdrawal history endpoints.
149#[derive(Debug, Clone, Default, Serialize)]
150pub struct HistoryParams {
151    #[serde(skip_serializing_if = "Option::is_none")]
152    pub symbol: Option<String>,
153    #[serde(skip_serializing_if = "Option::is_none")]
154    pub limit: Option<u32>,
155    #[serde(skip_serializing_if = "Option::is_none")]
156    pub start: Option<u64>,
157    #[serde(skip_serializing_if = "Option::is_none")]
158    pub end: Option<u64>,
159}
160
161impl HistoryParams {
162    pub fn new() -> Self {
163        Self::default()
164    }
165
166    pub fn symbol(mut self, symbol: impl Into<String>) -> Self {
167        self.symbol = Some(symbol.into());
168        self
169    }
170
171    pub fn limit(mut self, limit: u32) -> Self {
172        self.limit = Some(limit);
173        self
174    }
175
176    pub fn start(mut self, start_ms: u64) -> Self {
177        self.start = Some(start_ms);
178        self
179    }
180
181    pub fn end(mut self, end_ms: u64) -> Self {
182        self.end = Some(end_ms);
183        self
184    }
185}
186
187/// Request body for `POST /order`.
188#[derive(Debug, Clone, Serialize)]
189#[serde(rename_all = "camelCase")]
190pub struct OrderRequest {
191    pub market: String,
192    pub side: Side,
193    pub order_type: OrderType,
194    #[serde(skip_serializing_if = "Option::is_none")]
195    pub amount: Option<String>,
196    #[serde(skip_serializing_if = "Option::is_none")]
197    pub amount_quote: Option<String>,
198    #[serde(skip_serializing_if = "Option::is_none")]
199    pub price: Option<String>,
200    #[serde(skip_serializing_if = "Option::is_none")]
201    pub time_in_force: Option<String>,
202    #[serde(skip_serializing_if = "Option::is_none")]
203    pub self_trade_prevention: Option<String>,
204    #[serde(skip_serializing_if = "Option::is_none")]
205    pub post_only: Option<bool>,
206    #[serde(skip_serializing_if = "Option::is_none")]
207    pub disable_market_protection: Option<bool>,
208    #[serde(skip_serializing_if = "Option::is_none")]
209    pub response_required: Option<bool>,
210    #[serde(skip_serializing_if = "Option::is_none")]
211    pub trigger_type: Option<String>,
212    #[serde(skip_serializing_if = "Option::is_none")]
213    pub trigger_reference: Option<String>,
214    #[serde(skip_serializing_if = "Option::is_none")]
215    pub trigger_amount: Option<String>,
216    #[serde(skip_serializing_if = "Option::is_none")]
217    pub client_order_id: Option<String>,
218    #[serde(skip_serializing_if = "Option::is_none")]
219    pub operator_id: Option<i64>,
220}
221
222impl OrderRequest {
223    /// Creates an order request with only the required fields set.
224    pub fn new(market: impl Into<String>, side: Side, order_type: OrderType) -> Self {
225        Self {
226            market: market.into(),
227            side,
228            order_type,
229            amount: None,
230            amount_quote: None,
231            price: None,
232            time_in_force: None,
233            self_trade_prevention: None,
234            post_only: None,
235            disable_market_protection: None,
236            response_required: None,
237            trigger_type: None,
238            trigger_reference: None,
239            trigger_amount: None,
240            client_order_id: None,
241            operator_id: None,
242        }
243    }
244
245    /// Creates a limit order request.
246    pub fn limit(
247        market: impl Into<String>,
248        side: Side,
249        amount: impl Into<String>,
250        price: impl Into<String>,
251    ) -> Self {
252        Self::new(market, side, OrderType::Limit)
253            .amount(amount)
254            .price(price)
255    }
256
257    /// Creates a market order for an amount of the base asset.
258    pub fn market_amount(market: impl Into<String>, side: Side, amount: impl Into<String>) -> Self {
259        Self::new(market, side, OrderType::Market).amount(amount)
260    }
261
262    /// Creates a market order for an amount of the quote asset.
263    pub fn market_amount_quote(
264        market: impl Into<String>,
265        side: Side,
266        amount_quote: impl Into<String>,
267    ) -> Self {
268        Self::new(market, side, OrderType::Market).amount_quote(amount_quote)
269    }
270
271    pub fn amount(mut self, amount: impl Into<String>) -> Self {
272        self.amount = Some(amount.into());
273        self
274    }
275
276    pub fn amount_quote(mut self, amount_quote: impl Into<String>) -> Self {
277        self.amount_quote = Some(amount_quote.into());
278        self
279    }
280
281    pub fn price(mut self, price: impl Into<String>) -> Self {
282        self.price = Some(price.into());
283        self
284    }
285
286    pub fn time_in_force(mut self, tif: impl Into<String>) -> Self {
287        self.time_in_force = Some(tif.into());
288        self
289    }
290
291    pub fn self_trade_prevention(mut self, stp: impl Into<String>) -> Self {
292        self.self_trade_prevention = Some(stp.into());
293        self
294    }
295
296    pub fn post_only(mut self, post_only: bool) -> Self {
297        self.post_only = Some(post_only);
298        self
299    }
300
301    pub fn disable_market_protection(mut self, disable: bool) -> Self {
302        self.disable_market_protection = Some(disable);
303        self
304    }
305
306    pub fn trigger(
307        mut self,
308        trigger_type: impl Into<String>,
309        reference: impl Into<String>,
310        amount: impl Into<String>,
311    ) -> Self {
312        self.trigger_type = Some(trigger_type.into());
313        self.trigger_reference = Some(reference.into());
314        self.trigger_amount = Some(amount.into());
315        self
316    }
317
318    pub fn client_order_id(mut self, id: impl Into<String>) -> Self {
319        self.client_order_id = Some(id.into());
320        self
321    }
322
323    pub fn operator_id(mut self, id: i64) -> Self {
324        self.operator_id = Some(id);
325        self
326    }
327}
328
329/// Request body for `PUT /order`.
330#[derive(Debug, Clone, Serialize)]
331#[serde(rename_all = "camelCase")]
332pub struct UpdateOrderRequest {
333    pub market: String,
334    pub order_id: String,
335    #[serde(skip_serializing_if = "Option::is_none")]
336    pub amount: Option<String>,
337    #[serde(skip_serializing_if = "Option::is_none")]
338    pub amount_remaining: Option<String>,
339    #[serde(skip_serializing_if = "Option::is_none")]
340    pub price: Option<String>,
341    #[serde(skip_serializing_if = "Option::is_none")]
342    pub trigger_amount: Option<String>,
343    #[serde(skip_serializing_if = "Option::is_none")]
344    pub time_in_force: Option<String>,
345    #[serde(skip_serializing_if = "Option::is_none")]
346    pub self_trade_prevention: Option<String>,
347    #[serde(skip_serializing_if = "Option::is_none")]
348    pub post_only: Option<bool>,
349    #[serde(skip_serializing_if = "Option::is_none")]
350    pub response_required: Option<bool>,
351    #[serde(skip_serializing_if = "Option::is_none")]
352    pub operator_id: Option<i64>,
353}
354
355impl UpdateOrderRequest {
356    pub fn new(market: impl Into<String>, order_id: impl Into<String>) -> Self {
357        Self {
358            market: market.into(),
359            order_id: order_id.into(),
360            amount: None,
361            amount_remaining: None,
362            price: None,
363            trigger_amount: None,
364            time_in_force: None,
365            self_trade_prevention: None,
366            post_only: None,
367            response_required: None,
368            operator_id: None,
369        }
370    }
371
372    pub fn amount(mut self, amount: impl Into<String>) -> Self {
373        self.amount = Some(amount.into());
374        self
375    }
376
377    pub fn amount_remaining(mut self, amount: impl Into<String>) -> Self {
378        self.amount_remaining = Some(amount.into());
379        self
380    }
381
382    pub fn price(mut self, price: impl Into<String>) -> Self {
383        self.price = Some(price.into());
384        self
385    }
386
387    pub fn trigger_amount(mut self, amount: impl Into<String>) -> Self {
388        self.trigger_amount = Some(amount.into());
389        self
390    }
391
392    pub fn operator_id(mut self, id: i64) -> Self {
393        self.operator_id = Some(id);
394        self
395    }
396}
397
398/// Request body for `POST /withdrawal`.
399#[derive(Debug, Clone, Serialize)]
400#[serde(rename_all = "camelCase")]
401pub struct WithdrawalRequest {
402    pub symbol: String,
403    pub amount: String,
404    pub address: String,
405    #[serde(skip_serializing_if = "Option::is_none")]
406    pub payment_id: Option<String>,
407    #[serde(skip_serializing_if = "Option::is_none")]
408    pub internal: Option<bool>,
409    #[serde(skip_serializing_if = "Option::is_none")]
410    pub add_withdrawal_fee: Option<bool>,
411}
412
413impl WithdrawalRequest {
414    pub fn new(
415        symbol: impl Into<String>,
416        amount: impl Into<String>,
417        address: impl Into<String>,
418    ) -> Self {
419        Self {
420            symbol: symbol.into(),
421            amount: amount.into(),
422            address: address.into(),
423            payment_id: None,
424            internal: None,
425            add_withdrawal_fee: None,
426        }
427    }
428
429    pub fn payment_id(mut self, id: impl Into<String>) -> Self {
430        self.payment_id = Some(id.into());
431        self
432    }
433
434    pub fn internal(mut self, internal: bool) -> Self {
435        self.internal = Some(internal);
436        self
437    }
438
439    pub fn add_withdrawal_fee(mut self, add: bool) -> Self {
440        self.add_withdrawal_fee = Some(add);
441        self
442    }
443}
444
445/// Query string pairs for an endpoint.
446type Query = Vec<(String, String)>;
447
448/// Percent-encodes everything outside the RFC 3986 unreserved set.
449/// The signature is computed over the encoded path, so the signed string
450/// always matches the URL that is sent.
451/// Encoding is the identity for valid Bitvavo symbols and identifiers.
452fn encode_component(input: &str) -> String {
453    let mut out = String::with_capacity(input.len());
454    for byte in input.bytes() {
455        match byte {
456            b'A'..=b'Z' | b'a'..=b'z' | b'0'..=b'9' | b'-' | b'_' | b'.' | b'~' => {
457                out.push(byte as char);
458            }
459            _ => out.push_str(&format!("%{byte:02X}")),
460        }
461    }
462    out
463}
464
465/// Serializes a params struct into query string pairs.
466fn to_query<P: Serialize>(params: &P) -> Result<Query> {
467    let value = serde_json::to_value(params)?;
468    let mut query = Vec::new();
469    if let serde_json::Value::Object(map) = value {
470        for (key, val) in map {
471            let text = match val {
472                serde_json::Value::String(s) => s,
473                serde_json::Value::Null => continue,
474                other => other.to_string(),
475            };
476            query.push((key, text));
477        }
478    }
479    Ok(query)
480}
481
482/// Async client for the Bitvavo REST API.
483pub struct RestClient {
484    http: reqwest::Client,
485    config: ClientConfig,
486    rate_limit_remaining: AtomicI64,
487    rate_limit_reset_at: AtomicI64,
488}
489
490impl RestClient {
491    /// Creates a client from a configuration.
492    pub fn new(config: ClientConfig) -> Result<Self> {
493        crate::validate_transport_url(
494            &config.rest_url,
495            "REST",
496            "https",
497            "http",
498            config.allow_insecure_transport,
499        )?;
500        let http = reqwest::Client::builder().timeout(config.timeout).build()?;
501        Ok(Self {
502            http,
503            config,
504            rate_limit_remaining: AtomicI64::new(1000),
505            rate_limit_reset_at: AtomicI64::new(0),
506        })
507    }
508
509    /// Creates a client without credentials for public endpoints.
510    pub fn public() -> Result<Self> {
511        Self::new(ClientConfig::new())
512    }
513
514    /// Creates a client from the `BITVAVO_API_KEY` and `BITVAVO_API_SECRET`
515    /// environment variables.
516    pub fn from_env() -> Result<Self> {
517        Self::new(ClientConfig::from_env())
518    }
519
520    /// Returns the number of rate limit points left in the current window.
521    pub fn rate_limit_remaining(&self) -> i64 {
522        self.rate_limit_remaining.load(Ordering::Relaxed)
523    }
524
525    /// Returns the Unix time in milliseconds at which the rate limit resets.
526    pub fn rate_limit_reset_at(&self) -> i64 {
527        self.rate_limit_reset_at.load(Ordering::Relaxed)
528    }
529
530    fn update_rate_limit(&self, headers: &reqwest::header::HeaderMap) {
531        if let Some(remaining) = headers
532            .get("bitvavo-ratelimit-remaining")
533            .and_then(|v| v.to_str().ok())
534            .and_then(|v| v.parse().ok())
535        {
536            self.rate_limit_remaining
537                .store(remaining, Ordering::Relaxed);
538        }
539        if let Some(reset) = headers
540            .get("bitvavo-ratelimit-resetat")
541            .and_then(|v| v.to_str().ok())
542            .and_then(|v| v.parse().ok())
543        {
544            self.rate_limit_reset_at.store(reset, Ordering::Relaxed);
545        }
546    }
547
548    /// Sends a request and decodes the response.
549    /// Requests are signed whenever credentials are configured.
550    async fn request<T: DeserializeOwned>(
551        &self,
552        method: Method,
553        path: &str,
554        query: Query,
555        body: Option<serde_json::Value>,
556    ) -> Result<T> {
557        let mut path_with_query = path.to_string();
558        if !query.is_empty() {
559            let joined: Vec<String> = query
560                .iter()
561                .map(|(k, v)| format!("{k}={}", encode_component(v)))
562                .collect();
563            path_with_query.push('?');
564            path_with_query.push_str(&joined.join("&"));
565        }
566        let url = format!("{}{}", self.config.rest_url, path_with_query);
567        let body_text = match &body {
568            Some(value) => serde_json::to_string(value)?,
569            None => String::new(),
570        };
571
572        let mut request = self.http.request(method.clone(), &url);
573        if let Ok((key, secret)) = self.config.credentials() {
574            let timestamp = auth::timestamp_ms();
575            let signature = auth::sign(
576                secret,
577                timestamp,
578                method.as_str(),
579                &path_with_query,
580                &body_text,
581            );
582            request = request
583                .header("bitvavo-access-key", key)
584                .header("bitvavo-access-signature", signature)
585                .header("bitvavo-access-timestamp", timestamp.to_string())
586                .header(
587                    "bitvavo-access-window",
588                    self.config.access_window_ms.to_string(),
589                );
590        }
591        if body.is_some() {
592            request = request
593                .header("content-type", "application/json")
594                .body(body_text);
595        }
596
597        let response = request.send().await?;
598        self.update_rate_limit(response.headers());
599        let status = response.status();
600        let text = response.text().await?;
601
602        if let Ok(err) = serde_json::from_str::<ApiErrorBody>(&text) {
603            return Err(Error::Api {
604                code: err.error_code,
605                message: err.error,
606            });
607        }
608        if !status.is_success() {
609            return Err(Error::Api {
610                code: status.as_u16() as i64,
611                message: text,
612            });
613        }
614        Ok(serde_json::from_str(&text)?)
615    }
616
617    async fn get<T: DeserializeOwned>(&self, path: &str, query: Query) -> Result<T> {
618        self.request(Method::GET, path, query, None).await
619    }
620
621    // Public endpoints.
622
623    /// `GET /time`. Returns the server time.
624    pub async fn time(&self) -> Result<ServerTime> {
625        self.get("/time", Vec::new()).await
626    }
627
628    /// `GET /markets`. Returns all markets.
629    pub async fn markets(&self) -> Result<Vec<Market>> {
630        self.get("/markets", Vec::new()).await
631    }
632
633    /// `GET /markets?market={market}`. Returns a single market.
634    pub async fn market(&self, market: &str) -> Result<Market> {
635        self.get("/markets", vec![("market".into(), market.into())])
636            .await
637    }
638
639    /// `GET /assets`. Returns all assets.
640    pub async fn assets(&self) -> Result<Vec<Asset>> {
641        self.get("/assets", Vec::new()).await
642    }
643
644    /// `GET /assets?symbol={symbol}`. Returns a single asset.
645    pub async fn asset(&self, symbol: &str) -> Result<Asset> {
646        self.get("/assets", vec![("symbol".into(), symbol.into())])
647            .await
648    }
649
650    /// `GET /{market}/book`. Returns the order book for a market.
651    pub async fn order_book(&self, market: &str, depth: Option<u32>) -> Result<OrderBook> {
652        let mut query = Vec::new();
653        if let Some(depth) = depth {
654            query.push(("depth".into(), depth.to_string()));
655        }
656        self.get(&format!("/{}/book", encode_component(market)), query)
657            .await
658    }
659
660    /// `GET /{market}/trades`. Returns public trades for a market.
661    pub async fn public_trades(
662        &self,
663        market: &str,
664        params: &TradesParams,
665    ) -> Result<Vec<PublicTrade>> {
666        self.get(
667            &format!("/{}/trades", encode_component(market)),
668            to_query(params)?,
669        )
670        .await
671    }
672
673    /// `GET /{market}/candles`. Returns OHLCV candles for a market.
674    /// Supported intervals: `1m`, `5m`, `15m`, `30m`, `1h`, `2h`, `4h`, `6h`, `8h`, `12h`, `1d`.
675    pub async fn candles(
676        &self,
677        market: &str,
678        interval: &str,
679        params: &CandlesParams,
680    ) -> Result<Vec<Candle>> {
681        let mut query = vec![("interval".to_string(), interval.to_string())];
682        query.extend(to_query(params)?);
683        self.get(&format!("/{}/candles", encode_component(market)), query)
684            .await
685    }
686
687    /// `GET /ticker/price`. Returns the latest price for all markets.
688    pub async fn ticker_prices(&self) -> Result<Vec<TickerPrice>> {
689        self.get("/ticker/price", Vec::new()).await
690    }
691
692    /// `GET /ticker/price?market={market}`. Returns the latest price for one market.
693    pub async fn ticker_price(&self, market: &str) -> Result<TickerPrice> {
694        self.get("/ticker/price", vec![("market".into(), market.into())])
695            .await
696    }
697
698    /// `GET /ticker/book`. Returns the best bid and ask for all markets.
699    pub async fn ticker_books(&self) -> Result<Vec<TickerBook>> {
700        self.get("/ticker/book", Vec::new()).await
701    }
702
703    /// `GET /ticker/book?market={market}`. Returns the best bid and ask for one market.
704    pub async fn ticker_book(&self, market: &str) -> Result<TickerBook> {
705        self.get("/ticker/book", vec![("market".into(), market.into())])
706            .await
707    }
708
709    /// `GET /ticker/24h`. Returns 24 hour statistics for all markets.
710    pub async fn tickers_24h(&self) -> Result<Vec<Ticker24h>> {
711        self.get("/ticker/24h", Vec::new()).await
712    }
713
714    /// `GET /ticker/24h?market={market}`. Returns 24 hour statistics for one market.
715    pub async fn ticker_24h(&self, market: &str) -> Result<Ticker24h> {
716        self.get("/ticker/24h", vec![("market".into(), market.into())])
717            .await
718    }
719
720    // Private endpoints.
721
722    /// `POST /order`. Places a new order.
723    pub async fn place_order(&self, order: &OrderRequest) -> Result<Order> {
724        self.config.credentials()?;
725        self.request(
726            Method::POST,
727            "/order",
728            Vec::new(),
729            Some(serde_json::to_value(order)?),
730        )
731        .await
732    }
733
734    /// `GET /order`. Returns a single order.
735    pub async fn get_order(&self, market: &str, order_id: &str) -> Result<Order> {
736        self.config.credentials()?;
737        let query = vec![
738            ("market".into(), market.into()),
739            ("orderId".into(), order_id.into()),
740        ];
741        self.get("/order", query).await
742    }
743
744    /// `PUT /order`. Updates an open order.
745    pub async fn update_order(&self, update: &UpdateOrderRequest) -> Result<Order> {
746        self.config.credentials()?;
747        self.request(
748            Method::PUT,
749            "/order",
750            Vec::new(),
751            Some(serde_json::to_value(update)?),
752        )
753        .await
754    }
755
756    /// `DELETE /order`. Cancels a single order.
757    pub async fn cancel_order(
758        &self,
759        market: &str,
760        order_id: &str,
761        operator_id: Option<i64>,
762    ) -> Result<CanceledOrder> {
763        self.config.credentials()?;
764        let mut query = vec![
765            ("market".to_string(), market.to_string()),
766            ("orderId".to_string(), order_id.to_string()),
767        ];
768        if let Some(id) = operator_id {
769            query.push(("operatorId".into(), id.to_string()));
770        }
771        self.request(Method::DELETE, "/order", query, None).await
772    }
773
774    /// `GET /orders`. Returns orders for a market.
775    pub async fn get_orders(&self, market: &str, params: &OrdersParams) -> Result<Vec<Order>> {
776        self.config.credentials()?;
777        let mut query = vec![("market".to_string(), market.to_string())];
778        query.extend(to_query(params)?);
779        self.get("/orders", query).await
780    }
781
782    /// `DELETE /orders`. Cancels all open orders, optionally for one market.
783    pub async fn cancel_orders(&self, market: Option<&str>) -> Result<Vec<CanceledOrder>> {
784        self.config.credentials()?;
785        let mut query = Vec::new();
786        if let Some(market) = market {
787            query.push(("market".to_string(), market.to_string()));
788        }
789        self.request(Method::DELETE, "/orders", query, None).await
790    }
791
792    /// `GET /ordersOpen`. Returns all open orders, optionally for one market.
793    pub async fn open_orders(&self, market: Option<&str>) -> Result<Vec<Order>> {
794        self.config.credentials()?;
795        let mut query = Vec::new();
796        if let Some(market) = market {
797            query.push(("market".to_string(), market.to_string()));
798        }
799        self.get("/ordersOpen", query).await
800    }
801
802    /// `GET /trades`. Returns your trades for a market.
803    pub async fn trades(&self, market: &str, params: &TradesParams) -> Result<Vec<Trade>> {
804        self.config.credentials()?;
805        let mut query = vec![("market".to_string(), market.to_string())];
806        query.extend(to_query(params)?);
807        self.get("/trades", query).await
808    }
809
810    /// `GET /account`. Returns account information including fee rates.
811    pub async fn account(&self) -> Result<Account> {
812        self.config.credentials()?;
813        self.get("/account", Vec::new()).await
814    }
815
816    /// `GET /account/fees`. Returns fee rates, optionally for one market.
817    pub async fn fees(&self, market: Option<&str>) -> Result<FeeRates> {
818        self.config.credentials()?;
819        let mut query = Vec::new();
820        if let Some(market) = market {
821            query.push(("market".to_string(), market.to_string()));
822        }
823        self.get("/account/fees", query).await
824    }
825
826    /// `GET /balance`. Returns balances for all assets.
827    pub async fn balances(&self) -> Result<Vec<Balance>> {
828        self.config.credentials()?;
829        self.get("/balance", Vec::new()).await
830    }
831
832    /// `GET /balance?symbol={symbol}`. Returns the balance for one asset.
833    pub async fn balance(&self, symbol: &str) -> Result<Vec<Balance>> {
834        self.config.credentials()?;
835        self.get("/balance", vec![("symbol".into(), symbol.into())])
836            .await
837    }
838
839    /// `GET /depositAssets`. Returns deposit details for an asset.
840    pub async fn deposit_assets(&self, symbol: &str) -> Result<DepositInfo> {
841        self.config.credentials()?;
842        self.get("/depositAssets", vec![("symbol".into(), symbol.into())])
843            .await
844    }
845
846    /// `POST /withdrawal`. Requests a withdrawal.
847    pub async fn withdraw_assets(&self, request: &WithdrawalRequest) -> Result<WithdrawalResponse> {
848        self.config.credentials()?;
849        self.request(
850            Method::POST,
851            "/withdrawal",
852            Vec::new(),
853            Some(serde_json::to_value(request)?),
854        )
855        .await
856    }
857
858    /// `GET /depositHistory`. Returns the deposit history.
859    pub async fn deposit_history(&self, params: &HistoryParams) -> Result<Vec<DepositEntry>> {
860        self.config.credentials()?;
861        self.get("/depositHistory", to_query(params)?).await
862    }
863
864    /// `GET /withdrawalHistory`. Returns the withdrawal history.
865    pub async fn withdrawal_history(&self, params: &HistoryParams) -> Result<Vec<WithdrawalEntry>> {
866        self.config.credentials()?;
867        self.get("/withdrawalHistory", to_query(params)?).await
868    }
869}
870
871#[cfg(test)]
872mod tests {
873    use super::*;
874
875    #[test]
876    fn encode_component_is_identity_for_symbols() {
877        assert_eq!(encode_component("BTC-EUR"), "BTC-EUR");
878        assert_eq!(encode_component("abc123_.~"), "abc123_.~");
879    }
880
881    #[test]
882    fn encode_component_escapes_reserved_bytes() {
883        assert_eq!(encode_component("a b/c?d&e=f"), "a%20b%2Fc%3Fd%26e%3Df");
884    }
885
886    #[test]
887    fn to_query_skips_none_fields() {
888        let params = TradesParams::new().limit(10);
889        let query = to_query(&params).unwrap();
890        assert_eq!(query, vec![("limit".to_string(), "10".to_string())]);
891    }
892
893    #[test]
894    fn order_request_serializes_required_fields() {
895        let order = OrderRequest::limit("BTC-EUR", Side::Buy, "0.1", "20000");
896        let value = serde_json::to_value(&order).unwrap();
897        assert_eq!(value["market"], "BTC-EUR");
898        assert_eq!(value["side"], "buy");
899        assert_eq!(value["orderType"], "limit");
900        assert_eq!(value["amount"], "0.1");
901        assert_eq!(value["price"], "20000");
902        assert!(value.get("postOnly").is_none());
903    }
904}