From 8442990a0e6fe07de7af2fbbcd0dd32467390050 Mon Sep 17 00:00:00 2001 From: Giulio De Pasquale Date: Wed, 6 Jan 2021 21:17:01 +0000 Subject: [PATCH] connector --- rustybot/src/connectors.rs | 93 ++++++++++++++++++++++++++++++++++++++ 1 file changed, 93 insertions(+) create mode 100644 rustybot/src/connectors.rs diff --git a/rustybot/src/connectors.rs b/rustybot/src/connectors.rs new file mode 100644 index 0000000..d550a2f --- /dev/null +++ b/rustybot/src/connectors.rs @@ -0,0 +1,93 @@ +use std::convert::{TryFrom, TryInto}; + +use async_trait::async_trait; +use bitfinex::api::Bitfinex; +use bitfinex::ticker::TradingPairTicker; + +use crate::currency::{Symbol, SymbolPair}; +use crate::orders::Order; +use crate::positions::{Position, PositionState}; +use crate::BoxError; + +#[async_trait] +pub trait Connector { + async fn active_positions(&self, pair: &SymbolPair) -> Result, BoxError>; + async fn current_prices(&self, pair: &SymbolPair) -> Result; + async fn active_orders(&self, pair: &SymbolPair) -> Result, BoxError>; + async fn submit_order(&self) -> Result; +} + +pub struct BfxWrapper { + bfx: Bitfinex, + affiliate_code: Option, + // account_info: String, + // ledger: String, +} + +impl BfxWrapper { + pub fn new(api_key: &str, api_secret: &str) -> Self { + BfxWrapper { + bfx: Bitfinex::new(Some(api_key.into()), Some(api_secret.into())), + affiliate_code: None, + } + } + + pub fn with_affiliate_code(mut self, affiliate_code: Option) -> Self { + self.affiliate_code = affiliate_code; + self + } +} + +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( + self.symbol().try_into()?, + 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())) + } +} + +#[async_trait] +impl Connector for BfxWrapper { + async fn active_positions(&self, pair: &SymbolPair) -> Result, BoxError> { + let active_positions = self.bfx.positions.active_positions().await?; + + Ok(active_positions + .into_iter() + .filter_map(|x| x.try_into().ok()) + .filter(|x: &Position| x.pair() == pair) + .collect()) + } + + async fn current_prices(&self, pair: &SymbolPair) -> Result { + let ticker: TradingPairTicker = self.bfx.ticker.trading_pair(pair.clone()).await?; + + Ok(ticker) + } + + async fn active_orders(&self, pair: &SymbolPair) -> Result, BoxError> { + unimplemented!() + } + + async fn submit_order(&self) -> Result { + unimplemented!() + } +}