# The mathematical principle of automatic market maker (AMM) algorithm and its future development (Part 1)

In this article, we will first review the four automatic market maker (AMM) algorithms implemented by the Bancor, Uniswap , Balancer, and Curve protocols. The latest developments, possible improvements and the future of the AMM algorithm will also be discussed.

This article is divided into the first, middle, and second chapters to explain the automatic market maker algorithm, current situation and thinking about future iterations. This article is the first chapter.

## contents

1. Bancor Network’s joint curve concept and trading formula

2. Uniswap’s impermanence loss calculation

3. The positive return when the price changes between 2ρ
4. Liquidity distribution, liquidity injection, Uniswap V3 range orders

5. Balancer’s market making function and trading formula

6. Smart order routing (SOR) algorithm

……

Bancor Network’s joint curve concept and trading formula:

Bancor¹ uses the concept of a joint curve to determine prices. The joint curve is the relationship between the price of a token and its total supply.

Bancor¹

Bancor Protocol Continuous Liquidity for Cryptographic Tokens through their Smart Contracts

https://storage.googleapis.com/website-bancor/2018/04/01ba8253-bancor_protocol_whitepaper_en.pdf

Bonding Curve:

The joint curve model can be understood as describing the functional relationship between the “token buying and selling price” and the “total amount of token issuance”, which can be automatically executed by smart contracts in a decentralized manner.

https://medium.com/linum-labs/intro-to-bonding- curve s-and-shapes-bf326bc4e11a

The invariant chosen by Bancor Network is F , which is called the connection weight. In the first expression, R refers to the number of reserve tokens in the liquidity pool , S is the total supply of BNT outside the liquidity pool, and P is the relative price of BNT and reserve tokens. We can fit into P equation, for both sides of the integral ² obtained P and S the relationship between. This is an exponential expression, where the exponent α is related to the connection weight F ( F is between 0 and 1). The smaller the F , the larger the α , which means that the price changes faster relative to the total supply of BNT.

Integral on both sides²

Formulas for Bancor system

https://drive.google.com/file/d/0B3HPNP-GDn7aRkVaV3dkVl9NS2M/view?resourcekey=0-mbIgrdd0B9H8dPNRaeB_TA

Using this expression and simple points, we can derive the relationship between T (purchased BNT tokens) and E (reserve tokens paid), where R0 and S0 are the current values of R and S.

If we want to exchange between token A and token B, then sell token A to token B. We first need to use token A to buy BNT tokens from pool A (note: if we don’t have BNT tokens). Next, we need to buy token B from pool B using BNT. Below is the precise formula needed to calculate how many tokens we will receive. The relative price between token A and token B can be expressed by the relative price between BNT token and token A/B.

Advantages: Bancor allows unilateral liquidity injection in certain pools, which is determined by Bancor governance. There are restrictions on how much unilateral liquidity can be deposited, which is also determined by Bancor’s governance. Within the limit, when users deposit unilateral liquidity in the form of other tokens, Bancor will add equivalent BNT tokens. This doubles the effective liquidity provided by users. If the limit is reached, if people want to deposit unilateral liquidity, they have to wait for someone to withdraw unilateral liquidity, or someone to inject BNT as unilateral liquidity.

The Bancor agreement compensates users for the impermanent loss when depositing unilateral liquidity with the transaction fee earned by the BNT part (will be discussed later) If the transaction costs cannot fully compensate for the impermanence loss, Bancor will mint BNT to ensure that the impermanence loss is zero. Therefore, if the liquidity provider deposits the liquidity for a certain period of time (the deposit can be fully compensated for 100 days), they can enjoy a stable income.

Disadvantages: As mentioned above, all transactions require BNT tokens as an intermediary. Therefore, we will experience two slippages. For the same reason, all liquidity pools are composed of BNT and another token, so there is a lack of diversity. The price of BNT tokens may also be affected because of the need for flexible supply to achieve impermanent loss compensation and unilateral liquidity deposits.

Bancor introduced the concept of connected token BNT, which is connected to all tokens with different connection weights, corresponding to different joint curves that determine prices.

Uniswap’s impermanence loss calculation :

Uniswap uses a constant product market maker (CPMM) to determine prices. Before we delve into the algorithms used by Uniswap V2 and V3, let us first understand what an impermanence loss (IL) is and how to calculate it.

Constant Product Market Maker (CPMM)

Constant Product Market Maker

It is mandatory that the product of the reserves of the two assets must always remain unchanged x*y=k

https://ethresear.ch/t/improving-front-running-resistance-of-xyk-market-makers/1281

Impermanence loss

Impermanent Loss

Refers to the losses faced by funds in the liquidity pool.

https://finematics.com/impermanent-loss-explained/

