Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

3 changes: 3 additions & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -49,3 +49,6 @@ default = ["us", "non-us"]
all = ["non-us", "us"]
non-us = []
us = []

[dev-dependencies]
once_cell = "1.18.0"
55 changes: 54 additions & 1 deletion src/exchanges/binance/rest_api/endpoints/instruments.rs
Original file line number Diff line number Diff line change
Expand Up @@ -64,7 +64,7 @@ impl<'de> Deserialize<'de> for BinanceAllInstruments {

let instruments_value = val
.get("symbols")
.ok_or(eyre::ErrReport::msg("could not find 'symbols' field in binance instruments response".to_string()))
.ok_or(eyre::ErrReport::msg(format!("could not find 'symbols' field in binance instruments response of {val:?}")))
.map_err(serde::de::Error::custom)?;

let instruments = serde_json::from_value(instruments_value.clone()).map_err(serde::de::Error::custom)?;
Expand Down Expand Up @@ -165,3 +165,56 @@ impl PartialEq<NormalizedInstrument> for BinanceInstrument {
equals
}
}

#[cfg(test)]
mod tests {
use crate::normalized::types::NormalizedTradingPair;

use super::*;

#[test]
fn test_binance_instrument_normalize() {
let bi = BinanceInstrument {
symbol: BinanceTradingPair("ETHBTC".to_string()),
status: "TRADING".to_string(),
base_asset: "ETH".to_string(),
base_asset_precision: 8,
quote_asset: "BTC".to_string(),
quote_precision: 8,
quote_asset_precision: 8,
order_types: vec!["LIMIT".to_string(), "LIMIT_MAKER".to_string(), "MARKET".to_string(), "STOP_LOSS_LIMIT".to_string(), "TAKE_PROFIT_LIMIT".to_string()],
iceberg_allowed: true,
oco_allowed: true,
quote_order_qty_market_allowed: true,
allow_trailing_stop: true,
cancel_replace_allowed: true,
is_spot_trading_allowed: true,
is_margin_trading_allowed: true,
permission_sets: vec![vec![BinanceTradingType::Spot, BinanceTradingType::Margin, BinanceTradingType::Other, BinanceTradingType::Other, BinanceTradingType::Other, BinanceTradingType::Other, BinanceTradingType::Other, BinanceTradingType::Other, BinanceTradingType::Other, BinanceTradingType::Other, BinanceTradingType::Other, BinanceTradingType::Other, BinanceTradingType::Other, BinanceTradingType::Other, BinanceTradingType::Other, BinanceTradingType::Other, BinanceTradingType::Other, BinanceTradingType::Other, BinanceTradingType::Other, BinanceTradingType::Other, BinanceTradingType::Other, BinanceTradingType::Other, BinanceTradingType::Other]],
permissions: vec![],
default_self_trade_prevention_mode: "EXPIRE_MAKER".to_string(),
allowed_self_trade_prevention_modes: vec!["EXPIRE_TAKER".to_string(), "EXPIRE_MAKER".to_string(), "EXPIRE_BOTH".to_string()],
};

let expected = vec![
NormalizedInstrument {
exchange: CexExchange::Binance,
trading_pair: NormalizedTradingPair::new_base_quote(CexExchange::Binance, "ETH", "BTC", None, None),
trading_type: NormalizedTradingType::Spot,
base_asset_symbol: "ETH".to_string(),
quote_asset_symbol: "BTC".to_string(),
active: true,
futures_expiry: None
}, NormalizedInstrument {
exchange: CexExchange::Binance,
trading_pair: NormalizedTradingPair::new_base_quote(CexExchange::Binance, "ETH", "BTC", None, None),
trading_type: NormalizedTradingType::Margin,
base_asset_symbol: "ETH".to_string(),
quote_asset_symbol: "BTC".to_string(),
active: true,
futures_expiry: None
}
];
assert_eq!(bi.normalize(), expected);
}
}
12 changes: 10 additions & 2 deletions src/exchanges/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -159,7 +159,11 @@ impl CexExchange {
///
/// if calling without a filter:
/// ```
/// CexExchange::Okex.get_all_currencies::<EmptyFilter>(None).await;
/// use cex_exchanges::{CexExchange, EmptyFilter};
/// async {
/// CexExchange::Okex.get_all_currencies::<EmptyFilter>(None).await;
/// };
/// ()
/// ```
pub async fn get_all_currencies<F>(self, filter: Option<F>) -> Result<Vec<NormalizedCurrency>, RestApiError>
where
Expand Down Expand Up @@ -212,7 +216,11 @@ impl CexExchange {
///
/// if calling without a filter:
/// ```
/// CexExchange::Okex.get_all_instruments::<EmptyFilter>(None).await;
/// use cex_exchanges::{CexExchange, EmptyFilter};
/// async {
/// CexExchange::Okex.get_all_instruments::<EmptyFilter>(None).await;
/// };
/// ()
/// ```
pub async fn get_all_instruments<F>(self, filter: Option<F>) -> Result<Vec<NormalizedInstrument>, RestApiError>
where
Expand Down
8 changes: 4 additions & 4 deletions src/exchanges/okex/ws/channels/tickers.rs
Original file line number Diff line number Diff line change
Expand Up @@ -22,9 +22,9 @@ pub struct OkexTicker {
#[serde_as(as = "DisplayFromStr")]
#[serde(rename = "lastSz")]
pub last_size: f64,
#[serde_as(as = "DisplayFromStr")]
#[serde_as(as = "Option<DisplayFromStr>")]
#[serde(rename = "askPx")]
pub ask_price: f64,
pub ask_price: Option<f64>,
#[serde_as(as = "DisplayFromStr")]
#[serde(rename = "askSz")]
pub ask_amt: f64,
Expand Down Expand Up @@ -74,7 +74,7 @@ impl OkexTicker {
pair: self.pair.normalize(),
time: DateTime::from_timestamp_millis(self.timestamp as i64).unwrap(),
ask_amount: self.ask_amt,
ask_price: self.ask_price,
ask_price: self.ask_price.unwrap_or_default(),
bid_amount: self.bid_amt,
bid_price: self.bid_price,
quote_id: None
Expand All @@ -90,7 +90,7 @@ impl PartialEq<NormalizedQuote> for OkexTicker {
&& other.bid_amount == self.bid_amt
&& other.bid_price == self.bid_price
&& other.ask_amount == self.ask_amt
&& other.ask_price == self.ask_price
&& other.ask_price == self.ask_price.unwrap_or_default()
&& other.quote_id.is_none();

if !equals {
Expand Down
64 changes: 40 additions & 24 deletions tests/utils.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
#![allow(unused)]
use std::fmt::Debug;
use std::{fmt::Debug, sync::Once};

use cex_exchanges::{
clients::ws::{MutliWsStreamBuilder, WsStream},
Expand Down Expand Up @@ -120,28 +120,44 @@ where
writeln!(f0, "{}", serde_json::to_string(&a).unwrap()).unwrap();
}

static TRACING: Once = Once::new();

pub fn init_test_tracing() {
let data_filter = EnvFilter::builder()
.with_default_directive(format!("cex-exchanges={}", Level::TRACE).parse().unwrap())
.from_env_lossy();

let data_layer = tracing_subscriber::fmt::layer()
.with_ansi(true)
.with_target(true)
.with_filter(data_filter)
.boxed();

let general_filter = EnvFilter::builder()
.with_default_directive(Level::DEBUG.into())
.from_env_lossy();

let general_layer = tracing_subscriber::fmt::layer()
.with_ansi(true)
.with_target(true)
.with_filter(general_filter)
.boxed();

tracing_subscriber::registry()
.with(vec![data_layer, general_layer])
.init();
TRACING.call_once(|| {
let data_filter = EnvFilter::builder()
.with_default_directive(format!("cex-exchanges={}", Level::TRACE).parse().unwrap())
.from_env_lossy();

let data_layer = tracing_subscriber::fmt::layer()
.with_ansi(true)
.with_target(true)
.with_filter(data_filter)
.boxed();

let general_filter = EnvFilter::builder()
.with_default_directive(Level::DEBUG.into())
.from_env_lossy();

let general_layer = tracing_subscriber::fmt::layer()
.with_ansi(true)
.with_target(true)
.with_filter(general_filter)
.boxed();

tracing_subscriber::registry()
.with(vec![data_layer, general_layer])
.init();
});
}

pub async fn timeout_function(test_duration_sec: u64, f: impl futures::Future<Output = ()>) -> bool
where
{
let sleep = tokio::time::sleep(std::time::Duration::from_secs(test_duration_sec));
tokio::pin!(sleep);

tokio::select! {
_ = f => true,
_ = &mut sleep => false,
}
}
Loading