Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Liquidator: randomly select token/perps for rebalancing #921

Merged
merged 1 commit into from
Mar 27, 2024
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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");
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

this means it'll panic if only the token or only the perp rebalancing fails, I'd prefer to use _res? here

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 @@ -556,7 +566,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 @@ -565,4 +575,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
}
}
Loading