# ๐งฎRebalancer

Detailed overview of how rebalancing works through the lens of an actual example.

Assume the AVAX-USDC farm on Trader Joe has \$22M liquidity and the price of AVAX is \$18. That translates to \$11M USDC and 611,111 (11M/18) AVAX. Assuming we have \$1M worth of LP on Trader Joe which comes from a 3X LYF position on Homora, our debt in USDC is 1/6M and our debt in AVAX is 1/36M ~ 27.78K AVAX or \$500K USD.

Say after some time we accrue \$10K in farm token rewards and \$2K USDC plus \$4000/18\$ AVAX in interest. Therefore

Say the price of AVAX changes to \$20. After the \$10K in rewards is added to our LP, assume the farmโs liquidity becomes \$23.20M so that it has N_a=11.60M USDC and N_b=580K AVAX. The amount of tokens in our LP is

The current leverage becomes 3.29. In order to bring the leverage back to 3 and achieve delta-neutral, we need to remove some LP tokens, swap some USDC to AVAX and repay some of our debts.

The amount of LP we need to remove is proven to be

We need to remove 5.731% LP in our position during rebalance. After that the amount of tokens in our LP is

The amount of tokens left in the pool is

The optimal amount of USDC to be swapped to AVAX is proven to be

which amounts to 3% of the LP position.

The swap satisfies

Therefore

The amount of USDC to repay Delta_d_a is the amount withdrawn minus the amount swapped

Therefore the final amount of USDC in debt is

The final amount of USDC in the LP after the swap is proven to be

And the amount of repaid AVAX is

The final amount of AVAX in debt is

And the final amount of AVAX in the LP after the swap is

which matches the debt amount(up to rounding errors) in AVAX to reach delta-neutral.

The swap price of AVAX in terms of USDC is

which indicates a slippage (including the swap fee) of 0.8%.

Also the pool price of AVAX in terms of USDC after the swap is

As a result the final leverage is

The actual calculations are much more accurate and only have single digit errors (in Solidity `uint`). In a word our contract is able to rebalance the pseudo delta-neutral position by removing the optimal amount of LP and swapping the minimal amount of tokens, with less than 1,800,000 in gas.

Last updated