AMM and PMM Mechanisms and Mathematical Definitions to Avoid Dependency on LOB

Goal

In this section, we will study the basic economics and definitions of the Limit Order Book mechanism and identify its limitations. To resolve these limitations, we will analyze the AMM mechanism. We will examine the fluidity state changes dependent on external data and internal logic through mathematical definitions of the AMM mechanism. Additionally, we will also examine the relationship between the principle of invariants in swaps that occur in liquidity.

I reviewed this paper. SoK: Decentralized Exchanges (DEX) with Automated Market Maker (AMM) Protocols

Limit Order Book Mechanism

LOB (Limit Order Book) ?

  • System used in CEX (Centralized Exchanges) to connect buyers and sellers

  • Buyers and sellers can order at a specific price, and these orders are matched at the exchange based on price and time priority.

  • Buyers can place a "buy" order at a specific price and sellers can place a "sell" order at a specific price.

  • If the orders of the buyer and seller match, the trade is executed at the agreed price.

  • The market price of an asset is ultimately determined by the last matching sell/buy order.

  • Ultimately, it is determined by the acceptance and supply of the asset.

LOB simple economics

  • In finance and economics, LOB has mathematical modeling as a multi-dimensional Markovian system such as continuous-time Markov chain, a stochastic partial differential equation or a queuing network.

  • The system state is generally described as the distribution of limit orders (e.g. price and quantity) and market orders (e.g. reach and trade size) of LOBs.

  • The mathematical formula includes the effects of various market mechanisms such as price formation, order execution, price impact and liquidity provision.

  • A limit order is basically a list of orders placed by a trader to buy or sell a specific asset at a specified price. Supply and demand for a particular asset is indicated by bids (buy orders) and requests (sell orders). The difference between the highest bid and the lowest bid is called the `Spread'.

  • Price Discovery occurs when there is a new order that changes the existing spread between the highest bid and the lowest bid. This can cause prices to change and spreads to narrow or widen. The price at which a trade occurs is the result of the interaction between supply and demand in the market and is the price point where the highest bid price meets the lowest ask price.

  • Market clearing occurs when there is sufficient demand at the current price to satisfy the supply provided by market participants. Prices continue to adjust until the amount of an asset demanded equals the amount supplied.

mathematical generalization model

  • Almgren-Chriss Model

    • A partial differential equation that describes the evolution of the expected price impact of a large market order over time as a function of the order's trading speed and state in the current LOB.
  • Kyle Model

    • It is a continuous-time Markov chain that models the dynamic price impact of a sequence of market orders when executed on a LOB.
  • Obizhaeva-wang Model

    • A stochastic differential equation that describes the evolution of the best bid and ask prices in a LOB, taking into account the effectiveness and strategic behavior of a particular trader.
  • Gatheral Model

    • A partial differential equation that describes the evolution of the expected price impact of a large market order over time as a function of the volatility of the underlying asset and the order's trading speed.

Auto Market Maker, Proactive market maker Mechanism

AMM (Auto Market Maker), PMM (Proactive Market Maker)?

  • AMM is a DEX model that automatically sets asset prices based on supply and demand by utilizing mathematical algorithms.

  • AMMs do not rely on order books, but instead use certain product market maker formulas to price assets. The most commonly used AMM model uses liquidity pools to determine assets.

  • In AMM-based DEXs, liquidity pools act as a single counterparty to each risk through a so-called 'Conservation Function' that algorithmically priced assets by allowing prices to move along a predefined trajectory.

  • Liquidity Providers (LPs) contribute their assets to the liquidity pool

  • Implement a P2P method in which individual users exchange assets with a pool containing input/output assets

  • Individual users get instant liquidity without having to find an exchange.

  • LPs benefit from the supply of exchange fee assets by individual users.

  • By using a “conservation function” for price setting, AMMs make the need to maintain the state of costly order books on a distributed ledger significant.

  • PMM is one type of AMM that uses predictive market techniques to predict the future price of an asset. It incentivizes traders to provide accurate price predictions using market-based mechanisms.

  • PMMs can more accurately adjust asset prices based on projected future supply and demand.

Pros and Cons of (AMM, PMM; LOB)

Limit Order Book

Pros

  • Transparency: The limit order mechanism provides complete transparency in order flow and price discovery. All orders and trades are publicly viewable and traders can easily determine the current market price based on available orders.

  • Price discovery: limit orders provide a way for traders to actively participate in price discovery by placing limit orders at different prices.

  • Fair Pricing: The limit order mechanism ensures pricing is driven by the supply and demand of the underlying asset providing a fair price to all participants.

  • Accessibility: Limit orders are accessible to everyone, including retail traders. No special permissions or minimum order size required.

Cons

  • Latency: The pending order mechanism is dependent on the speed of your computer system and network infrastructure. Long wait times can lead to slow execution times or missed opportunities.

  • Complexity: The limit order mechanism is complex and can be difficult for inexperienced traders to understand.

  • Slippage: Limit orders can experience slippage when the price changes rapidly and the trader's order is not executed at the intended price.

  • Order Management: Traders must carefully manage their orders in the Limit Order Book as they may be partially or not executed at all depending on market conditions.

Auto Market Maker

Pros

  • Liquidity: AMMs can provide liquidity to the market even when trading volume is low.

  • Continuous pricing: AMMs provide continuous pricing, ensuring that buy and sell orders are always available in the market.

Cons

  • Lack of price discovery: AMM does not have a price discovery mechanism such as a limit order book, which can lead to inefficiencies in pricing.

  • Impermanent loss: AMMs may experience impermanent loss, a risk associated with providing liquidity in the market.

  • Dependence on liquidity pools: AMMs rely on liquidity pools, and when the pools are exhausted, the market may lose liquidity.

  • Reliance on smart contracts: AMMs rely on the underlying smart contracts, and errors or bugs in the contracts can lead to significant losses for traders.

Proactive Market Maker

Pros

  • Increased liquidity: PMMs provide increased liquidity compared to traditional market makers because they use algorithms to dynamically adjust positions.

  • Improved price discovery: PMM uses advanced algorithms to determine the best price, so it can provide improved price discovery compared to traditional market makers.

  • Reduced slippage: PMMs use algorithms to dynamically adjust positions and offer tighter spreads, reducing slippage compared to traditional market makers.

  • Reduced market impact: PMMs use algorithms to minimize the impact of trades on the market, thus reducing market impact compared to traditional market makers.

Cons

  • Complexity: PMMs can be complex and traders may need a deep understanding of the underlying algorithms to fully utilize them.

  • Dependence on Algorithm: PMM is dependent on the algorithm used, and errors or bugs in the algorithm can cause significant losses to traders.

Let's learn about the components of AMM

Actor

Liquidity Provider (LP)

  • Liquidity pools can be deployed via smart contracts where the first LP initially supplies crypto assets.

  • After that, other LPs can increase the pool's holdings by adding more asset types included in the pool. receive in turn.

  • Pool shares are part of the total pool and are proportional to the liquidity contribution.

  • LP receives trading fees paid by traders.

  • In some cases, fines are imposed for withdrawal of liquidity, but LPs can freely remove funds from the pool by giving up their stake in the pool.

Trader (Exchange User)

  • Traders send swap orders to the liquidity pool specifying input/output assets and quantities.

  • The smart contract automatically calculates the exchange rate and transaction fee based on the “conservation function” and executes the swap order accordingly.

  • Arbitrageurs: Comparing asset prices in different markets and executing trades whenever a profit can be made by closing the price gap. (User arbitrage through AMM protocol design such as DoDo)

Protocol Foundation

  • It consists of founders, designers and developers who are responsible for designing and improving the protocol.

  • Development activities are often funded directly or indirectly through accrued revenues, so foundation members are financially incentivized to build user-friendly protocols that can attract high transaction volumes.

Assets

For operation and governance, several distinct types of assets are used in the AMM protocol. (One asset can serve multiple roles.)

Risk Assets

  • Risky assets characterized by illiquidity are the main asset types for which AMM-based DEXs are designed.

  • Similar to CEX, AMM-based DEXs can facilitate ‘Initial Exchange Offering (IEO)’ to launch new tokens through the creation of a liquidity pool, a capital-raising activity called ‘Initial DEX Offering (IDO)’ especially suitable for illiquid assets. there is.

  • To qualify as an IDO, risky assets must be whitelisted and must be compatible with the technical requirements of the protocol (e.g. ERC20 for most AMMs in Ethereum).

Base Assets

  • Some protocols require that trading pairs always consist of a risk asset and a specified underlying asset.

  • In the case of Bancor, all risk assets are paired with BNT, the native token of the protocol.

  • In UniswapV1, all pools must be started with ETH and risk assets that make up payers.

  • Many protocols, such as Balanacer and Curve, can link two or more risky assets directly from a liquidity pool without a designated underlying asset.

Pool Share

  • Pool Shares, also known as “Liquidity Shares” or “LP Shares”, represent ownership in a portfolio of assets within the pool and are distributed to LPs.

  • Shares accrue proportionally to transaction fees and can be redeemed at any time to withdraw funds from the pool.

Protocol Token

  • Called “Governance Token” as it is used to represent voting rights on protocol governance issues

  • Protocol tokens are generally valuable assets that can be traded outside of AMM. (e.g. Participation can be encouraged when LPs are rewarded in proportion to liquidity provision.)

  • AMMs compete with each other to attract funds and trading volume.

  • In order to Bootstrap AMM in the initial stage of providing incentives for initial pool establishment transactions, Native Protocol Toke is issued and a function called liquidity mining issued to LPs and Traders is used.

Invariants property of AMM?

  • The method of encoding invariants properties depends on the “Conservation function”. (e.g. Uniswap determines the trading dynamics between assets in the pool.)

  • Preserve the product of value-weighted quantities of the two assets in the protocol

  • Each transaction must be made in such a way that the value removed from one asset is equal to the value added from another.

  • This weight preservation property is one of the invariants properties supported by Uniswap design.

  • AMM generally includes two types of interaction mechanisms: asset exchange of assets and liquidity provision/withdrawal.

  • The interaction mechanism must be specified in such a way that the desired invariants properties are maintained. Thus, the class of permissible mechanisms refers to a “defined conservation function” or is otherwise limited to preserving defined properties.

AMM basic economics

Reward

There are several reward schemes, including liquidity guarantees, staking rewards, governance rewards, and security rewards distributed to various actors to incentivize participation and contribution.

Liquidity Reward

  • LPs are compensated for supplying assets to liquidity pools as they have to bear the opportunity cost associated with funds locked in the pool.

  • LPs receive their own allocation of trading fees paid by traders.

Staking Reward

  • In addition to liquidity rewards in the form of trading income, LPs are offered the possibility to stake a pool stake or other tokens as part of an initial incentive program for a specific token protocol.

  • The ultimate goal of the Individual Token Protoc (GIV, TRIPS) is to promote token liquidity for swaps and product usage while further incentivizing token holdings.

Governance Right

  • Liquidity provision and swaps can be encouraged by rewarding participants with governance rights in the form of protocol tokens.

  • Governance issues such as protocol fund management are proposed and discussed on off-chain governance portals such as snapshot.org, tally.xyz, and boardroom.io.

  • Protocol tokens exercise voting rights to vote on proposals.

Security Reward

  • Ethereum's AMM-based DEX suffers from security vulnerabilities, and in addition to code audits, a common practice adopted by the protocol foundation is to audit code from the broad developer community and reward those who find and fix bugs in the protocol.

Explicit Costs

Various costs arise, including fees for some form of “value” or “service” performed, and fees for interacting with a blockchain network. AMM participants should expect three types of liquidity withdrawal penalties, swap fees and gas fees.

Swap Fee

  • Users interacting with liquidity pools for token exchanges must repay LPs for asset supply and quarterly losses.

  • This reward comes in the form of a swap fee that is charged on every swap transaction and then distributed to the liquidity pool.

  • A portion of share holders swap fees can be used as the basis for AMM to further develop the protocol.

Gas Fee

  • All interactions with the protocol are executed in the form of on-chain transactions, so gas fees that apply to all transactions on the underlying blockchain apply.

  • Verification nodes must be rewarded for their consensus efforts, and transaction initiators must cover these operating costs.

  • Interacting with complex protocols incurs higher gas fees due to the higher computational power required to confirm transactions.

Implicit Costs

The two essential implicit costs inherent in AMM-based DEXs are slippage, exchange users and divergence loss for LPs.

Slippage

Slippage
Slippage
  • Since other transactions can be included in the actual transaction as shown in the figure above, it means the allowable range up to the transaction. (Slippage is DEX 0.1 ~ 0.3%, DEX Aggregator 1.0%)

  • It is defined as the difference between the spot price and the transaction realization price.

  • Instead of matching buy and sell orders, the AMM determines the exchange rate on a continuous curve, and all trades face slippage depending on the size of the pool and the trade size for the correct proposition of the “Conservation Function”.

  • The spot price approaches the realized price of very small trades, but the larger the trade size, the more it deviate.

  • This effect is amplified in smaller liquidity pools as every transaction leads to a higher slippage which has a significant impact on the relative amount of assets in the pool.

  • Due to continuous slippage, AMM's transactions can be exploited to perform sandwich attacks, so it is necessary to set a slippage error to some extent.

Divergence loss

Divergence loss
Divergence loss
  • In the case of LP, the assets provided to the protocol are still exposed to volatility risk, which applies together with the loss of time value of locked funds.

  • Swap automatically updates the asset price implied by the pool's “conservation function” by changing the asset structure of the pool.

  • As a result, the value of the entire pool changes.

  • Compared to holding an asset outside of an AMM pool, donating the same amount of an asset to the pool in exchange for a stake in the pool may result in a lower value for price fluctuations.

  • A loss can be considered “impermanent” because it is only realized when the asset is actually taken out of the pool as the depreciation of the pool's value continually vanishes and reappears as the asset's price moves back and forth.

  • A well-designed AMM charges an appropriate swap fee to ensure that LPs are fully compensated for divergence loss.

  • Because the assets are combined in one pool, a change in the price of one asset affects all other assets in this pool. In the case of AMM protocols supporting single asset supply, this exposes LPs to risky assets that they did not hold in the first place.

Formalization of AMM Mechanisms

State Space Representation

  • Can be modeled using the term blockchain-based system. States and agents constitute the major system components. You can check the activity of the protocol through the figure below.

  • The evolution of the system over time is modeled as a state transition function.

State Space Representation
State Space Representation
  • Of interest is the state X of the liquidity pool, which can be described in the generalized way below.
Liquidity pool State X
Liquidity pool State X
  • This formalization may include various AMM designs. The most important design component of AMM is Conservation Function which defines the relationship between different state variables and Invariant(s) I.

  • “Conservation Function” treats the way protocols are followed because each protocol prioritizes its own functions and tries to target specific functions.

Liquidity provision and withdrawal

Liquidity provision and withdrawal
Liquidity provision and withdrawal

Liquidity Swap

Liquidity Swap
Liquidity Swap
  • The key to the health of the AMM system is the quantity of each asset held in the liquidity pool. Common Candidates for Invariants of Constraints or Products

generalized formula

  • We will demonstrate the interdependence between various AMM Invariants and state variables. We will generalize the AMM formulas needed to calculate slippage and divergence losses.

  • Below is a table of mathematical notations and definitions.

mathematical notations
mathematical notations
  • Hyperparameter Set, which is determined at the time of pool creation and remains the same afterwards. The values of hyperparameters are changed by protocol governance activities, but should not be changed frequently.

liquidity pool state change (liquidity change, swap)

  • Invariant I, which remains constant only in swap operation. It represents the pool variable that changes when liquidity is provided and withdrawn. Conversely, trading moves the price of an reserve and, in particular, increases the price of an outgoing reserve relative to a deposited reserve, reflecting an increase in the value of an outgoing reserve driven by demand.

    • On the other hand, liquidity provision and withdrawal should not move the reserve price. In particular, pure liquidity supply and withdrawal activities require a proportional change in reserve.

    • Due to pure liquidity changes and reserve swaps, the state transition is formally expressed as:

Liquidity Pool State change && Swap
Liquidity Pool State change && Swap

Conservation function

Conservation function
Conservation function
  • The AMM Conservation function, also called “bonding curve”, is a relationship function between AMM Invariants and reserve quantities, and can be expressed as above (*).
uniswap conservation function
uniswap conservation function
  • Like ri->ro, the conservation function for each token pair must be concave, non-negative, and non-decreasing. For complex AMMs like Curve, it is convenient to implicitly express a Conservation function to derive the exchange rate between two reserves in the pool.

Bonding Curve

  • A financial algorithm that controls the supply of tokens

  • Generally used when distributing tokens of blockchain-based projects or DAOs

  • When a coin seller sells a coin, it has a function of automatically adjusting the price.

  • Initially, the price is low when selling coins, but as the number of coins decreases, the price goes up.
    -> In this way, rewards are provided to those who buy coins quickly
    -> You can get the effect of imposing a penalty on people who buy coins late.

  • The equation below includes Invariants, I, whose value is determined by the initial liquidity provision (liquidity pool creation).

  • If the reserve quantity of one reserve is changed later, the reserve quantity of another reserve can be resolved.

Init Liquidity Pool create Invariants
Init Liquidity Pool create Invariants

Spot Exchange Rate

  • The spot exchange rate between token i and token o can be calculated as the slope of the ri-ro curve using partial derivatives of the conservation function Z.
spot exchange rate
spot exchange rate

Swap amount

  • When xi < 0, the amount of token o consumed and the amount of token consumed by xi (receive xi < 0) can be calculated according to the following steps.

  • Note xi > -ri , xo > -ro

  • Their lower bound is in case the received reserve is depleted from the pool. That is, the new reserve price becomes zero.

  • With common AMM protocols, xi,xo often has no theoretical upper bound.

  • If the reserve quantity is 1 unit, a trader can sell more than 2 units to the pool, but most often with high slippage.

Update reserve quantities

Update reserve quantities
Update reserve quantities
  • When swapping, explain the quantity of tokens used for the swap. Tokens used for swap are token i and o. At this time, if you use the quantity of token i as much as xi, you can get token o as much as xo.

  • At this time, if the quantity of token i before swap is ri, the quantity of token i after swap is ri + xi.

  • The quantity of other tokens not used in the swap does not change.

  • The input quantity xi is simply added to the existing token i reserve.

  • The reserve quantity of tokens other than token i and token o remains the same.

Compute new reserve quantity of token o

  • The new reserve of all tokens except token o can be checked in the previous step.

  • It is possible to solve r’o, which is an unknown quantity of token o, with a conservation function.

unknown quantity solve conservation function
unknown quantity solve conservation function
  • This is the process of setting the value to 0 so that the total balance of all swapped tokens is constant. That is, it expresses a constant that the amount of reserve tokens must be constant.
reserve token must be constant
reserve token must be constant
  • r’o origin reserve composition {rk}, input quantity xi

  • New reserve balance r’o of swapped token o can be calculated through origin reserve balance {rk} and exchanged token i amount xi

Compute Swapped quantity

Compute Swapped quantity
Compute Swapped quantity
  • Calculate the token o swap amount as the difference between old and new reserve quantities.

Slippage

  • Slippage measures how far the exchange rate deviates from the effective exchange rate.

  • Calculated by subtracting 1 from the effective exchange rate (ratio of input quantity xi and swap quantity xo) and the pre-swap spot exchange rate.

  • In other words, measure deviation by comparing spot and effective exchange rates

  • If the value is 0, it indicates no deviation or no slippage, and the higher the value, the larger the deviation and the higher the slippage.

  • Slippage measures the difference between the exchange rate before the transaction and the effective exchange rate after the transaction. The higher the exchange rate before the transaction, the higher the probability of slippage. Conversely, the higher the effective exchange rate after a transaction, the less likely it is that the slippage will increase.

Slippage calc
Slippage calc

Effective Exchange rate It represents the rate at which a specified amount of one currency can be exchanged for another currency, after taking into account any fees or costs associated with the exchange. This is the actual exchange rate you receive when you exchange money.

Spot Exchange rate It is the exchange rate at which one currency can be exchanged for another currency at the current market rate. Rates quoted in the financial press and used by banks and other financial institutions to exchange currencies

Divergence loss

  • Describes how much the value of reserve held in the reserve pool decreases compared to holding them outside the reserve pool according to the change in reserve price (considered opportunity cost).

  • This can be calculated based on spot price and swap quantity.

  • To do this, set token i as the standard token and calculate considering the case where token o increases by o.

Reserve Value
Reserve Value

Calculate the original pool value

  • This formula is for calculating the value of the pool “V({rk};I)” is the value of all token reserves in the pool expressed as token i.

  • The value of each token reserve is obtained by multiplying the number of tokens by the swap ratio with token i and adding the value of each token reserve to the original value.

Calculate the reserve value if held outside of the pool

Calculate the reserve value if held outside of the pool
Calculate the reserve value if held outside of the pool
  • If outside the pool, it displays the value of token o reserve when the value of token o changes by p. This allows the value of the pool to be compared to if it were outside the pool.

Obtain re-balanced reserve quantities

  • The process of obtaining rebalanced reserve quantities is used to adjust the amount of various assets in the pool so that the value remains stable.

  • This is done by swapping “cheap”, assets for “expensive” assets.

  • Exchange rates between different assets in a pool can be calculated using a series of equations.

  • The new value of the pool may be calculated by summing the product of the new reserve quantities multiplied by the new price of each asset in the pool.

  • The divergence loss is a measure of how much the value of the pool has changed as a result of these adjustments. It is calculated by comparing the new value of the pool to the original value.

exchange rate, conservation function
exchange rate, conservation function
  • It is an expression for the exchange rate. This formula expresses the exchange rate according to new reserve quantities and varies according to the composition of the pool.

  • The formula below is an expression for the conservation function and represents what is maintained according to new reserve quantities “({r’k})”.

  • Expression for new reserve quantities “({r’k})”. Exchange rate (p), a function that can calculate new reserve quantities using origin reserve quantities ({rk}) Rk is expressed as follows.

Calculate the new pool value

new pool value
new pool value
  • This formula calculates the new pool value by taking the new price of each token (token i) multiplied by the new reserve price. where V’ represents the new pool value, iEj represents the new reserve price of token j, and r’j represents the new reserve price of token j.

Calculate the divergence loss

Calculate the divergence loss
Calculate the divergence loss
  • Used to calculate divergence loss. It represents the difference between the new value of the pool (V') and the original value of the pool (Vheld) after rebalancing of reserve quantities.

  • The variable p represents the change in the value of an asset in the pool. Then, calculate the ratio of the new value of the pool (v') to the original value of the pool (vheld) and subtract 1 from it. This resulting number can measure how much the pool's value has changed as a result of the rebalancing.

Conclusion

Research is underway to solve the problems of the Limit Order book mechanism, and various protocols are emerging based on the top protocols such as uniswap, curve, balancer, dodo, etc. based on the AMM mechanism. Most of them are forks of the Uniswap function, but the reason is that AMM characteristics allow for easy addition and modification of various additional services. Previously, we defined the AMM mechanism mathematically and looked into liquidity change rate, the law of immutability, state change, and swap calculation.

In the next session, we will look at the unique characteristics of the AMM-based DEX applications Uniswap, Curve, Balancer, and check various issues at the network, contract, and application level with a focus on vulnerabilities.

Reference

Subscribe to Zer0Luck
Receive the latest updates directly to your inbox.
Mint this entry as an NFT to add it to your collection.
Verification
This entry has been permanently stored onchain and signed by its creator.