Skip to content

Commit

Permalink
liquidator: fix after review
Browse files Browse the repository at this point in the history
  • Loading branch information
farnyser committed Apr 10, 2024
1 parent 295a69b commit 5f295dd
Show file tree
Hide file tree
Showing 2 changed files with 34 additions and 34 deletions.
58 changes: 27 additions & 31 deletions bin/liquidator/src/rebalance.rs
Original file line number Diff line number Diff line change
Expand Up @@ -307,7 +307,7 @@ impl Rebalancer {
}

async fn rebalance_tokens(&self) -> anyhow::Result<()> {
self.settle_and_close_all_openbook_orders().await?;
self.close_and_settle_all_openbook_orders().await?;
let account = self.mango_account()?;

// TODO: configurable?
Expand All @@ -334,10 +334,19 @@ impl Rebalancer {
// to sell them. Instead they will be withdrawn at the end.
// Purchases will aim to purchase slightly more than is needed, such that we can
// again withdraw the dust at the end.
let dust_threshold = if self.config.use_limit_order {
I80F48::from(self.dust_threshold_for_limit_order(token).await?)
let dust_threshold_res = if self.config.use_limit_order {
self.dust_threshold_for_limit_order(token)
.await
.map(|x| I80F48::from(x))
} else {
I80F48::from(2) / token_price
Ok(I80F48::from(2) / token_price)
};

let Ok(dust_threshold) = dust_threshold_res
else {
let e = dust_threshold_res.unwrap_err();
error!("Cannot rebalance token {}, probably missing USDC market ? - error: {}", token.name, e);
return Ok(());
};

// Some rebalancing can actually change non-USDC positions (rebalancing to SOL)
Expand All @@ -352,7 +361,7 @@ impl Rebalancer {
};
let mut amount = fresh_amount()?;

trace!(token_index, %amount, %dust_threshold, "checking");
trace!(token_index, token.name, %amount, %dust_threshold, "checking");

if self.config.use_limit_order {
self.unwind_using_limit_orders(
Expand Down Expand Up @@ -485,7 +494,7 @@ impl Rebalancer {
price_adjustment_factor = price_adjustment_factor.to_num::<f64>(),
coin_lot_size = market.coin_lot_size,
pc_lot_size = market.pc_lot_size,
limit_price = limit_price,
limit_price,
native_amount = native_amount.to_num::<f64>(),
max_base_lots = max_base_lots,
"building order for rebalancing"
Expand All @@ -506,7 +515,7 @@ impl Rebalancer {
}

let mut account = account.clone();
let create_or_replace_ixs = self
let create_or_replace_account_ixs = self
.mango_client
.serum3_create_or_replace_account_instruction(&mut account, *market_index, side)
.await?;
Expand All @@ -523,11 +532,7 @@ impl Rebalancer {
max_base_lots,
((limit_price * max_base_lots * market.pc_lot_size) as f64 * 1.01) as u64,
Serum3SelfTradeBehavior::CancelProvide,
if self.config.limit_order_distance_from_oracle_price_bps == 0 {
Serum3OrderType::PostOnly
} else {
Serum3OrderType::Limit
},
Serum3OrderType::Limit,
SystemTime::now().duration_since(UNIX_EPOCH)?.as_millis() as u64,
10,
)
Expand All @@ -539,7 +544,7 @@ impl Rebalancer {
.await?;

let mut ixs = PreparedInstructions::new();
ixs.append(create_or_replace_ixs);
ixs.append(create_or_replace_account_ixs);
ixs.append(cancel_ixs);
ixs.append(place_order_ixs);
ixs.append(seq_check_ixs);
Expand All @@ -563,7 +568,7 @@ impl Rebalancer {
Ok(())
}

async fn settle_and_close_all_openbook_orders(&self) -> anyhow::Result<()> {
async fn close_and_settle_all_openbook_orders(&self) -> anyhow::Result<()> {
let account = self.mango_account()?;

for x in Self::shuffle(account.active_serum3_orders()) {
Expand All @@ -576,30 +581,26 @@ impl Rebalancer {
.serum3_markets
.get(&market_index)
.expect("no openbook market found");
self.settle_and_close_openbook_orders(&account, token, &market_index, market, quote)
self.close_and_settle_openbook_orders(&account, token, &market_index, market, quote)
.await?;
}
Ok(())
}

async fn settle_and_close_openbook_orders(
/// This will only settle funds when there is no more active orders (avoid doing too many settle tx)
async fn close_and_settle_openbook_orders(
&self,
account: &Box<MangoAccountValue>,
token: &TokenContext,
market_index: &Serum3MarketIndex,
market: &Serum3MarketContext,
quote: &TokenContext,
) -> anyhow::Result<()> {
let open_orders_opt = account
.serum3_orders(*market_index)
.map(|x| x.open_orders)
.ok();

if open_orders_opt.is_none() {
let Ok(open_orders) = account.serum3_orders(*market_index).map(|x| x.open_orders)
else {
return Ok(());
}
};

let open_orders = open_orders_opt.unwrap();
let oo_acc = self.account_fetcher.fetch_raw(&open_orders)?;
let oo = serum3_cpi::load_open_orders_bytes(oo_acc.data())?;
let oo_slim = OpenOrdersSlim::from_oo(oo);
Expand All @@ -608,14 +609,9 @@ impl Rebalancer {
return Ok(());
}

let settle_ixs = PreparedInstructions::from_single(
self.mango_client
.serum3_settle_funds_instruction(market, token, quote, open_orders),
let settle_ixs =
self.mango_client
.context
.compute_estimates
.cu_per_serum3_order_cancel, // TODO FAS
);
.serum3_settle_funds_instruction(market, token, quote, open_orders);

let close_ixs = self
.mango_client
Expand Down
10 changes: 7 additions & 3 deletions lib/client/src/client.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1163,7 +1163,7 @@ impl MangoClient {
let open_orders = account.serum3_orders(market_index).unwrap().open_orders;

let ix = self.serum3_settle_funds_instruction(s3, base, quote, open_orders);
self.send_and_confirm_owner_tx(vec![ix]).await
self.send_and_confirm_owner_tx(ix.to_instructions()).await
}

pub fn serum3_settle_funds_instruction(
Expand All @@ -1172,7 +1172,7 @@ impl MangoClient {
base: &TokenContext,
quote: &TokenContext,
open_orders: Pubkey,
) -> Instruction {
) -> PreparedInstructions {
let ix = Instruction {
program_id: mango_v4::id(),
accounts: anchor_lang::ToAccountMetas::to_account_metas(
Expand Down Expand Up @@ -1205,7 +1205,11 @@ impl MangoClient {
fees_to_dao: true,
}),
};
ix

PreparedInstructions::from_single(
ix,
self.context.compute_estimates.cu_per_mango_instruction,
)
}

pub fn serum3_cancel_all_orders_instruction(
Expand Down

0 comments on commit 5f295dd

Please sign in to comment.