1use 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#[derive(Debug, Deserialize)]
16struct ApiErrorBody {
17 #[serde(rename = "errorCode")]
18 error_code: i64,
19 error: String,
20}
21
22#[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#[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#[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#[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#[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 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 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 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 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#[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#[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
445type Query = Vec<(String, String)>;
447
448fn 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
465fn 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
482pub 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 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 pub fn public() -> Result<Self> {
511 Self::new(ClientConfig::new())
512 }
513
514 pub fn from_env() -> Result<Self> {
517 Self::new(ClientConfig::from_env())
518 }
519
520 pub fn rate_limit_remaining(&self) -> i64 {
522 self.rate_limit_remaining.load(Ordering::Relaxed)
523 }
524
525 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 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 pub async fn time(&self) -> Result<ServerTime> {
625 self.get("/time", Vec::new()).await
626 }
627
628 pub async fn markets(&self) -> Result<Vec<Market>> {
630 self.get("/markets", Vec::new()).await
631 }
632
633 pub async fn market(&self, market: &str) -> Result<Market> {
635 self.get("/markets", vec![("market".into(), market.into())])
636 .await
637 }
638
639 pub async fn assets(&self) -> Result<Vec<Asset>> {
641 self.get("/assets", Vec::new()).await
642 }
643
644 pub async fn asset(&self, symbol: &str) -> Result<Asset> {
646 self.get("/assets", vec![("symbol".into(), symbol.into())])
647 .await
648 }
649
650 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 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 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 pub async fn ticker_prices(&self) -> Result<Vec<TickerPrice>> {
689 self.get("/ticker/price", Vec::new()).await
690 }
691
692 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 pub async fn ticker_books(&self) -> Result<Vec<TickerBook>> {
700 self.get("/ticker/book", Vec::new()).await
701 }
702
703 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 pub async fn tickers_24h(&self) -> Result<Vec<Ticker24h>> {
711 self.get("/ticker/24h", Vec::new()).await
712 }
713
714 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 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 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 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 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 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 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 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 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 pub async fn account(&self) -> Result<Account> {
812 self.config.credentials()?;
813 self.get("/account", Vec::new()).await
814 }
815
816 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 pub async fn balances(&self) -> Result<Vec<Balance>> {
828 self.config.credentials()?;
829 self.get("/balance", Vec::new()).await
830 }
831
832 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 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 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 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 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(¶ms).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}