bcc-research / CFMMRouter.jl

Convex optimization for fun and profit. (Now in Julia!)
MIT License
317 stars 59 forks source link

Liquidaiton blows up when input amount is much bigger than reserves #12

Open fulminmaxi opened 2 years ago

fulminmaxi commented 2 years ago

Hey, I've noticed that a liquidation tends to blow up when reserves are much smaller than the input amount. I don't think this would ever happen in real situation, but I thought the bug was interesting regardless. I've set up a repo with an example here https://github.com/fulminmaxi/CFMMRouterExample/tree/main

An example of liquidations blowing up

Running this code:

#=
# Liquidating a basket of tokens
This example illustrates how to use CFMMRouter.jl to liquidate a basket of tokens.
=#
using CFMMRouter
using LinearAlgebra

## Create CFMMs
cfmms = [
    ProductTwoCoin([1e3, 1e4], 0.997, [1, 2]),
    ProductTwoCoin([1e3, 1e2], 0.997, [2, 3]),
    ProductTwoCoin([1e3, 2e4], 0.997, [1, 3])
]

## We want to liquidate a basket of tokens 2 & 3 into token 1
Δin = [0, 1e9, 0]

## Build a routing problem with liquidation objective
router = Router(
    BasketLiquidation(1, Δin),
    cfmms,
    maximum([maximum(cfmm.Ai) for cfmm in cfmms]),
)

## Optimize!
route!(router)

## Print results
Ψ = round.(Int, netflows(router))
println("Input Basket: $(round.(Int, Δin))")
println("Net trade: $Ψ")
println("Amount recieved: $(Ψ[1])")

Prints:

Input Basket: [0, 1000000000, 0]
Net trade: [1977, -9790664250826, -869499]
Amount recieved: 1977

which I think violates constraints

tjdiamandis commented 2 years ago

We could check constraints after the solve. Unfortunately, I don't think there's an easy way to get this information from the LBFGSB.jl wrapper (ideally will do a Julia native implementation at some point).

But we should allow LBFGSB options to be passed into the route! method

https://github.com/bcc-research/CFMMRouter.jl/blob/97a909c51adcb7c4a6ce582f23b3228fabd78d40/src/router.jl#L106