don't crash if no open positions are found

This commit is contained in:
Giulio De Pasquale 2021-01-27 17:12:20 +00:00
parent d445dc137a
commit 7357d48115

View File

@ -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);
}
}
}
}