use crate::amount::{Amount, check_amounts};
use crate::client::Client;
use crate::error::{Error, ErrorCategory, Result};
use crate::models_gen::*;
use crate::operations_gen::*;
use crate::pagination::{ItemStream, Page, paginate};
use crate::transport::{Call, decode, decode_data, new_id};
fn q<P>(
params: Option<&P>,
f: fn(&P) -> Vec<(&'static str, String)>,
) -> Vec<(&'static str, String)> {
params.map(f).unwrap_or_default()
}
impl Client {
pub(crate) async fn page<T: serde::de::DeserializeOwned>(&self, c: Call) -> Result<Page<T>> {
let op = c.op;
let raw = self.t.request(c, &self.resolved()).await?;
decode(op, &raw)
}
pub(crate) async fn text(&self, mut c: Call) -> Result<String> {
c.text = true;
let raw = self.t.request(c, &self.resolved()).await?;
Ok(String::from_utf8_lossy(&raw.body).into_owned())
}
}
macro_rules! all_items {
($(#[$m:meta])* $name:ident, $page:ident, $params:ty, $item:ty) => {
$(#[$m])*
pub fn $name(&self, params: Option<&$params>, max_items: Option<usize>) -> ItemStream<'a, $item> {
let base = params.cloned().unwrap_or_default();
let this = Self { c: self.c };
paginate(base.cursor.clone(), max_items, move |cursor| {
let mut p = base.clone();
p.cursor = cursor;
async move { this.$page(Some(&p)).await }
})
}
};
}
#[derive(Clone, Copy)]
pub struct Markets<'a> {
pub(crate) c: &'a Client,
}
impl<'a> Markets<'a> {
pub async fn list(&self) -> Result<Vec<Market>> {
self.c.get(Call::new(OperationId::ListMarkets)).await
}
pub async fn get(&self, symbol: &str) -> Result<Market> {
self.c
.get(Call::new(OperationId::GetMarket).path("symbol", symbol))
.await
}
pub async fn order_book(
&self,
symbol: &str,
params: Option<&GetOrderBookParams>,
) -> Result<OrderBook> {
let c = Call::new(OperationId::GetOrderBook)
.path("symbol", symbol)
.query(q(params, GetOrderBookParams::query));
self.c.get(c).await
}
pub async fn trades(
&self,
symbol: &str,
params: Option<&GetMarketTradesParams>,
) -> Result<Page<PublicTrade>> {
let c = Call::new(OperationId::GetMarketTrades)
.path("symbol", symbol)
.query(q(params, GetMarketTradesParams::query));
self.c.page(c).await
}
pub fn all_trades(
&self,
symbol: &'a str,
params: Option<&GetMarketTradesParams>,
max_items: Option<usize>,
) -> ItemStream<'a, PublicTrade> {
let base = params.cloned().unwrap_or_default();
let this = *self;
paginate(base.cursor.clone(), max_items, move |cursor| {
let mut p = base.clone();
p.cursor = cursor;
async move { this.trades(symbol, Some(&p)).await }
})
}
pub async fn candles(&self, symbol: &str, params: &GetCandlesParams) -> Result<Vec<Candle>> {
let c = Call::new(OperationId::GetCandles)
.path("symbol", symbol)
.query(params.query());
self.c.get(c).await
}
}
pub struct Assets<'a> {
pub(crate) c: &'a Client,
}
impl Assets<'_> {
pub async fn list(&self) -> Result<Vec<Asset>> {
self.c.get(Call::new(OperationId::ListAssets)).await
}
pub async fn get(&self, symbol: &str) -> Result<Asset> {
self.c
.get(Call::new(OperationId::GetAsset).path("symbol", symbol))
.await
}
}
pub struct Networks<'a> {
pub(crate) c: &'a Client,
}
impl Networks<'_> {
pub async fn list(&self) -> Result<Vec<Network>> {
self.c.get(Call::new(OperationId::ListNetworks)).await
}
}
pub struct Fees<'a> {
pub(crate) c: &'a Client,
}
impl Fees<'_> {
pub async fn list(&self) -> Result<Vec<FeeSchedule>> {
self.c.get(Call::new(OperationId::ListFeeSchedules)).await
}
}
pub struct Pools<'a> {
pub(crate) c: &'a Client,
}
impl Pools<'_> {
pub async fn list(&self) -> Result<Vec<Pool>> {
self.c.get(Call::new(OperationId::ListPools)).await
}
pub async fn get(&self, symbol: &str) -> Result<Pool> {
self.c
.get(Call::new(OperationId::GetPool).path("symbol", symbol))
.await
}
pub async fn join(&self, symbol: &str, req: &JoinPoolRequest) -> Result<JoinPoolResult> {
let max_dev = req
.max_ratio_deviation_percent
.clone()
.map(Amount::try_from);
let max_dev = match max_dev {
Some(Err(_)) => Some(Amount::default_invalid(
req.max_ratio_deviation_percent.as_deref().unwrap_or(""),
)),
Some(Ok(a)) => Some(a),
None => None,
};
check_amounts(
"pools.join",
&[
("base_amount", Some(&req.base_amount)),
("quote_amount", Some(&req.quote_amount)),
("max_ratio_deviation_percent", max_dev.as_ref()),
],
)?;
self.c
.get(
Call::new(OperationId::JoinPool)
.path("symbol", symbol)
.json(req)?,
)
.await
}
pub async fn exit(&self, symbol: &str, req: &ExitPoolRequest) -> Result<ExitPoolResult> {
check_amounts("pools.exit", &[("shares", Some(&req.shares))])?;
self.c
.get(
Call::new(OperationId::ExitPool)
.path("symbol", symbol)
.json(req)?,
)
.await
}
}
#[derive(Clone, Copy)]
pub struct Account<'a> {
pub(crate) c: &'a Client,
}
impl<'a> Account<'a> {
pub async fn balances(&self) -> Result<Vec<Balance>> {
self.c.get(Call::new(OperationId::ListBalances)).await
}
pub async fn balance(&self, asset: &str) -> Result<Balance> {
self.c
.get(Call::new(OperationId::GetBalance).path("asset", asset))
.await
}
pub async fn ledger(&self, params: Option<&GetLedgerParams>) -> Result<Page<LedgerEntry>> {
self.c
.page(Call::new(OperationId::GetLedger).query(q(params, GetLedgerParams::query)))
.await
}
all_items!(
all_ledger, ledger, GetLedgerParams, LedgerEntry
);
pub async fn notifications(
&self,
params: Option<&ListNotificationsParams>,
) -> Result<Page<Notification>> {
self.c
.page(
Call::new(OperationId::ListNotifications)
.query(q(params, ListNotificationsParams::query)),
)
.await
}
all_items!(
all_notifications, notifications, ListNotificationsParams, Notification
);
pub async fn sub_accounts(&self) -> Result<Vec<SubAccount>> {
self.c.get(Call::new(OperationId::ListSubAccounts)).await
}
pub async fn api_keys(&self) -> Result<Vec<ApiKey>> {
self.c.get(Call::new(OperationId::ListApiKeys)).await
}
}
pub struct Exports<'a> {
pub(crate) c: &'a Client,
}
impl Exports<'_> {
async fn export(&self, op: OperationId, params: Option<&ExportParams>) -> Result<String> {
self.c
.text(Call::new(op).query(q(params, ExportParams::query)))
.await
}
pub async fn deposits(&self, params: Option<&ExportParams>) -> Result<String> {
self.export(OperationId::ExportDeposits, params).await
}
pub async fn ledger(&self, params: Option<&ExportParams>) -> Result<String> {
self.export(OperationId::ExportLedger, params).await
}
pub async fn orders(&self, params: Option<&ExportParams>) -> Result<String> {
self.export(OperationId::ExportOrders, params).await
}
pub async fn trades(&self, params: Option<&ExportParams>) -> Result<String> {
self.export(OperationId::ExportTrades, params).await
}
pub async fn withdrawals(&self, params: Option<&ExportParams>) -> Result<String> {
self.export(OperationId::ExportWithdrawals, params).await
}
}
#[derive(Clone, Copy)]
pub struct Wallet<'a> {
pub(crate) c: &'a Client,
}
impl<'a> Wallet<'a> {
pub async fn deposits(&self, params: Option<&ListDepositsParams>) -> Result<Page<Deposit>> {
self.c
.page(Call::new(OperationId::ListDeposits).query(q(params, ListDepositsParams::query)))
.await
}
all_items!(
all_deposits, deposits, ListDepositsParams, Deposit
);
pub async fn deposit(&self, deposit_id: &str) -> Result<Deposit> {
self.c
.get(Call::new(OperationId::GetDeposit).path("deposit_id", deposit_id))
.await
}
pub async fn withdrawals(
&self,
params: Option<&ListWithdrawalsParams>,
) -> Result<Page<Withdrawal>> {
self.c
.page(
Call::new(OperationId::ListWithdrawals)
.query(q(params, ListWithdrawalsParams::query)),
)
.await
}
all_items!(
all_withdrawals, withdrawals, ListWithdrawalsParams, Withdrawal
);
pub async fn withdrawal(&self, withdrawal_id: &str) -> Result<Withdrawal> {
self.c
.get(Call::new(OperationId::GetWithdrawal).path("withdrawal_id", withdrawal_id))
.await
}
pub async fn withdrawal_addresses(&self) -> Result<Vec<WithdrawalAddress>> {
self.c
.get(Call::new(OperationId::ListWithdrawalAddresses))
.await
}
pub async fn deposit_address(&self, params: &DepositAddressParams) -> Result<DepositAddress> {
if params.asset.is_empty() || params.network.is_empty() {
return Err(Error::config(
"wallet.deposit_address: asset and network are required",
));
}
self.c
.get(Call::new(OperationId::DepositAddress).query(params.query()))
.await
}
}
#[derive(Clone, Copy)]
pub struct Trading<'a> {
pub(crate) c: &'a Client,
}
#[derive(Debug, Clone, PartialEq)]
pub struct PlaceOrderResult {
pub response: PlaceOrderResponse,
pub client_order_id: String,
pub recovered: bool,
}
impl<'a> Trading<'a> {
pub async fn open_orders(&self, params: Option<&ListOpenOrdersParams>) -> Result<Vec<Order>> {
self.c
.get(
Call::new(OperationId::ListOpenOrders)
.query(q(params, ListOpenOrdersParams::query)),
)
.await
}
pub async fn order(&self, order_id: &str) -> Result<Order> {
self.c
.get(Call::new(OperationId::GetOrder).path("order_id", order_id))
.await
}
pub async fn order_by_client_id(&self, client_order_id: &str) -> Result<Order> {
self.c
.get(
Call::new(OperationId::GetOrderByClientId).path("client_order_id", client_order_id),
)
.await
}
pub async fn order_history(&self, params: Option<&OrderHistoryParams>) -> Result<Page<Order>> {
self.c
.page(Call::new(OperationId::OrderHistory).query(q(params, OrderHistoryParams::query)))
.await
}
all_items!(
all_order_history, order_history, OrderHistoryParams, Order
);
pub async fn trades(&self, params: Option<&TradeHistoryParams>) -> Result<Page<Fill>> {
self.c
.page(Call::new(OperationId::TradeHistory).query(q(params, TradeHistoryParams::query)))
.await
}
all_items!(
all_trades, trades, TradeHistoryParams, Fill
);
pub async fn place_order(&self, order: &PlaceOrderRequest) -> Result<PlaceOrderResult> {
if order.symbol.is_empty() {
return Err(Error::config("trading.place_order: symbol is required"));
}
check_amounts(
"trading.place_order",
&[
("price", order.price.as_ref()),
("quantity", order.quantity.as_ref()),
("quote_quantity", order.quote_quantity.as_ref()),
("stop_price", order.stop_price.as_ref()),
],
)?;
let mut order = order.clone();
let client_order_id = order
.client_order_id
.clone()
.filter(|s| !s.is_empty())
.unwrap_or_else(new_id);
order.client_order_id = Some(client_order_id.clone());
let o = self.c.resolved();
let call = Call::new(OperationId::PlaceOrder).json(&order)?;
let mut attempt = 0;
loop {
let err = match self.c.t.attempt(&call, &o).await {
Ok(raw) => {
let response: PlaceOrderResponse = decode_data(OperationId::PlaceOrder, &raw)
.map_err(|e| Error::OrderStateUnknown {
client_order_id: client_order_id.clone(),
source: Box::new(e),
})?;
return Ok(PlaceOrderResult {
response,
client_order_id,
recovered: false,
});
}
Err(e) => e,
};
let duplicate_after_retry = attempt > 0
&& err.is(ErrorCategory::Conflict)
&& err.api().is_some_and(|a| {
a.code == ErrorCode::AlreadyExists
|| a.code == ErrorCode::IdempotencyKeyConflict
});
if err.is_ambiguous() || duplicate_after_retry {
if let Some(existing) = self.lookup(&client_order_id, &err, o.timeout).await? {
return Ok(PlaceOrderResult {
response: PlaceOrderResponse {
order: existing,
fills: vec![],
},
client_order_id,
recovered: true,
});
}
if duplicate_after_retry || attempt >= o.max_retries || err.server_wait_too_long() {
return Err(err);
}
} else if !err.is_retryable() || attempt >= o.max_retries {
return Err(err);
}
self.c
.t
.backoff(OperationId::PlaceOrder, attempt, &err, None)
.await;
attempt += 1;
}
}
async fn lookup(
&self,
client_order_id: &str,
original: &Error,
timeout: std::time::Duration,
) -> Result<Option<Order>> {
let c = self.c.with_options(crate::CallOptions {
timeout: Some(timeout),
..self.c.opts.clone()
});
match c.trading().order_by_client_id(client_order_id).await {
Ok(o) => Ok(Some(o)),
Err(e) if e.is(ErrorCategory::NotFound) => Ok(None),
Err(_) => Err(Error::OrderStateUnknown {
client_order_id: client_order_id.to_string(),
source: Box::new(clone_error(original)),
}),
}
}
pub async fn cancel_order(&self, order_id: &str) -> Result<Order> {
let o = self.c.resolved();
let call = Call::new(OperationId::CancelOrder).path("order_id", order_id);
let mut attempt = 0;
loop {
let err = match self.c.t.attempt(&call, &o).await {
Ok(raw) => return decode_data(OperationId::CancelOrder, &raw),
Err(e) => e,
};
if attempt > 0 && err.api().is_some_and(|a| a.code == ErrorCode::InvalidState) {
return self.order(order_id).await;
}
if !err.is_retryable() || attempt >= o.max_retries {
return Err(err);
}
self.c
.t
.backoff(OperationId::CancelOrder, attempt, &err, None)
.await;
attempt += 1;
}
}
pub async fn cancel_all(&self, symbol: &str) -> Result<CancelAllResult> {
if symbol.is_empty() {
return Err(Error::config(
"trading.cancel_all: symbol is required (\"BASE/QUOTE\"); use cancel_all_markets to cancel in every market",
));
}
self.cancel_all_once(Some(symbol)).await
}
pub async fn cancel_all_markets(&self) -> Result<CancelAllResult> {
self.cancel_all_once(None).await
}
pub(crate) async fn cancel_all_once(&self, symbol: Option<&str>) -> Result<CancelAllResult> {
self.c.get(cancel_all_call(symbol)?).await
}
pub(crate) async fn cancel_all_single_request(
&self,
symbol: Option<&str>,
) -> Result<CancelAllResult> {
let o = self.c.resolved();
let raw = self.c.t.attempt(&cancel_all_call(symbol)?, &o).await?;
decode_data(OperationId::CancelAll, &raw)
}
}
fn cancel_all_call(symbol: Option<&str>) -> Result<Call> {
let mut call = Call::new(OperationId::CancelAll).json(&CancelAllRequest {
symbol: symbol.map(str::to_string),
})?;
call.no_idempotency_key = true;
Ok(call)
}
impl Amount {
fn default_invalid(text: &str) -> Amount {
serde_json::from_value(serde_json::Value::String(text.to_string())).unwrap_or_default()
}
}
pub(crate) fn clone_error(e: &Error) -> Error {
match e {
Error::Api(a) => Error::Api(a.clone()),
Error::Connection(c) => Error::Connection(c.clone()),
Error::WebSocket(w) => Error::WebSocket(w.clone()),
other => Error::Decode(other.to_string()),
}
}