use std::convert::{TryFrom, TryInto}; use std::fmt::{Debug, Formatter}; use std::str::FromStr; use std::sync::Arc; use async_trait::async_trait; use bitfinex::api::Bitfinex; use bitfinex::orders::{OrderMeta, OrderResponse}; use bitfinex::ticker::TradingPairTicker; use chrono::{DateTime, NaiveDate, NaiveDateTime, Utc}; use log::debug; use crate::currency::SymbolPair; use crate::models::{ ActiveOrder, OrderBook, OrderBookEntry, OrderForm, OrderKind, Position, PositionState, PriceTicker, }; use crate::BoxError; #[derive(Eq, PartialEq, Hash, Clone, Debug)] pub enum ExchangeKind { Bitfinex { api_key: String, api_secret: String }, } /// You do **not** have to wrap the `Client` in an [`Rc`] or [`Arc`] to **reuse** it, /// because it already uses an [`Arc`] internally. #[derive(Clone, Debug)] pub struct Client { exchange: ExchangeKind, inner: Arc>, } impl Client { pub fn new(exchange: &ExchangeKind) -> Self { let inner = match &exchange { ExchangeKind::Bitfinex { api_key, api_secret, } => BitfinexConnector::new(&api_key, &api_secret), }; Client { exchange: exchange.clone(), inner: Arc::new(Box::new(inner)), } } pub async fn active_positions( &self, pair: &SymbolPair, ) -> Result>, BoxError> { self.inner.active_positions(pair).await } pub async fn current_prices(&self, pair: &SymbolPair) -> Result { self.inner.current_prices(pair).await } pub async fn active_orders(&self, pair: &SymbolPair) -> Result, BoxError> { self.inner.active_orders(pair).await } pub async fn submit_order(&self, order: OrderForm) -> Result { self.inner.submit_order(order).await } pub async fn order_book(&self, pair: &SymbolPair) -> Result { self.inner.order_book(pair).await } pub async fn cancel_order(&self, order: &ActiveOrder) -> Result { self.inner.cancel_order(order).await } } #[async_trait] pub trait Connector: Send + Sync { fn name(&self) -> String; async fn active_positions(&self, pair: &SymbolPair) -> Result>, BoxError>; async fn current_prices(&self, pair: &SymbolPair) -> Result; async fn order_book(&self, pair: &SymbolPair) -> Result; async fn active_orders(&self, pair: &SymbolPair) -> Result, BoxError>; async fn submit_order(&self, order: OrderForm) -> Result; async fn cancel_order(&self, order: &ActiveOrder) -> Result; } impl Debug for dyn Connector { fn fmt(&self, f: &mut Formatter<'_>) -> core::fmt::Result { write!(f, "{}", self.name()) } } /************** * BITFINEX **************/ pub struct BitfinexConnector { bfx: Bitfinex, affiliate_code: Option, // account_info: String, // ledger: String, } impl BitfinexConnector { const AFFILIATE_CODE: &'static str = "XPebOgHxA"; pub fn new(api_key: &str, api_secret: &str) -> Self { BitfinexConnector { bfx: Bitfinex::new(Some(api_key.into()), Some(api_secret.into())), affiliate_code: Some(BitfinexConnector::AFFILIATE_CODE.into()), } } fn format_trading_pair(&self, pair: &SymbolPair) -> String { if pair.to_string().to_lowercase().contains("test") { format!("{}:{}", pair.base(), pair.quote()) } else { format!("{}{}", pair.base(), pair.quote()) } } } #[async_trait] impl Connector for BitfinexConnector { fn name(&self) -> String { "Bitfinex".into() } async fn active_positions(&self, pair: &SymbolPair) -> Result>, BoxError> { let active_positions = self.bfx.positions.active_positions().await?; let positions: Vec<_> = active_positions .into_iter() .filter_map(|x| x.try_into().ok()) .filter(|x: &Position| x.pair() == pair) .collect(); if positions.is_empty() { Ok(None) } else { Ok(Some(positions)) } } async fn current_prices(&self, pair: &SymbolPair) -> Result { let ticker: TradingPairTicker = self .bfx .ticker .trading_pair(self.format_trading_pair(pair)) .await?; Ok(ticker) } async fn active_orders(&self, pair: &SymbolPair) -> Result, BoxError> { unimplemented!() } async fn submit_order(&self, order: OrderForm) -> Result { // TODO: change trading pair formatting. awful. let order_form = match &self.affiliate_code { Some(affiliate_code) => bitfinex::orders::OrderForm::new( format!("t{}", self.format_trading_pair(order.pair())), *order.price(), *order.amount(), order.kind().into(), ) .with_meta(OrderMeta::new(affiliate_code.clone())), None => bitfinex::orders::OrderForm::new( format!("t{}", self.format_trading_pair(order.pair())), *order.price(), *order.amount(), order.kind().into(), ), }; let response = self.bfx.orders.submit_order(&order_form).await?; Ok(response.try_into()?) } async fn order_book(&self, pair: &SymbolPair) -> Result { let x = self .bfx .book .trading_pair( self.format_trading_pair(&pair), bitfinex::book::BookPrecision::P0, ) .await?; let entries = x .into_iter() .map(|x| OrderBookEntry::Trading { price: x.price, count: x.count as u64, amount: x.amount, }) .collect(); Ok(OrderBook::new(pair.clone()).with_entries(entries)) } async fn cancel_order(&self, order: &ActiveOrder) -> Result { let date = DateTime::::from_utc( NaiveDateTime::from_timestamp(order.update_timestamp as i64, 0), Utc, ); let cancel_form = bitfinex::orders::CancelOrderForm::new(order.id, order.client_id, date); Ok(self .bfx .orders .cancel_order(&cancel_form) .await? .try_into()?) } } impl TryFrom for ActiveOrder { type Error = BoxError; fn try_from(response: OrderResponse) -> Result { Ok(Self { id: response.id(), group_id: response.gid(), client_id: response.cid(), symbol: SymbolPair::from_str(response.symbol())?, creation_timestamp: response.mts_create(), update_timestamp: response.mts_update(), amount: response.amount(), amount_original: response.amount_orig(), order_type: (&response.order_type()).into(), previous_order_type: response.prev_order_type().map(|x| (&x).into()), price: response.price(), price_avg: response.price_avg(), hidden: response.hidden(), }) } } impl TryInto for bitfinex::positions::Position { type Error = BoxError; fn try_into(self) -> Result { let state = { if self.status().to_lowercase().contains("active") { PositionState::Open } else { PositionState::Closed } }; Ok(Position::new( SymbolPair::from_str(self.symbol())?, state, self.amount(), self.base_price(), self.pl(), self.pl_perc(), self.price_liq(), self.position_id(), ) .with_creation_date(self.mts_create()) .with_creation_update(self.mts_update())) } } impl From<&OrderKind> for bitfinex::orders::OrderKind { fn from(o: &OrderKind) -> Self { match o { OrderKind::Limit => Self::Limit, OrderKind::ExchangeLimit => Self::ExchangeLimit, OrderKind::Market => Self::Market, OrderKind::ExchangeMarket => Self::ExchangeMarket, OrderKind::Stop => Self::Stop, OrderKind::ExchangeStop => Self::ExchangeStop, OrderKind::StopLimit => Self::StopLimit, OrderKind::ExchangeStopLimit => Self::ExchangeStopLimit, OrderKind::TrailingStop => Self::TrailingStop, OrderKind::Fok => Self::Fok, OrderKind::ExchangeFok => Self::ExchangeFok, OrderKind::Ioc => Self::Ioc, OrderKind::ExchangeIoc => Self::ExchangeIoc, } } } impl From<&bitfinex::orders::OrderKind> for OrderKind { fn from(o: &bitfinex::orders::OrderKind) -> Self { match o { bitfinex::orders::OrderKind::Limit => OrderKind::Limit, bitfinex::orders::OrderKind::ExchangeLimit => OrderKind::ExchangeLimit, bitfinex::orders::OrderKind::Market => OrderKind::Market, bitfinex::orders::OrderKind::ExchangeMarket => OrderKind::ExchangeMarket, bitfinex::orders::OrderKind::Stop => OrderKind::Stop, bitfinex::orders::OrderKind::ExchangeStop => OrderKind::ExchangeStop, bitfinex::orders::OrderKind::StopLimit => OrderKind::StopLimit, bitfinex::orders::OrderKind::ExchangeStopLimit => OrderKind::ExchangeStopLimit, bitfinex::orders::OrderKind::TrailingStop => OrderKind::TrailingStop, bitfinex::orders::OrderKind::Fok => OrderKind::Fok, bitfinex::orders::OrderKind::ExchangeFok => OrderKind::ExchangeFok, bitfinex::orders::OrderKind::Ioc => OrderKind::Ioc, bitfinex::orders::OrderKind::ExchangeIoc => OrderKind::ExchangeIoc, } } } impl From for bitfinex::orders::OrderKind { fn from(o: OrderKind) -> Self { match o { OrderKind::Limit => Self::Limit, OrderKind::ExchangeLimit => Self::ExchangeLimit, OrderKind::Market => Self::Market, OrderKind::ExchangeMarket => Self::ExchangeMarket, OrderKind::Stop => Self::Stop, OrderKind::ExchangeStop => Self::ExchangeStop, OrderKind::StopLimit => Self::StopLimit, OrderKind::ExchangeStopLimit => Self::ExchangeStopLimit, OrderKind::TrailingStop => Self::TrailingStop, OrderKind::Fok => Self::Fok, OrderKind::ExchangeFok => Self::ExchangeFok, OrderKind::Ioc => Self::Ioc, OrderKind::ExchangeIoc => Self::ExchangeIoc, } } } impl From for PriceTicker { fn from(t: TradingPairTicker) -> Self { Self { bid: t.bid, bid_size: t.bid_size, ask: t.ask, ask_size: t.ask_size, daily_change: t.daily_change, daily_change_perc: t.daily_change_perc, last_price: t.last_price, volume: t.volume, high: t.high, low: t.low, } } }