From 7357d48115cb0ea5b53570642f0c4e09255aba44 Mon Sep 17 00:00:00 2001 From: Giulio De Pasquale Date: Wed, 27 Jan 2021 17:12:20 +0000 Subject: [PATCH] don't crash if no open positions are found --- rustybot/src/managers.rs | 68 ++++++++++++++++++++-------------------- 1 file changed, 34 insertions(+), 34 deletions(-) diff --git a/rustybot/src/managers.rs b/rustybot/src/managers.rs index 9da5656..bb6e3f8 100644 --- a/rustybot/src/managers.rs +++ b/rustybot/src/managers.rs @@ -415,43 +415,43 @@ impl OrderManager { let (open_orders, order_book, open_positions) = (res_open_orders?, res_order_book?, res_open_positions?); - let position = open_positions - .ok_or("No open positions!")? - .into_iter() - .find(|x| x.id() == position_id) - .ok_or("Position #{} not found in open positions.")?; + // if there are open positions + if let Some(open_positions) = open_positions { + // if we find an open position with the ID we are looking for + if let Some(position) = open_positions.into_iter().find(|x| x.id() == position_id) { + let opt_position_order = open_orders + .iter() + .find(|x| x.current_form.amount().neg() == position.amount()); - let opt_position_order = open_orders - .iter() - .find(|x| x.current_form.amount().neg() == position.amount()); + // checking if the position has an open order. + // If so, don't do anything since the order is taken care of + // in the update phase. + // If no order is open, send an undercut limit order at the best current price. + if let None = opt_position_order { + // No open order, undercutting best price with limit order + let closing_price = self.best_closing_price(&position, &order_book); - // checking if the position has an open order. - // If so, don't do anything since the order is taken care of - // in the update phase. - // If no order is open, send an undercut limit order at the best current price. - if let None = opt_position_order { - // No open order, undercutting best price with limit order - let closing_price = self.best_closing_price(&position, &order_book); + // TODO: hardcoded platform to Margin! + let order_form = OrderForm::new( + self.pair.clone(), + OrderKind::Limit { + price: closing_price, + amount: position.amount().neg(), + }, + TradingPlatform::Margin, + ); - // TODO: hardcoded platform to Margin! - let order_form = OrderForm::new( - self.pair.clone(), - OrderKind::Limit { - price: closing_price, - amount: position.amount().neg(), - }, - TradingPlatform::Margin, - ); - - info!("Submitting {} order", order_form.kind()); - if let Err(e) = self.client.submit_order(&order_form).await { - error!( - "Could not submit {} to close position #{}: {}", - order_form.kind(), - position.id(), - e - ); - return Err(e); + info!("Submitting {} order", order_form.kind()); + if let Err(e) = self.client.submit_order(&order_form).await { + error!( + "Could not submit {} to close position #{}: {}", + order_form.kind(), + position.id(), + e + ); + return Err(e); + } + } } }