If the AMM function is convex (note: the price increases as we buy / the price decreases as we sell ), then a single transaction without transaction fee compensation will always cause the liquidity provider to lose money. Suppose a transaction causes the AMM function to move from point 1 to point 2. The spot prices of points 1 and 2 (the absolute value of the derivative of the function) are P1 and P2. P3 is the actual transaction price. Due to the nature of the convex function, P1> P3> P2. The impermanence loss is defined as the difference between the current value of the liquidity provider’s tokens in the pool after the transaction and the current value of the liquidity provider’s tokens, if he just holds his tokens and does not use them for liquidity Provided, it is expressed as V and Vheld. For convenience, the impermanence loss and price will be expressed in token Y (the price of 1 token Y is the unit 1). After some simple derivation, it is easy to prove that the impermanence loss is always less than zero (x2> x1, P2 <P3).

Uniswap³ V2 uses a simple but powerful formula to determine transactions. The product of the number of pool token reserves is a constant. Compared with Bancor, it gets rid of the dependency on connected tokens. The transaction is completely determined by the number of tokens in the liquidity pool.

Uniswap³

Uniswap V2 Core

https://uniswap.org/whitepaper.pdf

Due to the nature of this function, the value of the two tokens in the pool will always be the same (the prices we use in this article will always be relative prices).

Using the same logic, it is not difficult to calculate a single impermanence loss without commission in Uniswap V2 . Suppose the transaction changes the price from P to Pk . The impermanence loss measured as a percentage can be separately expressed as a function of k .

Not surprisingly, this function is always less than or equal to zero, as we can see from the graph of impermanence loss without cost above. If the horizontal axis is drawn in logarithmic space, IL(k) will be symmetric. The conclusion is: the greater the relative price change, the greater the impermanence loss. This can be explained by the fact that the more valuable tokens of the liquidity provider are bought from the pool, leaving them with more tokens of lower value.

The positive return when the price changes between 2ρ :

Next, let’s see how IL(k) will behave if we add transaction fees :

The derived impermanence loss function IL(k, ρ) looks very similar to the uncostly impermanence loss function. We can verify the plausibility by setting ρ to zero and get the same result. The typical Uniswap V2 fee percentage is ρ = 0.3%. When plotting the impermanence loss function, we can see that there is a part above zero between approximately k = 0.994 and 1 (approximately 2 ρ span). In this region, impermanence losses are positive, which means that the liquidity provider actually gains value (transaction fees earned in the region are better than losses). By introducing transaction fees, when the price fluctuates within a certain range, the liquidity provider will get a positive return.

When price changes become more volatile, liquidity providers always seem to suffer losses. However, this is not the case. We know that Dave White 4 (Note: Researcher of Paradim Venture Capital Fund) and others have solved this problem. Unfortunately, it is beyond the scope of this introductory paper. We intend to study this issue further in the future.

Dave White4

Uniswap’s Financial Alchemy

https://research.paradigm.xyz/uniswaps-alchemy

As for the impermanence loss derivation of other popular AMM algorithms (including Uniswap V3), we recommend this paper by Jiahua Xu⁵ et al. These derivations will be the subject of the next time.

Jiahua Xu⁵

SoK: Decentralized Exchanges (DEX) with Automated Market Maker (AMM) protocols

https://arxiv.org/abs/2103.12732

Advantages: The first to use a convex function of the number of tokens in the pool to determine the price.

Disadvantages: Liquidity supply is evenly distributed across all price ranges, which means lower capital efficiency.

Liquidity distribution, liquidity injection, Uniswap V3 range orders :

In order to improve the utility of liquidity and reduce the risk of impermanent loss, Uniswap⁶ V3 allows users to provide liquidity only within a certain price range.

Uniswap⁶

Uniswap V3 Core

https://uniswap.org/whitepaper-v3.pdf

From Uniswap V3 whitepaper

This is achieved by translating the Uniswap V2 function:

From Uniswap V3 whitepaper

The function translate downward a Y value of a point, pan left b point having x values as shown above and shown in Equation ensure a and b effective result between transactions, as we use our price green curve as determined function. When the price exceeds this range, one of the token reserves will be sold out, effectively concentrating liquidity within this price range.

Dan Robinson⁷ (Note: Researcher Supervisor of Paradim Venture Capital Fund) published an excellent paper on calculating the liquidity distribution of multiple AMMs.

Dan Robinson⁷

Uniswap V3: The Universal AMM

https://www.paradigm.xyz/2021/06/uniswap-v3-the-universal-amm/

It can also be simply proved that the liquidity of two liquidity providers within the same price range can be simply added together.

When depositing liquidity, as shown above, the value of each asset in Uniswap V3 is not necessarily equal. Only when P is equal to the geometric mean of Pa and Pb , the value of each asset is equal. When P is less than the geometric mean, the value of asset X is greater than the value of asset Y. When P is greater than the geometric mean, the value of asset X is less than the value of asset Y.

