Skip to content

Commit

Permalink
liquidator: randomly select token/perps for rebalancing to avoid fail…
Browse files Browse the repository at this point in the history
…ing at every try if one token is having an issue (#921)

(cherry picked from commit e3a7ed9)
  • Loading branch information
farnyser committed Apr 18, 2024
1 parent fb6311e commit b128ef6
Showing 1 changed file with 26 additions and 4 deletions.
30 changes: 26 additions & 4 deletions bin/liquidator/src/rebalance.rs
Original file line number Diff line number Diff line change
Expand Up @@ -69,9 +69,19 @@ impl Rebalancer {
"checking for rebalance"
);

self.rebalance_perps().await?;
self.rebalance_tokens().await?;
let rebalance_perps_res = self.rebalance_perps().await;
let rebalance_tokens_res = self.rebalance_tokens().await;

if rebalance_perps_res.is_err() && rebalance_tokens_res.is_err() {
anyhow::bail!(
"Failed to rebalance perps ({}) and tokens ({})",
rebalance_perps_res.unwrap_err(),
rebalance_tokens_res.unwrap_err()
)
}

rebalance_perps_res.expect("rebalancing perps failed");
rebalance_tokens_res.expect("rebalancing tokens failed");
Ok(())
}

Expand Down Expand Up @@ -278,7 +288,7 @@ impl Rebalancer {
// TODO: configurable?
let quote_token = self.mango_client.context.token(QUOTE_TOKEN_INDEX);

for token_position in account.active_token_positions() {
for token_position in Self::shuffle(account.active_token_positions()) {
let token_index = token_position.token_index;
let token = self.mango_client.context.token(token_index);
if token_index == quote_token.token_index
Expand Down Expand Up @@ -557,7 +567,7 @@ impl Rebalancer {
async fn rebalance_perps(&self) -> anyhow::Result<()> {
let account = self.mango_account()?;

for perp_position in account.active_perp_positions() {
for perp_position in Self::shuffle(account.active_perp_positions()) {
let perp = self.mango_client.context.perp(perp_position.market_index);
if !self.rebalance_perp(&account, perp, perp_position).await? {
return Ok(());
Expand All @@ -566,4 +576,16 @@ impl Rebalancer {

Ok(())
}

fn shuffle<T>(iterator: impl Iterator<Item = T>) -> Vec<T> {
use rand::seq::SliceRandom;

let mut result = iterator.collect::<Vec<T>>();
{
let mut rng = rand::thread_rng();
result.shuffle(&mut rng);
}

result
}
}

0 comments on commit b128ef6

Please sign in to comment.