# Batch Trading & Function-Maximizing AMMs

## Background&#x20;

In traditional financial markets, trading is primarily conducted through order book systems, where liquidity providers place buy and sell quotes to facilitate trades. These markets face significant challenges due to the presence of high-frequency traders (HFTs). One critical issue is "[sniping stale quotes](https://academic.oup.com/qje/article/130/4/1547/1916146)." Liquidity providers maintain quotes around an equilibrium price, but when market conditions change, these quotes can become stale. HFTs race to exploit these stale quotes before liquidity providers can cancel them, leading to inefficiencies. In anticipation, liquidity providers widen their spreads to protect themselves, which reduces overall market liquidity.

To address these inefficiencies, the financial industry has explored the concept of [batching trades](https://www.investopedia.com/terms/b/batchtrading.asp). Instead of continuous trading, time is divided[ into discrete intervals or batches](https://econpapers.repec.org/article/oupqjecon/v_3a130_3ay_3a2015_3ai_3a4_3ap_3a1547-1621.htm). Orders arriving within the same batch are processed without prioritizing speed, encouraging traders to compete on price rather than speed. Batching trades eliminates latency races in traditional finance by changing the nature of competition between arbitrageurs.

There is a strong similarity between LVR and  high frequency trading (HFT)  in the traditional orderbook markets. The research paper titled [Arbitrageurs’ profits, LVR, and sandwich attacks: batch trading as an AMM design response](https://arxiv.org/pdf/2307.02074) aims to adapt the concept of batching from traditional markets to DeFi AMMs and address:

1. CFAMMs trading at a loss whenever there is a rebalancing event similar to sniping stale quotes".
2. Traders are routinely exploited by attackers, most commonly via sandwich attacks in which an attacker front-runs a victim’s swap with the same swap and then back-runs it with the opposite swap.

## Proposed Design: High-Level Overview

The proposed design leverages batching to enhance trade fairness and efficiency, while expanding the design possibilities for AMMs to create more dynamic and effective liquidity provision mechanisms. It incorporates two key elements: **Batching** and a **Function-maximizing AMM.**

1. **Batching Trades**:
   * **Off-Chain Collection**: The system collects trading intents off-chain, which reduces the load on the blockchain and allows for more efficient trade processing.
   * **Batch Processing**: Once trades are collected, they are batched together. Within a batch, trades are settled peer-to-peer as much as possible to maximize efficiency. Any remaining trades that cannot be settled directly are processed through an AMM that is accessible only to the batch.
   * **Uniform Pricing**: By ensuring that all trades within the same batch for the same token have the same price, we eliminate opportunities for traders to exploit price differences, thereby enhancing market fairness and stability.
2. **Expanded AMM Design Space**:
   * **Path Independence**: In traditional AMMs, ensuring path independence is crucial to prevent traders from gaining an unfair advantage by splitting their trades. Our batching mechanism naturally prevents this type of exploitation, allowing us to explore a broader range of AMM designs.
   * **Function-Maximizing AMM**: An **FM-AMM** refers to a type of automated market maker (AMM) that maintains **`clearing-price consistency`**. This means that for every trade executed within this AMM, the average price is designed to be equal to the marginal price after the trade is completed. This flexibility allows the AMM to adapt more dynamically to market conditions, potentially providing better liquidity and more efficient trading outcomes.\
     This innovative AMM design aims to maximize a specific function of its liquidity reserves with each trade. The simplest version of this is maximizing the product of the reserves, but the design can be extended to maximize any function of the reserves.&#x20;

## The function-maximizing AMM

The Function Maximizing AMM (FM-AMM) addresses key challenges faced by Automated Market Makers (AMMs). It enables anyone to submit trades in batches, encouraging competition among traders. This competition acts as a self-correcting mechanism, ensuring $$FM-AMM$$ always trades at the equilibrium price set by a larger market. This eliminates opportunities for arbitrage and manipulative tactics like leverage and sandwich attacks. Within a batch, all trades occur at the same price, further preventing manipulation. Even strategic attempts to move prices across batches are thwarted by arbitrageurs seeking to exploit any price discrepancies.

### Properties of an FM-AMM

* **Maximizing Objective Functions:** A defining aspect of the $$FM-AMM$$ lies in its objective-driven trading approach. By maximizing an `objective function. T`he $$FM-AMM$$ strategically executes trades to optimize outcomes.\
  If the objective function is defined as the product of the two liquidity reserves, then for a given price $$𝑝$$, the FM-AMM determines the amount $$𝑥$$ token to supply by solving the optimization problem:

&#x20;                                             $$x ^{FM-AMM} ​  (p)=argmax _x [{(X−x)(Y+p⋅x)}]$$

* **Comparative Analysis:** Comparing the FM-AMM to its CPAMM counterpart reveals notable disparities. While the FM-AMM generates twice the price impact per trade, it also implements a passive investment strategy, wherein the total value of reserves is evenly distributed between assets. This strategic positioning enhances the FM-AMM's efficacy in capital deployment and risk management.

$$
p^{FM-AMM}(x) \equiv p(x) = \frac{Y - 2x}{x} \\ p^{CP AMM}(x) = \frac{Y - x}{x}
$$

* A traditional CPAMM always trades along the same curve given by $$Y · X$$, while the $$FM-AMM$$ trades as to be on the highest possible curve.
* The $$FM-AMM$$'s trading function is all about keeping things balanced in the market. It uses a carefully designed trading algorithm to make sure that the amount of assets available for trading is in line with what people want to buy and sell. This helps to keep prices stable and fair. Additionally, the $$FM-AMM$$ can work with different investment strategies where the amount of money put into each investment stays the same.&#x20;

$$
p · (X − x^{
FM−AMM} (p)) = Y + p · x^{
FM−AMM} (p).
$$

In other words, for a given $$p$$, the values of the two liquidity reserves are equal after the trade. Therefore, an $$FM-AMM$$ with `product function` trades to implement a passive investment strategy, in which the total value of the two reserves is equally split between the two assets (that is, a passive investment strategy with weights $$1/2, 1/2$$.

<figure><img src="https://3553550185-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FmfykzqcxD3JDEQ5bBuj1%2Fuploads%2F324fQNdY70tZe3JTSA48%2Fimage.png?alt=media&#x26;token=2e2616b7-3b97-468b-b2cd-39f3385833b5" alt=""><figcaption><p>On an FM-AMM, the price at which a given trade x is executed equals the marginal price after the trade is executed. This implies that an FM-AMM “moves up” the curve with each trade.</p></figcaption></figure>

## Why batching trades is necessary?

$$CFAMM$$'s are path-independent: splitting a trade into multiple parts and executing them sequentially does not change the average price of the trade. This property does not hold for an $$FM-AMM$$ because traders can get better prices by splitting their trade. In fact, by splitting their trade into arbitrarily small parts, traders pay approximately the same price as on the corresponding $$CFAMM$$.This is why an $$FM-AMM$$’s trading function can be implemented only if trades are batched.

### FM-AMM vs CFMM (similar fee structure)

* Comparison between  the cumulative returns of a simulated $$FM-AMM$$ with those of the corresponding `Uniswap v3` pool.
* The $$FM-AMM$$'s trading fee matches that of the Uniswap `v3` pool being compared.
* In most high-volume pairs, providing liquidity on the $$FM-AMM$$ consistently outperforms `Uniswap`, except for the $$ETH-USDT$$ 0.05% pool where returns are approximately equal.
* For the largest and most traded Uniswap `v3`pools, providing liquidity is unprofitable as trading fees don't compensate for arbitrage losses.
* In pools with less-traded tokens, results vary, with Uniswap `v3` outperforming FM-AMM on some pairs, but the absolute difference in cumulative returns is generally small.
* Even if the $$FM-AMM$$ receives only 30% of Uniswap `v3`'s total trading volume as noise trading, it can outperform `Uniswap`. This scenario seems plausible given the likelihood of noise trading on `Uniswap` being higher than 30%.

<figure><img src="https://3553550185-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FmfykzqcxD3JDEQ5bBuj1%2Fuploads%2Fp3N2YHXPinJT69uNXjHU%2Fimage.png?alt=media&#x26;token=ba1356c3-85e9-4922-89ca-aa3adaa79d90" alt=""><figcaption><p>Highly traded pairs between ETH, BTC and stablecoins</p></figcaption></figure>

<figure><img src="https://3553550185-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FmfykzqcxD3JDEQ5bBuj1%2Fuploads%2FtFvG6qvE8PcK76ZnFUjK%2Fimage.png?alt=media&#x26;token=3b56c36a-57b3-420f-ba95-de72906ce0ac" alt=""><figcaption><p>Less traded pairs, with Binance prices obtained by combining the prices of the two respective USDT pairs</p></figcaption></figure>

## FM-AMM fees

* **Fee and Rebalancing:** Higher fees in an $$FM-AMM$$ lead to smaller rebalancing trades  that occur at the new equilibrium price.
* **Fee and Arbitrage:** Higher fees can also reduce the likelihood of arbitrageurs rebalancing the pool.
* **Path Dependence and Return:** The frequency of rebalancing impacts LP returns. A single large batch trade may offer less benefit than multiple smaller trades that "move the $$FM-AMM$$ up the curve."
* **Optimal Fee:** In many cases, a **zero fee** is optimal, leading to more frequent rebalancing and potentially higher returns. However, exceptions exist where a positive fee might be better.
* **Comparison with Uniswap v3:** The default fee used in the $$FM-AMM$$ simulation might not be optimal.A zero fee for the $$MATIC-ETH$$ pair outperformed the same fee used in Uniswap `v3`.

<figure><img src="https://3553550185-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FmfykzqcxD3JDEQ5bBuj1%2Fuploads%2FD76arQJxNly8HgOwiFmK%2Fimage.png?alt=media&#x26;token=8711a0ea-ac39-4fc7-a216-bfb217839f65" alt=""><figcaption><p>Return on providing liquidity to an FM-AMM, for different fees: 0.0%, 0.05%, 0.3%, 1.0%</p></figcaption></figure>

## FM-AMM with noise trading

[Heimbach et al. (2024) ](https://arxiv.org/abs/2401.01622)identifies 30% of the total volume on Unswap v3 as non-atomic arbitrage. Also, according to labeling by https://zeromev.org/, sandwich attack and atomic arbitrage volume correspond to 6% of Unswap v3 volume. When extrapolated from Unsiwap `v3` in general to the studied pools, then in each of the pools studiedFM-AMM, approximately 60% of trading volume is noise trading.

<figure><img src="https://3553550185-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FmfykzqcxD3JDEQ5bBuj1%2Fuploads%2F1703QV62gT8DmrA8Uqh8%2Fimage.png?alt=media&#x26;token=e85983d8-a105-4f1c-8fb8-56beae22c2b5" alt=""><figcaption><p>Difference between FM-AMM and Uniswap v3 returns for a full-range liquidity position over 6 months (April 2023 - October 2023) for different scenarios of how much noise trading volume the <span class="math">FM-AMM</span>FM-AMM receives as a proportion of total Uniswap trade volume (approximate noise trading volume). Positive values indicate a higher return on the FM-AMM</p></figcaption></figure>

In all the pools studied, the return of providing liquidity on an $$FM-AMM$$ exceeds that of providing liquidity on `Uniswap` as long as $$FM-AMM$$’s noise trading volume exceeds $$30%$$`30%` of the volume of the corresponding Uniswap pool, which under approximation corresponds to `50%` of that Uniswap pool’s noise trading volume.

## Attack Model

Batching serves as an off-chain component of the AMM, collecting trades and settling them both peer-to-peer and on the $$FM-AMM$$ as a single transaction. However, this introduces a vulnerability: the malicious "`batch operator".`Since the batching process occurs off-chain, this entity has the responsibility of collecting and settling trades. While the smart contract managing the FM-AMM can prevent manipulation by limiting the batch operator to one transaction per block, the operator retains discretion over which transactions are included in the batch. This discretion could be exploited by the batch operator to suppress trades and act as the sole arbitrageur, maximizing their profits. Just as the first arbitrageur reaches a CFAMM after an equilibrium price change, the batch operator holds the exclusive power to rebalance the pool and exploit this opportunity. However, the loss that $$FM-AMM$$’s LP's may face from a malicious batch operator are half of the losses that CPAMM’s LPs routinely face from arbitrageur. It is also possible to introduce punishments on the batch operator in case it misbehaves. There could be social punishments such as LPs withdrawing their liquidity, (and hence making $$FM-AMM$$ useless), automated slashing of dedicated funds, or even legal remedies if the batch operator is a legal entity.

## Conclusion

$$FM-AMM$$ leverages trade batching to achieve several advantages. By eliminating the need for path independence and fostering competition among arbitrageurs, $$FM-AMM$$ captures profits previously enjoyed by arbitrageurs, improves returns for liquidity providers, and eliminates sandwich attacks. Simulations show that $$FM-AMM$$ can outperform existing AMMs like `Uniswap v3`. Furthermore, $$FM-AMM$$ has the potential to significantly reduce `MeV`in DeFi by eliminating arbitrage profits and potentially mitigating liquidation `MeV` in lending protocols.&#x20;