When the current price completely exceeds the price range set by the liquidity provider, Uniswap V3 counts the input of the liquidity provider as a Range Order, and only allows it to be deposited in one token (the type depends on whether the price range is Completely above or below the current price). For example, consider a liquidity pool composed of ETH and Dai. If the set price range is completely higher than the current price of ETH, only users are allowed to deposit ETH. If the price range is completely lower than the current price of ETH, only users are allowed to deposit Dai. When the price completely exceeds the price range set by the liquidity provider, all his deposited assets will be converted into another token. Since users can only deposit one token, range orders can only achieve two-quarters of the traditional limit orders (profit orders, buy limit orders). On the other hand, buy stop loss orders and stop loss orders cannot be realized. As of now, we don’t know what the purpose of restricting the order token type is.

Range order

Range Orders

In essence, it is not a real order, but the aggregate liquidity provided by LP to a specific price point of the fund pool. Although it is not a real order, the characteristics of the “range order” simulates the basic functions of a limit order well.

https://docs.uniswap.org/protocol/concepts/V3-overview/range-orders

Advantages: Uniswap V3 introduces the concept of liquidity distribution , allowing its users to enter liquidity within the price range. Improve capital efficiency by concentrating liquidity. When depositing assets of the same value, higher liquidity and lower slippage can be obtained. Providing liquidity within a certain price range also reduces the risk of impermanence to some extent.

Disadvantages: Users can only deposit certain types of tokens when making a range order . Therefore, buy stop loss orders and stop loss orders cannot be realized.

Uniswap V2 and V3 introduced CPMM and liquidity distribution in their AMM algorithm. Providing liquidity within the price range essentially makes Uniswap V3 a universal AMM, which can become any possible AMM by changing its liquidity distribution.

Balancer’s market-making function and trading formula :

Balancer⁸ expands Uniswap V2’s dual-token pool to a multi-token pool. The value of each asset in the Balancer pool holds a constant weight, which adds up to 1. It is not difficult to prove that this is equivalent to the power product of the number of reserves of each asset is a constant. The price of asset n relative to asset t can also be derived as the ratio between the number of reserves of asset t and n, normalized by their weights .

Balancer⁸

A non-custodial portfolio manager, liquidity provider, and price sensor

https://balancer.fi/whitepaper.pdf

Based on the constant invariant, we can derive the transaction formula with different input values ​​(the transaction between asset o and asset i). In this notation standard, asset o is always a purchased asset. Asset i is the asset sold. A and B are the tokens credited/received and the current token reserve quantity . We can also calculate the number of tokens injected or tokens bought based on changes in price .

Smart Order Routing (SOR) algorithm :

Balancer also introduced the Smart Order Routing (SOR⁹) algorithm.

SOR⁹

Smart Order Router V2

https://docs.balancer.fi/developers/smart-order-router

The general idea of ​​the algorithm is to divide an order into several small blocks for trading in different Balancer pools to obtain better trading results . Suppose we want to trade in token pool 1 and token pool 2. If the total amount N we want to trade is lower than A in the above figure, we will only trade in token pool 1, because of the price of token pool 1. It is always better than the token pool 2 price. If the total amount exceeds A, we will trade part of the order in token pool 1 and part of the order in token pool 2. The number of transactions in each token pool will equalize the price in each pool (B + C = N).

It is easy to prove that the optimal strategy is always the strategy that equals the prices in each pool (if the prices are not equal, we can always find a pool with a better price to improve our trading results).

The price function, relative to transaction volume, is usually a non-linear function. Balancer reduces the price function to a linear function. If there are n token pools, the optimal strategy can be expressed as:

If there is a remaining price function whose price function is always greater than or less than the range (0, N), the price function and the corresponding pool should be removed from the above calculation to ensure that the result is valid. If the price function is always small, then the obvious best strategy will be to exchange all tokens in the pool.

In this calculation, the gas cost is not considered. In fact, the optimal strategy should be to maintain a balance between routing revenue and gas cost loss.

The SOR algorithm, we believe it can be used in a wider context. For example, the price function can be a function of other AMM protocol pools. Due to the limitations of our current knowledge, we are not sure whether actual AMM aggregators use the same logic to achieve better prices. A more general solution without any approximation of the price function will be discussed later in this article.

Advantages: Balancer promotes 2 token pools to multiple token pools, and introduces the SOR algorithm to achieve better prices for its users.

Disadvantages: “The strength of the liquidity pool depends on its weakest asset.” The more types of tokens in a pool, the higher the risk.

Balancer is a multi-token portfolio management tool that allows flexible token value distribution and has a price optimization algorithm.

As the paper too long, Curve discussion and subsequent content will novellas and next announcement.

Posted by:CoinYuppie，Reprinted with attribution to:https://coinyuppie.com/the-mathematical-principle-of-automatic-market-maker-amm-algorithm-and-its-future-development-part-1/
Coinyuppie is an open information publishing platform, all information provided is not related to the views and positions of coinyuppie, and does not constitute any investment and financial advice. Users are expected to carefully screen and prevent risks.

Like (0)
Donate Buy me a coffee
Previous 2021-09-11 11:51
Next 2021-09-11 11:54

2021-05-01

2022-10-26

2021-06-29

2021-09-28

2022-10-08

2021-10-16