client active_positions's retrieves positions with accurate profit loss

This commit is contained in:
Giulio De Pasquale 2021-01-24 15:42:54 +00:00
parent 3a0a420c5a
commit 1db62c404e
4 changed files with 43 additions and 2 deletions

View File

@ -54,7 +54,25 @@ impl Client {
&self, &self,
pair: &SymbolPair, pair: &SymbolPair,
) -> Result<Option<Vec<Position>>, BoxError> { ) -> Result<Option<Vec<Position>>, BoxError> {
self.inner.active_positions(pair).await // retrieving open positions and order book to calculate effective profit/loss
let (positions, order_book) = tokio::join!(
self.inner.active_positions(pair),
self.inner.order_book(pair)
);
let (mut positions, order_book) = (positions?, order_book?);
let (best_ask, best_bid) = (order_book.lowest_ask(), order_book.highest_bid());
// updating positions with effective profit/loss
positions.iter_mut().flatten().for_each(|mut x| {
if x.is_short() {
x.update_profit_loss(best_ask, 0.2);
} else {
x.update_profit_loss(best_bid, 0.2);
}
});
Ok(positions)
} }
pub async fn current_prices(&self, pair: &SymbolPair) -> Result<TradingPairTicker, BoxError> { pub async fn current_prices(&self, pair: &SymbolPair) -> Result<TradingPairTicker, BoxError> {

View File

@ -268,6 +268,7 @@ impl PositionManager {
None => return Ok((None, None)), None => return Ok((None, None)),
Some(positions) => { Some(positions) => {
println!("Open positions: {:?}", positions);
// checking if there are positions open for our pair // checking if there are positions open for our pair
match positions match positions
.into_iter() .into_iter()

View File

@ -386,6 +386,28 @@ impl Position {
self self
} }
pub fn update_profit_loss(&mut self, best_offer: f64, fee_perc: f64) {
let best_offer = best_offer.abs();
let base_price = self.base_price * (1.0 + fee_perc / 100.0);
let delta = if self.is_short() {
base_price - best_offer
} else {
best_offer - base_price
};
let profit_loss_percentage =
((1.0 - (base_price + delta) / base_price) * 100.0).abs() * delta.signum();
self.pl = delta * self.amount;
self.pl_perc = profit_loss_percentage;
}
pub fn with_profit_loss(mut self, profit_loss: f64) -> Self {
self.pl = profit_loss;
self
}
pub fn pair(&self) -> &SymbolPair { pub fn pair(&self) -> &SymbolPair {
&self.pair &self.pair
} }

View File

@ -96,7 +96,7 @@ impl PositionStrategy for TrailingStop {
let mut messages = vec![]; let mut messages = vec![];
let events = vec![]; let events = vec![];
let pl_perc = TrailingStop::net_pl_percentage(position.pl_perc(), TrailingStop::TAKER_FEE); let pl_perc = position.pl_perc();
let state = { let state = {
if pl_perc > TrailingStop::GOOD_PROFIT_PERC { if pl_perc > TrailingStop::GOOD_PROFIT_PERC {