<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Stefan Loesch on Medium]]></title>
        <description><![CDATA[Stories by Stefan Loesch on Medium]]></description>
        <link>https://medium.com/@odtorson?source=rss-b8621923f1b5------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*Xn9RzXxiqGZktjEqJh0C_w.png</url>
            <title>Stories by Stefan Loesch on Medium</title>
            <link>https://medium.com/@odtorson?source=rss-b8621923f1b5------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 16 Nov 2026 06:19:26 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@odtorson/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[No sandwiches allowed — how to prevent MEV attacks]]></title>
            <link>https://medium.com/carbondefi/no-sandwiches-allowed-how-to-prevent-mev-attacks-7e91ec7d0eb4?source=rss-b8621923f1b5------2</link>
            <guid isPermaLink="false">https://medium.com/p/7e91ec7d0eb4</guid>
            <category><![CDATA[english]]></category>
            <category><![CDATA[mev]]></category>
            <category><![CDATA[crypto]]></category>
            <category><![CDATA[carbondefi]]></category>
            <category><![CDATA[amm]]></category>
            <dc:creator><![CDATA[Stefan Loesch]]></dc:creator>
            <pubDate>Fri, 11 Aug 2023 12:53:43 GMT</pubDate>
            <atom:updated>2023-08-11T12:53:43.101Z</atom:updated>
            <content:encoded><![CDATA[<h3>No sandwiches allowed — how to prevent MEV attacks on AMMs</h3><p><em>This is a follow on post of my </em><a href="https://medium.com/carbondefi/carbon-the-mev-sandwich-is-toast-2ec7800dde68"><em>initial post</em></a><em> on how Carbon (and the big virtual fees inherent in a Carbon’y position) make sandwich style MEV attacks impossible, and Mark’s subsequent posts that </em><a href="https://medium.com/carbondefi/the-optimum-sandwich-how-to-exploit-blockchain-enthusiasts-with-arbitrary-precision-e9131a2562b5"><em>quantified this</em></a><em>, and </em><a href="https://medium.com/carbondefi/the-forbidden-sandwich-a-theory-of-mev-resistant-cfmm-transactions-a582efd98c98"><em>looked at what those formulas imply</em></a><em>. This post is more of a lab notes style post that works with some of the formulas in Mark’s </em><a href="https://medium.com/carbondefi/the-forbidden-sandwich-a-theory-of-mev-resistant-cfmm-transactions-a582efd98c98"><em>latest article</em></a><em> and discusses them further.</em></p><h3>Background</h3><p>The key formulas that we are working with here are</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*BG7Xghw4iQtwaGbB.png" /><figcaption>Sandwich profit Q as a function of the other parameters</figcaption></figure><p>from <a href="https://medium.com/carbondefi/the-optimum-sandwich-how-to-exploit-blockchain-enthusiasts-with-arbitrary-precision-e9131a2562b5">article 1</a>, and</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qFPQLNn4jJSxpqXgMwbyDg.png" /><figcaption>Relationship between parameters when sandwich profit is zero</figcaption></figure><p>from <a href="https://medium.com/carbondefi/the-forbidden-sandwich-a-theory-of-mev-resistant-cfmm-transactions-a582efd98c98">article 2</a>.</p><p>Before we go further into those equations, I want to take a moment to define the symbols used as this will greatly aid the understanding of the formulas</p><ul><li><em>Q</em> is the profit an attacker makes with a sandwich attack that is based on the other parameters below, and</li><li>Δ<em>x</em>ₐ is the size of the front-running trade that leads to this particular value of Q. The trade parameters are</li><li>Δ<em>x</em>ᵤ which represents the size of the user trade in token terms,</li><li><em>x</em> which represents the size of the pool in the same units as the Δ<em>x</em> (virtual size in case of levered pools, but this analysis ignores the stuck-at-the-boundary implications of levered liquidity), and most importantly</li><li><em>δ </em>represents the percentage fee of the pool (in decimal terms, eg 10bp = 0.001)</li></ul><p>The key equation we will be looking at here is the second equation above. It is obtained from the first one by first deriving with respect to Δ<em>x</em>ₐ, and then requiring that the derivative of <em>Q</em> with respect to Δ<em>x</em>ₐ vanishes at Δ<em>x</em>ₐ=0. This condition ensures that Δ<em>x</em>ₐ=0 is optimal for the potential sandwich attacker, in other words, there is no arbitrage profit.</p><h3>Simplifying the formula</h3><p>We see that the formula above, as written, consist of three terms, the first two of which are trivial because they yield solutions that are not financially interesting. One of those terms shows that an empty pool (<em>x</em>=0) does not allow for sandwich attacks, and the other solution is at an unreasonably big value of Δ<em>x</em>ᵤ and can therefore be discarded. We are therefore left with the operation part of the equation which is as follows</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/738/1*_Uw1eJ-TCQG3ahkf9n1XwQ.png" /><figcaption>Operational part of the second equation above</figcaption></figure><p>To paraphrase what Mark discusses in his article, the above condition should not be an equality but an inequality because of course attackers will never engage in loss making transactions. Therefore</p><ul><li><em>δ </em>is really inf<em> δ</em> as any fee &gt;<em>δ </em>will also prevent sandwiching</li><li>Δ<em>x</em>ᵤ is really sup Δ<em>x</em>ᵤ as any trade &lt;Δ<em>x</em>ᵤ will also prevent sandwiching, and</li><li><em>x </em>is really inf<em> x </em>as any pool liquidity &gt;<em>x</em> will also prevent sandwiching</li></ul><p>Mark has in his article solved the above equation for <em>δ, </em>Δ<em>x</em>ᵤ and <em>x, </em>yielding the following formulas</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*ZZ2EwN5bBmJXeGWU.png" /><figcaption>Formulas from article 2</figcaption></figure><p>For us the first of the three formulas above is the most interesting one — <strong>it indicates how big the fee has to be for a given trade so that sandwich attacks no longer make sense</strong>. I slightly rewrote it into the new notation, indicating that the no-sandwich-possible conditions holds for this fee level <em>δ </em>and above</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Y8ko12yjIoDdewBFZWw_aQ.png" /><figcaption>Fee levels that do not allow for a sandwich attack</figcaption></figure><p>This formula looks disappointingly complex — but fortunately it has a nice asymptotics for big values of r=x/Δ<em>x</em>ᵤ (aka small trades):</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_iYGp5IH3sbPvDlEQzovXA.png" /><figcaption>Asymptotic behaviour of the minimum resistant fee level for small trades (r=x/Δ<em>x)</em></figcaption></figure><p>In the chart below the red line is the actual curve, the blue line is the power law asymptotics <em>1/r</em>, and the green line is the (massively) improved asymptotics <em>2/2r+3</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kzao6qtbLvRsfZsmYjVjgQ.png" /><figcaption>Minimum no-sandwich fee as a function of r=x/Δ<em>x</em></figcaption></figure><p><em>(see here for the underlying </em><a href="https://www.desmos.com/calculator/pkmg14evcl"><em>desmos calculator</em></a><em>)</em></p><p>Whilst <em>r=x/</em>Δ<em>x</em>ᵤ works better for the formulas, financially the more intuitive quantity is the <strong>liquidity-normalised trade size</strong> 1/r = Δ<em>x</em>ᵤ<em>/x. </em>It is important to keep in mind that this is also the percentage slippage, ie the amount by which a trade of size <em>Δx </em>adversely pushes the price of a pool of size <em>x</em>.</p><p>Therefore we find the following, important result:</p><h3><strong>Minimum fee levels so trades cannot be attacked</strong></h3><p><strong>Small trades (1% of pool size or less) can not be attacked by sandwich attacks if the fee level is bigger than the slippage (which is also the liquidity-normalised trade size)</strong>, ie <em>δ&gt;</em>Δ<em>x</em>ᵤ<em>/x. </em>For slightly bigger trades — up to about 10% slippage — the approximation <em>δ&gt;2/(2r+3) </em>works well, and beyond that the full formula [2] above should be used.</p><h3>Maximum trade size that can’t be attacked</h3><p>Similarly we can look at the maximum viable trade size as a function of the fee level that cannot be sandwich attacked. We start with equation [3] from article 2 above but we divide both sides by <em>x</em> and by <em>δ. </em>We recall that Δ<em>x</em>ᵤ<em>/x </em>is the (liquidity-normalised) trade size, and therefore the new LHS of the equation Δ<em>x</em>ᵤ<em>/xδ </em>is the normalised trade size (also: slippage) divided by fees.</p><p>We have charted the RHS of the above equation below</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*aCOUqZ4bA4JmFtRmfU8Lgw.png" /><figcaption>Maximum normalised trades size relative to fees as a function of fees</figcaption></figure><p>(see this chart <a href="https://www.desmos.com/calculator/9ibwzjnpca">on desmos</a>)</p><p>The way to interpret the above chart is as follows: for a given level of fees (here 0.2 = 20% fees), what is the maximum normalised trade size as a percentage of fees? For small for small values this number is unity, ie <strong>for small fees the maximum non-sandwichable normalised trade size equals the fees level</strong>. If fees are bigger then the possible trade size increases disproportionally. Eg at 20% fees the trade size can be 20%*1.4=28% of pool size before it is sandwichable.</p><p>We should note however that this increase in trade sizes only happens for rather large fee levels. Below a slightly more reasonably view on this graph with fee levels up to 5% where the improvement is linear at about 5% for every 3% of fees and therefore below 10% at a 5% fee level, ie not particularly meaningful when compared to a base value of 100% (and definitely not at fees &lt; 1%).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fVSjJx1FiyuarjnGUm2FOQ.png" /><figcaption>Same graph but with fee levels only up to 5%</figcaption></figure><p>—</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Ppij34culFiKkjI_.jpg" /><figcaption>Title Image</figcaption></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7e91ec7d0eb4" width="1" height="1" alt=""><hr><p><a href="https://medium.com/carbondefi/no-sandwiches-allowed-how-to-prevent-mev-attacks-7e91ec7d0eb4">No sandwiches allowed — how to prevent MEV attacks</a> was originally published in <a href="https://medium.com/carbondefi">CarbonDeFi</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Carbon — the MEV sandwich is toast]]></title>
            <link>https://medium.com/carbondefi/carbon-the-mev-sandwich-is-toast-2ec7800dde68?source=rss-b8621923f1b5------2</link>
            <guid isPermaLink="false">https://medium.com/p/2ec7800dde68</guid>
            <category><![CDATA[carbon]]></category>
            <category><![CDATA[defi]]></category>
            <category><![CDATA[amm]]></category>
            <category><![CDATA[english]]></category>
            <category><![CDATA[mev]]></category>
            <dc:creator><![CDATA[Stefan Loesch]]></dc:creator>
            <pubDate>Mon, 31 Jul 2023 07:47:34 GMT</pubDate>
            <atom:updated>2023-08-10T09:46:35.224Z</atom:updated>
            <content:encoded><![CDATA[<h3>Carbon — the MEV sandwich is toast</h3><p><em>Note: my colleague Mark has taken this topic much further and doing the hard work. In his </em><a href="https://medium.com/carbondefi/the-optimum-sandwich-how-to-exploit-blockchain-enthusiasts-with-arbitrary-precision-e9131a2562b5"><em>first post</em></a><em> he calculates the actual formulas underlying the assertion that large enough fees prevent sandwich attacks that is made in this article here, and in his </em><a href="https://medium.com/carbondefi/the-forbidden-sandwich-a-theory-of-mev-resistant-cfmm-transactions-a582efd98c98"><em>second post</em></a><em> he looks much closer into what those formulas actually mean.</em></p><p>When discussing Carbon you will often hear the claim that “there is no MEV on Carbon” or that “Carbon is MEV resistant, specifically to sandwich attacks”. As usual, this is more complex than those simple statements allow for, which is why I want to discuss this topic here in more detail. The TLDR is — a typical Carbon strategy is indeed resistant to sandwich attacks, which is the most common form of MEV. However — not all strategies are. This is of course not surprising as Carbon strategies are a strict superset of Uniswap v3 positions, and Uniswap v3 positions are vulnerable.</p><h3>How Carbon works</h3><p>In order to make this note self consistent, here is a brief description of how Carbon works (please feel free to skip this section if you are already familiar with it).</p><p>Every Carbon <strong>strategy</strong> consists of two <strong>orders</strong>, one <strong>buy order</strong> (eg buy ETH for USDC) and one <strong>sell order</strong> (eg sell ETH for USDC) and of course buying should happen at a lower price (for the strategy owner) than selling, otherwise the strategy will be emptied quickly by the market. Which is why a Carbon strategy is often referred to as a <strong>buy-low-sell-high strategy</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*R3TrTN1c73p8EVeHzheYrw.png" /><figcaption>A Carbon “Strategy”: Buy Low, Sell High</figcaption></figure><p>Orders can be <strong>single-price orders</strong> aka <strong>limit orders</strong> (buy ETH for USDC at 2000 USDC per ETH) or <strong>range orders</strong> (ditto between 2000 and 1800 USDC per ETH, starting at 2000). The <strong>volume</strong> of an order is always determined by the token being sold, and for not too wide ranges one can approximate range orders with easier-to-reason-about sets of equally-sized single-price orders (buy 10 USDC worth of ETH at 2000, 10 at 1999, 10 at 1998, …, 10 at 1900). A strategy can either be any combination of two opposing limit or range orders, ie a <strong>recurring strategy</strong>, or it can execute only once either buying or selling, again in range or limit format, and then stop, ie be a <strong>disposable strategy</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nYOcRj9sxwVGSLecIP2CTQ.png" /><figcaption>Range Sell Order: Sell (approximately) the same amount at every tick between 100–105</figcaption></figure><h3>MEV, arbitrages and sandwich attacks</h3><p><strong>MEV</strong> used to stand for “Miner Extractable Value”, but this was changed somewhat inelegantly to “<strong>Maximum Extractable Value</strong>” when people realized that miners are not the only one who can influence block production and in particular transaction sequencing. MEV corresponds to the value that players in the block production chain can extract from submitted transactions by virtue of choosing where and when to include them into a block, and what other transactions to include ahead or after them.</p><p>Arguably the two most important MEV-able transactions in relation to online trading are arbitrage snipes and sandwich attacks. The case of <strong>arbitrage snipes</strong> has been nicely described by Dan Robinson in his <a href="https://medium.com/@danrobinson/ethereum-is-a-dark-forest-ecc5f0505dff">Dark Forest Medium post</a>. Arbitrages (on-chain) are by definition transactions that can be submitted by everyone and that yield a guaranteed profit. Dealing with those is hard, and Carbon does not offer any particular protections in this respect.</p><h4>No-fee sandwich attacks</h4><p>The more interesting case is that of <strong>sandwich attacks</strong>. Those are akin to front running in tradfi markets. Their mechanics are as follows: assume that a trader submits a transaction to sell 1,000 TKN for USDC on a constant-product AMM like Uniswap v2 or Bancor. Further assume that this (a) is currently the only such transaction in the mempool, (b) there are no fees, and (c) the current price after slippage is 100, so the trader gets 100,000 USDC. A sandwich attacker would front and back run this transaction, meaning that they would (1) sell a large amount of TKN on the exchange, then (2) insert the transaction into this “sandwich” and then (3) buy the same amount of TKN back.</p><p>The sell transaction (1) will have pushed the price in the AMM lower, and we assume (d) that the sandwiched transaction (2) has now been executed at a price of 90 after slippage rather than 100, so the trader only gets 90,000 USDC. Because after transaction (3) the AMM is in exactly the same state as after only executing the un-sandwiched transaction, this is a zero sum game, so the 10,000 USDC loss of the trader is a 10,000 USDC gain of the sandwichooor.</p><p>This is the essence of a sandwich attack: the attacker pushes the price of a submitted transaction into a less favorable area, and keeps the difference. It is easy to see that whoever controls the sequencing — and therefore can ensure that all three transactions are included in the right order — can make a lot of money from unsuspecting traders.</p><h4>Sandwich attacks in the presence of gas</h4><p>In the presence of gas, transactions (1) and (3) are not costless, but instead incur a constant cost, ie a cost independent of the volume traded. As the gain on the sandwich attack is always proportional to the volume it is clear that the attack is not viable below a certain minimum volume. For a standard constant product case this volume is very low and likely to be exceeded, but for the other cases discussed below this may differ.</p><h4>Sandwich attacks with concentrated liquidity</h4><p>Provided the attacker has enough liquid funds — flash loans do not work here because all three transactions are individually signed and the loan can only be paid back in transaction (3) — the gain in a constant product scenario is in principle unlimited: with sufficient liquidity the attacker can push the price to a point where the trader sells their token for (almost) nothing, so the attacker gains (almost) the entire amount the trader was sending into the AMM.</p><p>A concentrated liquidity AMM runs out of liquidity at a finite and non-zero price, so the maximum amount the attacker can contribute under (1) is such that the attacked transaction (2) just does not fail. This sets a minimum or maximum execution price for this transaction, and therefore a maximum profit that can be achieved with a sandwich attack.</p><h4>Sandwich attacks in the presence of fees</h4><p>The presence of fees changes the above analysis in that an AMM can never return to its original state because every transaction will leak value in terms of fees that accrue to the LPs. This fee can either be capitalized (ie increase the amount of liquidity in the AMM) or distributed which changes the exact mechanics of the transaction, but which does not make a practical difference for our analysis.</p><p>Even in a constant product case, fees may make a sandwich attack not viable if the pool is very liquid. The reason is that the profit generated is proportional to the slippage generated and the amount of TKN in the sandwiched transaction, whilst the fees paid are proportional to the amount of TKN in the attacking transaction. For very liquid pools the fees paid — in currency terms, not in percentage terms — may outpace the profits generated by the additional slippage they generate. In case of concentrated liquidity — which massively increases the “virtual” liquidity of the pool and reduces slippage— this effect is of course even stronger.</p><h3>Sandwich attacks on Carbon</h3><h4>Carbon strategies and fees</h4><p>We have discussed above how Carbon works, specifically how recurring strategies that recycle liquidity between sell and buy curves work. For simplicity, we will first look at strategies which are composed of single-price orders where all the buying and selling happens at a single price. Furthermore, we first consider a rather narrow strategy, like “buy at 99, sell at 101” or even “buy at 99.9, sell at 100.1”. It is clear that, as far as the trader trading against this strategy is concerned, those are trades “at 100” with fees of 1% or 0.1% respectively. There is of course no qualitative difference between a 99/101 strategy, and a 50/150 or even a 1/199 one. Mathematically they can all be expressed as mid-price plus/minus a fee — again, only as far as the taker trader is concerned. So whilst those strategies would not usually be thought of as “mid plus/minus fees”, mathematically they are.</p><p>For Carbon <em>ranges</em>, this still more or less holds true. If we stick to the interpretation that a range is “$1 at 100, $1 at 100.1 and $1 at 100.2” etc then the mid and fee are somewhat dependant on how the range has been exhausted / refilled, ie the mid and the fee are not constant but change over time when the state of the strategy changes. This is more relevant for wider ranges — eg “buy 99–89.9, sell at 100–100.1” is essentially still a range with mid 100 and fee about 1%. In summary — the mid plus/minus fee view still applies, except it changes over time with the state of the strategy.</p><h4>Sandwich attacks on Carbon</h4><p>As we just have seen, Carbon strategies can be seen as concentrated liquidity AMMs with, usually very large, fees. As we have seen above, for concentrated liquidity positions with large fees, sandwich attacks are typically not viable. So the short version here is: typical Carbon ranges can not be viably attacked using sandwich attacks; however, very narrow overlapping ranges — which are possible in Carbon but not very “Carbon’y” — may still be susceptible to sandwich attacks.</p><p>It is worth looking at a number of specific examples. The first one is a very “Carbon’y” strategy, say buying ETH for USDC between 1,800–1,500, and selling it back between 2,200–2,500, and we assume the strategy is currently fully funded in USDC. In this case, the first USDC converted to ETH will be at 1,800, and it will be placed on a curve selling it back at 2,200. Firstly — the strategy owner here is a maker, so they can not be front run at all. They expressed the “intent” to buy and sell in two specific ranges, and this intent will either be fulfilled or not. Ex post they may of course no longer like this intent — say if ETH goes all the way down to 1,000 then having bought between 1,800–1,500 looks like a bad idea in hindsight — but this is no different from any other trading decision.</p><p>The question we are trying to answer here is whether <em>takers</em> trading against Carbon strategies can be sandwiched. Takers in the above model <em>sell </em>the first dollar worth of ETH at 1,800 and the last at 1,500. In other words, their price gets increasingly worse, and someone front running them does take money away from them. The issue is that anyone front running them, ie selling ETH ahead of them in step (1), must buy back this ETH in step (3). In this situation the ETH is placed back for sale at 2,200, ie at a price difference of 400 initially, and 1,000 at the end. This difference, which is a cost to the attacker, is too big to pay for the cost increase imposed on the taker in step 2, and therefore the sandwich attack is not viable.</p><p>However, if we have a strategy buying at 2000–1500 and selling at 1501–2001 (meaning the buy and sell ranges are overlapping, and the implied fee is around 5bp) then this behaves very similar to a 5bp Uniswap v3 range, and a sandwich attack is possible.</p><h3>Conclusion</h3><p>Sandwich attacks work best on constant product AMMs with no fees. Both introducing concentrated liquidity and fees makes sandwich attacks less profitable, with the profitability being the lower the higher the concentration and the higher the fees. Beyond certain points profitability is negative, ie the attack is no longer viable.</p><p>Carbon strategies can be mathematically thought of as AMM strategies with a current mid price and fee, both the price and the fee changing when trades happen against a strategy. For typical Carbon strategies those parameters are such that sandwich attacks are not viable. For others — in particular those mimicking Uniswap v3 positions which are a subset of Carbon strategies — sandwich attacks are however viable and therefore possible.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*iuLpExK5VL8ZB_Mk6dlq_g.jpeg" /><figcaption>Cover Image</figcaption></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2ec7800dde68" width="1" height="1" alt=""><hr><p><a href="https://medium.com/carbondefi/carbon-the-mev-sandwich-is-toast-2ec7800dde68">Carbon — the MEV sandwich is toast</a> was originally published in <a href="https://medium.com/carbondefi">CarbonDeFi</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Using Convex Optimization for Optimal Routing and Arbitrage in Carbon]]></title>
            <link>https://medium.com/carbondefi/using-convex-optimization-for-optimal-routing-and-arbitrage-in-carbon-5f07f526604f?source=rss-b8621923f1b5------2</link>
            <guid isPermaLink="false">https://medium.com/p/5f07f526604f</guid>
            <category><![CDATA[convex-optimization]]></category>
            <category><![CDATA[english]]></category>
            <category><![CDATA[arbitrage]]></category>
            <category><![CDATA[routing]]></category>
            <category><![CDATA[uniswap-v3]]></category>
            <dc:creator><![CDATA[Stefan Loesch]]></dc:creator>
            <pubDate>Tue, 21 Mar 2023 17:29:59 GMT</pubDate>
            <atom:updated>2023-03-21T20:13:09.142Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Ya1t4YwxLL1zlJWbY9aFIw.png" /></figure><h4>Carbon, routing, arbitrage and convex optimization</h4><p>Carbon as a protocol is unique for two reasons: firstly it has uni-directional trading curves, ie curves that are either for buying or for selling, but in order to do both one has to use two linked curves. Secondly, and this is important here, every Carbon position is unique in the sense that traders have to route their trades to individual positions rather than having the AMM consolidate all positions into one (xy=k) or into buckets (Uniswap v3) to simplify routing.</p><p>For the Carbon system to be efficient we need to ensure that efficient routing and arbitrage mechanisms are available. The Carbon SDK does include a very efficient routing algorithm, but for efficienty reasons (it runs in the user’s browser) it only routes through the position of the desired pair, so it will miss instances where routing through other pairs would improve the price. Relatedly, we want to enable anyone to identify and profit from arbitrage opportunities both within different pairs on Carbon, and between Carbon and other exchanges. We are therefore working on — and I am describing here the first step to — a generic routing and arbitrage framework that works both within Carbon, and between Carbon and most popular other AMM models, notable constant product, constant sum, and leverage liquidity.</p><p>A big shoutout here goes to Guillermo Angeris, Tarun Chitra, Alex Evans, and Stephen Boyd for their <a href="https://arxiv.org/pdf/2204.05238v1.pdf">paper</a> “Optimal Routing for Constant Function Market Makers” as well as the <a href="https://github.com/angeris/cfmm-routing-code">associated code</a>. We are using the convex optimization methodology they’ve outlined in their paper, and the code examples of how to use the <a href="https://www.cvxpy.org/install/index.html">cvxpy</a> library were extremely helpful to get our code running quickly.</p><h4>Scope of the problem addressed</h4><p>In our work we want to look at two closely related problems</p><ol><li>A trader wants to exchange TKN1 to TKN2 and is looking for the most efficient way of doing so; this could either be within Carbon positions only, or across the entire market</li><li>A trader wants to make a risk free gain by arbitraging either Carbon positions against each other, or arbitraging Carbon positions against each other and against the wider market.</li></ol><p>It is easy to see that problem (2) is a sub-problem of problem (1) if we require that the input amount is zero TKN1, and we want to maximize the (positive) amount of TKN2 which is say ETH or USDC, or whichever other token we want to receive our arbitrage profits in.</p><p>This problem is addressed in three distinct steps</p><ul><li><strong>Step 1. </strong>Identify the arbitrage opportunity, ie an unordered set of transactions that overall lead to the desired outcome</li><li><strong>Step 2. </strong>Construct a transaction from that arbitrage opportunity, ie a linear combination of executable trades</li><li><strong>Step 3. </strong>Execute it in a way that is safe with respect to MEV extraction</li></ul><p>The focus in this article is on step 1, and before we start I want to briefly discuss steps 2 and 3 that we may address at a later stage. The issue that leads to differentiating between step 1 and step 2 is that you can only trade tokens that you actually have. In an ideal world we could do the following</p><ol><li>Borrow sufficiently large amounts of all tokens involved</li><li>Execute all transactions, in arbitrary orders</li><li>Return the tokens borrowed in (1)</li></ol><p>This may or may not be possible, but even if it is possible this will not be optimal unless the borrow happens at zero cost. Instead, the optimal transaction will go as follows</p><ol><li>Take out a flash loan of [ETH or BNT] at the appropriate size</li><li>Sell [ETH or BNT] against [TKNa]</li><li>Sell [TKNa] against [TKNb]</li><li>…</li><li>Repay the flash loan</li></ol><p>Here at every stage we ensure that we have sufficient tokens available to execute the transaction we want to execute, and at the same time we minimize the amount of upfront borrowing needed, or rather its cost.</p><p>Especially for pure arbitrage transaction — ie when we have zero inputs — it is then important to submit them through an MEV protected end point, otherwise we will be certain to be front run. Whether or not this is also necessary for bona fide trading transactions without too big an arbitrage component remains to be seen.</p><h4>Levered liquidity and virtual tokens</h4><p>We will discuss below how exactly to apply the methods described here to Carbon curves — here we assume that all AMMs are constant product AMMs the produce leverage using a virtual token mechanism.</p><p>The way this mechanism works as follows: the indifference curve of our AMM is a standard <em>xy=k</em> curve with some value <em>k</em>. Contrary to non-levered AMM however, the actual token holdings <em>x1, y1</em> are below their theoretical values, ie we have (<em>x1+xv) (y1+yv) = k </em>where the quantities <em>xv, yv</em> correspond to the <em>virtual</em> token holdings of the AMM. Those virtual tokens are there for accounting purposes only, so they can not leave the AMM, meaning this levered AMM can only trade inside of a limited range of prices. This range is determined by the joint conditions <em>x1≥0, y1≥0</em>, and outside this range the AMM stops trading.</p><p>The chart below shows four different AMMs of this type that are arbitraged. We note that the AMMs where the state is in the interior of the range — ie <em>x1&gt;0, y1&gt;0 </em>rather than greater or equal — the dots lie in the straight line with the origin, indicating that they have the same price. For all other AMMs the state is as close as possible as they can get to this price, ie it is at the end of the range that is closes to the price.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/747/1*DySQ_chqFJRrleQn2P6kKQ.png" /><figcaption>Chart 1. Arbitraged curves.</figcaption></figure><h4>Routing and arbitrage using convex optimization</h4><p>In what follows I will treat convex optimization as a black box. For the theory of convex optimization I refer you to the paper quoted above, and the references therein. The <a href="https://github.com/bancorprotocol/carbon-simulator/blob/beta/resources/routing/NB01-MultiAssetRouting.ipynb">Jupyter Notebook</a> of the example implementation can be found in the resources section of the <a href="https://github.com/bancorprotocol/carbon-simulator/">Carbon Simulator</a> repo.</p><p>We are starting with a set of curves with arbitrageable states, ie contrary to the previous example the states correspond to different prices even if they are in the interior of the range, and therefore arbitrage gains can be created trading against them</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/737/1*0vBXHw97fHO38_hWaQn0ZA.png" /><figcaption>Chart 2. Curves pre arbitrage</figcaption></figure><p>What we are looking for is a state like in Chart 1 where all those arbitrage gains have been taken.</p><p>What convex optimization — and especially the cvxpy optimization library — allows us to do is to</p><ol><li>optimize a target function</li><li>subject to a number of constraints</li><li>provided (1) and (2) fulfil certain “convexity” conditions</li></ol><p>In what follows I will ignore (3) and just posit that the problem does indeed fulfil those conditions, otherwise cvxpy will warn us, and I will focus on (1) and (2).</p><p>Angeris et al discuss the generic case of a non-linear utility, but our problem is is much simpler: we choose one specific token, and we either want to receive as much as possible of this token, or we want to put in as little as possible. Throughout the calculations we consider all changes from the point of view of the AMM, do negative numbers are outflows, and positive numbers are inflows. Optimization however happens from the point of view of the trader, and it is easy to see that in both cases the problem is a <strong>minimization problem</strong></p><ul><li>Paying into the AMM, the trader prefers a smaller (positive) amount to a bigger one</li><li>Receiving from the AMM, the traders prefers a smaller (negative, therefore bigger in absolute value) amount to a bigger one</li></ul><p>The interesting part of course is not the target function, but the constraints. Those constraints are three-fold:</p><ol><li>constraints linked to the invariant curves</li><li>constraints linked to the AMM leverage, and</li><li>constraints linked to the self-financing conditions</li></ol><p>I will take those items in turns. The first one, about invariant curves, is essentially <em>xy=k</em>, except that <em>xy=k</em> is not a convex constraint, therefore not admissible under convex optimization. However, it is well known from linear optimization theory — and Angeris et all show it for this specific case — that the optimum value is always attained on the boundary, therefore we can use the constraint <em>xy≥k</em> instead</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/505/1*NxpTI3-RBt1YK-ubnss1Sg.png" /><figcaption>Figure 1. Code for curve constraints</figcaption></figure><p>Technically it is also important that we do not use the standard <em>xy=k</em> invariant function but the equivalent one where we apply a square root on both sides, so <em>xy</em> becomes a geometric mean, and <em>k</em> becomes kbar after taking the square root.</p><p>Secondly, the leverage constraints ensure that the AMMs can not pay out more tokens than they possess. Keeping in mind that flows are considered from the point of view of the AMM this means that the flows <em>dx, dy</em> must be bounded from below by a negative number, where this number corresponds to the actual token holdings of the AMM.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/239/1*KU_VnC4BhItM5kEnjzCldA.png" /><figcaption>Figure 2. Code for leverage constraints</figcaption></figure><p>Finally we have our self financing constraints. Those apply to all tokens except for the token that is used in the objective function. In the arbitrage case this means that all <em>dx,dy</em> that correspond to a specific token must sum up to zero. In the trading case they must sum up to the (positive) amount we want to pay in or the (negative) amount that we want to take out. In any case, if we have <em>N</em> tokens, then we have <em>N-1</em> constraints.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/752/1*gr7e6caX3q-SuXY0DOTY7w.png" /><figcaption>Figure 3. Code for self-financing constraints</figcaption></figure><p>The code for the objective function is essentially the same as for the self-financing constraints, except that it is wrapped in a cp.Minimize rather than being a constraint equation</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/648/1*VtjVdsDUQl39zmvd2pIXkQ.png" /><figcaption>Figure 4. Code for the objective function</figcaption></figure><p>Once we have set up our objective function and constraints, all we have to do is to feed this data into the solver</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/362/1*abuKh3WAG3iZxBEarFh90w.png" /><figcaption>Figure 5. Code for running the solver</figcaption></figure><p>The solver then spits out not only the optimized value, but more importantly the vectors <em>dx, dy</em> that determine the trades that lead to this optimal value. The chart below shows the (arbitrageable) starting positions of one pair (stars) and where the states end up after optimization (circles).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/808/1*fqhjBJK37zeKewYO7kGwIQ.png" /><figcaption>Chart 3. Curves pre and post arbitrage</figcaption></figure><h4>Summary and outlook</h4><p>I have shown above how to optimally route through an arbitrary number of levered virtual token positions, and I have asserted that any Carbon or Uniswap state can be described by those (this asserting is discussed in the Appendix just below). This algorithm is blazingly fast — for hundreds of positions it has no meaningful delay, and even for 1,000s or 10,000s it is very quick.</p><p>The analysis above omitted two things: fees and gas. Fees are in principle easily included, provided they are percentage fees, as all they do is shift the price. The only problem is that the direction of the shift depends on the direction of the trade, so the process needs run twice: in the first run we determine in which direction a specific curve trades [only for non-Carbon curves of course; Carbon curves only ever trade in one direction and have no fees] and before the second run we shift the prices by the fee amount in accordance with the trading direction in obtained in the first run.</p><p>Gas is somewhat more complex as with a constant per-AMM-used fee we leave the realm of convex optimization. We will write more about this in due course, and Angeris et al has a brief discussion on this topic, but essentially the trick is to identify the “dust” positions whose inclusion costs more in gas than it brings in term of slippage reduction. This may be an iterative process, even though heuristics and some smart construction of the algorithm should allow for restricting the calculation to 2–3 iterations.</p><h4>APPENDIX: The virtual token view of Carbon and Uniswap curves</h4><h4>Carbon curves</h4><p>In our <a href="https://carbondefi.xyz/whitepaper">whitepaper</a>, in equations 2.13–2.18, we give the virtual token curve that is associated with a Carbon curve. They key formula in this context is 2.16 which gives the virtual pool constant kappa as</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/261/1*uuUBZEr6E1ZlFU54JOT8rg.png" /><figcaption>Equation A1. Virtual pool constant kappa</figcaption></figure><p>Note that the numerator can also be written as <em>x0 y0</em> where <em>x0,y0</em> are the the special coordinates of the pivot point of the Carbon curve that are for example defined in formulas A.22, A.23</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/297/1*jNXxXxjoGDMrBDy7rZW6dg.png" /><figcaption>Equation A2. Pool parameter y0</figcaption></figure><p>Here y<em>int</em> is the y-intercept, ie the curve capacity aka the amount of tokens available for sale on the curve if the curve is full, and Gamma is the leverage factor also appearing in the equation for kappa. The equation for x0 is the same, except that it uses the x-intercept which corresponds to the amount of tokens the curve receives when all tokens on y are sold. Therefore, the effective curve price <em>P0=y0/x0</em>.</p><p>Our <a href="https://github.com/bancorprotocol/carbon-simulator/blob/beta/carbon/carbon_order_ui.py">CarbonOrderUI class</a> — the class the describes a single Carbon order — has a property <strong>as_cpc</strong> that returns a <a href="https://github.com/bancorprotocol/carbon-simulator/blob/beta/carbon/cpc.py">ConstantProduceCurve</a> object that can be used in the optimization algorithm.</p><h4>Uniswap v3 curves</h4><p>Uniswap v3 curves are composed of curvelets where each curvelet corresponds to a single bucket between two prices, and whose width depends on the tick size. At the moment, Uniswap v3 are most easily represented by the corresponding CarbonOrderUI object.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5f07f526604f" width="1" height="1" alt=""><hr><p><a href="https://medium.com/carbondefi/using-convex-optimization-for-optimal-routing-and-arbitrage-in-carbon-5f07f526604f">Using Convex Optimization for Optimal Routing and Arbitrage in Carbon</a> was originally published in <a href="https://medium.com/carbondefi">CarbonDeFi</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Introducing the Carbon Simulator]]></title>
            <link>https://medium.com/carbondefi/introducing-the-carbon-simulator-1b8e7bc8b0c2?source=rss-b8621923f1b5------2</link>
            <guid isPermaLink="false">https://medium.com/p/1b8e7bc8b0c2</guid>
            <category><![CDATA[amm]]></category>
            <category><![CDATA[crypto-trading]]></category>
            <category><![CDATA[english]]></category>
            <category><![CDATA[decentralized-finance]]></category>
            <category><![CDATA[simulator]]></category>
            <dc:creator><![CDATA[Stefan Loesch]]></dc:creator>
            <pubDate>Thu, 02 Feb 2023 14:18:32 GMT</pubDate>
            <atom:updated>2023-02-21T15:29:12.289Z</atom:updated>
            <content:encoded><![CDATA[<p><a href="https://simulator.carbondefi.xyz/"><strong>Carbon Simulator on simulator.carbondefi.xyz</strong></a></p><p>After the <a href="https://github.com/bancorprotocol/carbon-simulator">Carbon Simulator library</a> has been live <a href="https://pypi.org/project/carbon-simulator/">on PyPi</a> for a while now, we are glad that we can now announce that we have published it in an easily usable format, as <a href="https://simulator.carbondefi.xyz/">Jupyter Notebook directly in your browser</a>, no installation needed.</p><h3>Introduction to Carbon</h3><p>Carbon has been described at length elsewhere, notably in the <a href="https://carbondefi.xyz/whitepaper?_gl=1*10jn1y0*_ga*MTYwNjk0MTA1Ni4xNjc1MzMzNjYw*_ga_9CKMT9HWVK*MTY3NTMzMzY2MC4xLjAuMTY3NTMzMzY2MC42MC4wLjA.">Whitepaper</a>, the <a href="https://www.carbondefi.xyz/clkn/https/www.carbondefi.xyz/litepaper/">Litepaper</a>, and in the other resources on <a href="https://www.carbondefi.xyz/">carbondefi.xyz</a>. The Carbon Simulator is a python library that provides Carbon functionality very close — albeit not fully equivalent — to what we will have in the smart contracts and the SDK. The library is open-sourced <a href="https://github.com/bancorprotocol/carbon-simulator">on Github</a> and it is available as a pip install [<em>pip install carbon-simulator</em>] <a href="https://pypi.org/project/carbon-simulator/">on PyPi</a>. So here I’ll just give a very short intro, based on <a href="https://github.com/bancorprotocol/carbon-simulator/blob/main/resources/notes/202301%20Simulating%20Carbon.pdf">this presentation</a>.</p><p>In a nutshell, the Carbon invariant curve is a concentrated liquidity hyperbolic (x*y=k) curve, parameterized by its start price <strong>Pa</strong>, end price <strong>Pb</strong>, and the curve capacity <strong>yint</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nHSazPZIolBEMtvFhfAYVQ.png" /><figcaption>Carbon curve parameter Pa, Pb, yint</figcaption></figure><p>Carbon’s major innovation is that the curves are <strong>asymmetric</strong>, ie they do only allow for trading in one direction, as opposed to traditional AMM curves that trade back and forth.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FRpBiAJhFC_jG6XrLU_TMg.png" /><figcaption>Carbon asymmetric curve</figcaption></figure><p>Carbon still allow recurrent, bi-directional trading, using the concept of linked curves where liquidity is moved back and forth between those two curves.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mtvQK5cbVUdUGGgIzWj1Qg.png" /><figcaption>Carbon linked curves</figcaption></figure><p>In other words, Carbon implements an on-chain order book with <strong>two distinct bid and ask and ranges</strong>. This is shown in the chart below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*v1_IbYB_qMqGbVZIvUETvQ.png" /><figcaption>Carbon bid and ask order book</figcaption></figure><p>It is worth looking at the chart above in more detail to understand how Carbon works: the <strong>orange line</strong> is the BTC/ETH exchange rates from July 2021 to now. The <strong>green shaded area</strong> is the Carbon “buy [BTC for ETH]” bid range, from 12.1–13.3 [ETH per BTC]. The red shaded area is the “sell” ask range, from 14.6–16.1. The initial portfolio is 50/50 [by value] BTC and ETH. When ever prices dip into the green bid area, the Carbon position sells ETH for BTC, and in the red ask are Carbon sells BTC for ETH. In other words: Carbon <strong>buys-low/sells-high</strong> whenever markets move in a crab fashion. Above the red ask area, the position is 100% ETH, and below the green bid area it is 100% BTC. In other words: the position is <strong>flat on the upside and long on the downside</strong>. Option aficionados will recognize the usual trade-off here, albeit on a macroscopic scale: <strong>an unadjusted Carbon position is outperforming in sidewards trending “crab” markets, but underperforms in trending markets</strong>.</p><p><em>[Note: if the above is confusing think about ETH as USD “cash”, and about BTC as some TKN “risk asset” that is worth between 10–20 USD per TKN].</em></p><p>To see what happens to the Carbon position we can look at the chart below, which adds position data to the above chart (right hand side axis):</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WZ9oubb78qPxE9sbxVm3Bw.png" /><figcaption>Carbon position</figcaption></figure><p>The thick grey line is the <strong>total value </strong>of the Carbon position in ETH (starting at 1,000 ETH), and the thin dashed grey line is the <strong>value of the ETH position</strong> (starting at 50%, ie 500ETH), both on the right hand side axis. We see it the portfolio starts 50/50 (dashed line half way up), moves a bit more into BTC when dipping into the green range (dashed line goes down), and then it moves 100% into ETH once the price is above the upper end of the ask range [16.1]. Once the top end of the range is broken we notice that the value is flat, because at this stage the portfolio is all ETH, so it no longer depends on the BTC/ETH price. In Sep ’21 the price then dips back into the green bid range, so the Carbon position sells some ETH for BTC. This is sold at a profit in Oct ’21, when again the value stabilizes, at a slightly higher level because of the profit taken. We have a few more buy-low/sell-high cycles like this, and <strong>the Carbon position ends up at about 1,629 ETH, ie 60%+ up, in sideways market.</strong></p><h3>The Carbon Simulator</h3><p>In the following, when we refer to the Carbon Simulator we refer specifically to a number of Jupyter Notebooks that provide a user-friendly interface for specific types of analysis, rather than the all-singing-and-dancing Python library. We also note that there is a second simulator that runs a very similar analysis to the one described here, but that produces the output as a movies covering the whole timeline. We highly recommend to watch one or two of those animations before reading on, because the animation provides a very visceral understanding of how Carbon works that is hard to convey in a static chart.</p><p>The main distribution of the Carbon Simulator that we are covering here is on located at simulator.carbondefi.xyz which launches a JupyterLite instance running the Jupyter Notebooks directly in your browser, without the need for external resources hosting the kernel server. It works rather well, albeit <a href="https://twitter.com/odtorson/status/1621051248748404736">there are a few gotchas</a>. We have an alternative distribution at Binder, but this one is maintained less often, so it may be a bit behind. Please note that you are not obliged to run this simulation on the server — you can simply download the notebooks into a <a href="https://docs.anaconda.com/anaconda/install/index.html">Conda installation</a> and they should run out of the box. But this means you will be running our code on your local machine outside the browser-provided sandbox, <a href="https://twitter.com/odtorson/status/1621076163593379841">with all risks that this entails</a>.</p><p>The Carbon Simulator current consists of two similar Jupyter notebooks</p><ul><li>The interactive simulations book, <a href="https://simulator.carbondefi.xyz/lab?path=demo7-4%2Fdemo7-4.py">Demo7–4</a> (named thus for historical reasons)</li><li>The frozen simulations book, <a href="https://simulator.carbondefi.xyz/lab?path=demo7-4%2FScenarios.ipynb">Scenarios</a></li></ul><p>This post is already rather long, so here we will focus on how to use the Scenarios book. In the next post we will then look at how to run simulations interactively, and in the third post of this series we will look at how you can create your own scenarios.</p><p>So to launch the Scenario book, <a href="https://simulator.carbondefi.xyz/lab?path=demo7-4%2FScenarios.ipynb">please open this link in an incognito Window (ideally on Chrome)</a>. This is how it should look like</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2_kK2x1z84MM6qNKquOiRw.png" /><figcaption>Carbon Simulator initial view</figcaption></figure><p>The first step (and key recurring step) is to Run All Cells</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/956/1*V1WjAHkXfP6hi7IsKraHwQ.png" /><figcaption>The all-important Run All Cells command</figcaption></figure><p>This can take a few seconds whilst dependencies are installed but eventually you will see a screen as the one below</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*43co_89pHA1SooQEAox57Q.png" /><figcaption>Carbon Simulator after initialisation</figcaption></figure><p>This mostly shows the version numbers, and the one to take note of particularly is the one that says<em> Carbon Sim v1.1</em>. If this one is lower in a regular window than in an incognito window than the regular window is stuck on an old version.</p><p>The book that greats you then looks like this</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/776/1*CYNrkWceuo_sNSbRHZwzuw.png" /><figcaption>Notebook initialised view</figcaption></figure><p>It has three key segments</p><ol><li>The check boxes determining the <strong>display choices</strong></li><li>The drop downs determining the <strong>chart collection</strong> and the scenario choice within that collection</li><li>The <strong>chart output area</strong></li><li>The <strong>description area</strong> (not shown above)</li></ol><p>Starting with number (2), the top slider shows <a href="https://github.com/sklbancor/carbon-sim-jupylite/tree/main/content/demo7-4/scenarios">all xlsx and csv files in the scenarios directory</a>. Those will be subject of the 3rd post of this series. The second drop down chooses amongst the scenarios in a collection (a single line in the xlsx or csv file).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/796/1*RPxoVQfha_4zCEwBOKTjcw.png" /></figure><p>We have chosen the initial <em>Intro</em> scenario that contains charts from all the other ones below in a single view. You need to <strong>Run All</strong> after changing the collection to see an updated choice of scenarios in the bottom drop-down, and <strong>Run All</strong> again after changing the scenario.</p><p>In area (1) we see the following choices</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/452/1*0XQK_uxQXDsphkvZNcVzGw.png" /><figcaption>chart elements and option</figcaption></figure><p>Those indicate either elements to include in the chart (eg <em>plotPrice</em> for the spot price, or <em>plotValueTotal</em> for including the portfolio value) or display choices (eg <em>plotDark</em> to switch the charts to dark mode). In order for changes to take effect you need to <strong>Run All</strong>.</p><p>As an aside: you can customize all colors if you click on the three dots below the section headline (color choices are <a href="https://www.google.com/search?q=matplotlib+colors">matplotlib colors</a>)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/770/1*GyGTYMSxKL9lV0NRi6QC4A.png" /></figure><h3>Interpreting the charts</h3><p>Finally, let’s discuss a few simulation result charts. Below is a theoretical show-and-tell example of a perfect sinoidal market dynamics. Whenever the price goes down through the green bid range, the Carbon position sells cash CSH against the token RSK, and whenever it goes up through the red ask range it sells RSK against CSH.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*G3iVqBQpuOOCQnGIi8VAmA.png" /><figcaption>Theoretical example chart</figcaption></figure><p>The solid grey line shows the total portfolio value (in CSH), and the dashed line the value of the CSH component, going from zero (100% RSK) to the total value (100% CSH). If the portfolio is 100% in CSH the grey value line is flat as the portfolio is no longer sensitive to changes in the spot price. When spot moves below the red line the curve remains flat until the spot price moves into the green bid area, at which point the Carbon position get more and more converted in RSK and therefore starts moving more and more in line with spot prices.</p><p>Let’s finish on some real market data with the following ETH/BTC chart, here in a period of upwards trending prices ETH versus BTC:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*iGHB5a0_qfiqq6_zaR6h_A.png" /><figcaption>BTC/ETH chart (upwards trending)</figcaption></figure><p>Here the strategy provider was bullish, so they set the strategy entirely above the current price, and started 100% in the risk asset, ETH (note the inverted scale here compared to the chart in the intro). When the spot hit the red ask range in June 2021, most of the ETH is sold at a price of around 0.08. The spot is then range trading between 0.06 and 0.08, and the Carbon position engages in a number of rounds of buy-low/sell-high. Overall this strategy made 5x+, in an environment where markets went up 70%.</p><h3>Resources</h3><ul><li>Carbon Simulator as <a href="https://simulator.carbondefi.xyz/">JupyterLite distribution</a> (<a href="https://simulator-beta.carbondefi.xyz/">beta branch</a>; <a href="https://github.com/sklbancor/carbon-sim-jupylite">repo</a>) and as Binder distribution (<a href="https://github.com/bancorprotocol/carbon-simulator-binder">repo</a>)</li><li>Carbon Animated Simulator</li><li><a href="https://carbondefi.xyz/whitepaper?_gl=1*10jn1y0*_ga*MTYwNjk0MTA1Ni4xNjc1MzMzNjYw*_ga_9CKMT9HWVK*MTY3NTMzMzY2MC4xLjAuMTY3NTMzMzY2MC42MC4wLjA.">Whitepaper</a>, the <a href="https://www.carbondefi.xyz/clkn/https/www.carbondefi.xyz/litepaper/">Litepaper</a>, and the Carbon website <a href="https://www.carbondefi.xyz/">carbondefi.xyz</a></li><li>Carbon library <a href="https://github.com/bancorprotocol/carbon-simulator">on Github</a> and <a href="https://pypi.org/project/carbon-simulator/">on PyPi</a></li><li>Carbon Simulator <a href="https://github.com/bancorprotocol/carbon-simulator/blob/main/resources/notes/202301%20Simulating%20Carbon.pdf">presentation</a></li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dIByY8En5Kdtgtip2W5HJA.png" /><figcaption>Cover Image</figcaption></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1b8e7bc8b0c2" width="1" height="1" alt=""><hr><p><a href="https://medium.com/carbondefi/introducing-the-carbon-simulator-1b8e7bc8b0c2">Introducing the Carbon Simulator</a> was originally published in <a href="https://medium.com/carbondefi">CarbonDeFi</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[AMM Gamma, options, and optimal fees]]></title>
            <link>https://medium.com/@odtorson/amm-gamma-options-and-optimal-fees-b5c93b60630c?source=rss-b8621923f1b5------2</link>
            <guid isPermaLink="false">https://medium.com/p/b5c93b60630c</guid>
            <category><![CDATA[amm]]></category>
            <category><![CDATA[amm-fee-optimization]]></category>
            <category><![CDATA[gamma]]></category>
            <category><![CDATA[amm-fees]]></category>
            <category><![CDATA[options]]></category>
            <dc:creator><![CDATA[Stefan Loesch]]></dc:creator>
            <pubDate>Wed, 21 Dec 2022 08:56:22 GMT</pubDate>
            <atom:updated>2022-12-24T10:36:16.134Z</atom:updated>
            <content:encoded><![CDATA[<p><em>Note: the associated Jupyter notebook is </em><a href="https://github.com/topazeblue/notebooks/blob/main/AMMs/2022/202212_AMM_Gamma_vs_Derivatives_Gamma.ipynb"><em>on Github</em></a><em> and </em><a href="https://mybinder.org/v2/gh/topazeblue/notebooks/main?labpath=AMMs/2022/202212_AMM_Gamma_vs_Derivatives_Gamma.ipynb"><em>on Binder</em></a><em>.</em></p><p>This article is part 3 of a series of articles that look at the relationship between AMMs and options, especially via the respective Gammas, and what this means for fees. <a href="https://medium.com/@odtorson/why-amm-gamma-and-derivatives-gamma-is-different-70b51c4692f0">Part 1 looking at a zero-fee environment is here</a> , and <strong>Part 2 story which took a first look at how fees impact the previous findings is here</strong>. Those articles are part of a wider series dealing with <a href="https://medium.com/bancor/what-we-all-got-wrong-about-calculating-impermanent-loss-37925604ef1a">Divergence Loss aka Impermanent Loss</a>, <a href="https://medium.com/@odtorson/why-loss-versus-rebalancing-lvr-and-impermanent-loss-il-are-essentially-the-same-85796c7df4d3">Loss Versus Rebalancing</a>, and they are all tied together by the <a href="https://medium.com/@odtorson/liquidity-providers-options-and-amms-c5e4ca50819e">AMM Triangle introduced here</a>.</p><h3>Review parts 1 &amp;2</h3><p>In <a href="https://medium.com/@odtorson/why-amm-gamma-and-derivatives-gamma-is-different-70b51c4692f0">part 1 of this series</a> we looked at the below chart which shows the AMM Gamma profile (red) compared with a hedged option profile (blue) and a perfect square profile (green)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/386/1*Iyb9SsX2f1pY6dtW4wpDCA.png" /><figcaption>Chart 1 — Various Gamma profiles</figcaption></figure><p>In part 2, we looked at how any non-zero levels of fees widen the straddle-like cusp of the fee=0 profile to a strangle-like profile with two separated strikes</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/386/1*0APqvuZAsY0BQpYhDbWvxg.png" /><figcaption>Chart 2 — Gamma profile with fees</figcaption></figure><p>We have seen that this has profound implications on the mathematics of the AMM: whilst in the fees=0 case the rebalancing P&amp;L diverges when rebalancing instantaneously, as soon as any non-zero level of fees is introduced the rebalancing P&amp;L for instantaneous rebalancing is to zero, and it only increases when rebalancing less frequently</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/376/1*ULdiygeG-ia5dlSfhqV4mg.png" /><figcaption>Chart 3 — Rebalancing P&amp;L</figcaption></figure><p>In this article I will continue the discussion of this particular finding and link it to certain assumptions on market micro-structure.</p><h3>Analysis</h3><p>Above we have looked at the fees as impacting the effective execution price, therefore splitting the straddle strike into a strangle. Another, equivalent, way of looking at this is to keep the fees separate, ie we operate under the fiction that the trades is executed at the trade at the strike price of the straddle, that the fees are to be paid separately. In this view of the world our analysis becomes a break-even analysis: at which stage will the gain on the off-market trade — ie the AMM being willing to trade at the geometric average of its currently set price and the new market price — be sufficient to pay for the fees the AMM requires.</p><p>The chart below shows this analysis for an AMM currently struck at 1000 USD per TKN, and with a fee level of 0.1%.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/378/1*pXDcgS2PHJ36B5vlvixo3w.png" /><figcaption>Chart 4 — Break-even analysis</figcaption></figure><p>It is worth understanding the meaning of Chart 3, specifically the behaviour for small rebalancing times, in the context of Charts 2 and 4. The reason why the rebalancing P&amp;L is zero is because the price movements considered in a single step are not sufficient to make a trade worthwhile. In terms of Chart 2 this means that the price movements remain in the area where the strangle profile is flat at zero, and in terms of Chart 4 this means that the trades are within the area where fees are smaller than the P&amp;L generated by the red Gamma curve. The corollary here is of course that the strikes of the strangle in Chart 2 sit at the points where the green fee curve intersects the red Gamma curve in Chart 4.</p><p>The relationship between break-even price and fee level is actually linear</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/405/1*QVqP2sWuPRYVc1nCb98Etg.png" /><figcaption>Chart 5 — Break even price</figcaption></figure><h3>Monte Carlo simulation</h3><p>The above analysis is a somewhat simplistic as it does only look at a one-period model — if the move in spot price during the rebalancing period is not sufficiently large to break-even, nothing happens and the state of the world is reset. In the analysis above there is no way of aggregating the effects of multiple observation periods, and to perform a transaction when the aggregate move is big enough.</p><p>This is addressed in the Monte Carlo simulation that described below. All simulation code is available on <a href="https://github.com/topazeblue/notebooks/blob/main/AMMs/2022/202212_AMM_Gamma_vs_Derivatives_Gamma.ipynb">Github</a> and <a href="https://mybinder.org/v2/gh/topazeblue/notebooks/main?labpath=AMMs/2022/202212_AMM_Gamma_vs_Derivatives_Gamma.ipynb">Binder</a>. Below an example of how the simulation works: it is initialized at a price of 100, and a fee of 10% (for demonstration purposes only; actual sims use lower fees). Then markets move from 100 to 150. We can confirm that <em>p=150</em>. We also have <em>bleed=2.53</em> and <em>fee=1.12</em>. The bleed is the money the arbitrageurs makes on the Gamma, the fee is the fee they pay, but expressed in the numeraire<em> y</em>. Then markets move to 130. This <em>would</em> yield <em>bleed=0.29</em> and <em>fee=0.42</em>, ie the arbitrageurs is losing money. Arbitrageurs are not losing money, therefore the trade is reverted, as can be seen by the fact that the price of the AMM remains at 150 (see the yellow markup). Then markets move from 130 to 100. This allows the AMM to move from 150 to 100, with <em>bleed=2.06</em> and <em>fee=1.12</em> which is a profitable trade for the arbitrageur, and which therefore happens.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1014/1*LXf4-ygKoj5R-QuVEqn6Gg.png" /><figcaption>Chart 6</figcaption></figure><p>For the simulation we look at paths with a different sampling frequency. What this means is that all paths start at the same point, all paths cover the same period, and all paths exhibit the same annualized volatility. The only difference is the frequency with which changes are observed an acted upon.</p><p>The intuition behind this is that in highly efficient markets, many players are present that observe them closely and that react quickly when an arbitrage opportunity opens. In less efficient markets however, arbitrage opportunities can exist for longer, and markets can therefore move further before arbitrages happen.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/386/1*gqNMw0JUJTtGNcQcPtCQhQ.png" /><figcaption>Chart 7</figcaption></figure><p>The first chart is a scatter plot where every point corresponds to a single random path, where the number of observation segments (x-axis) of the path is determined at random between 10 and 1,000. The y-axis is the AMM <strong>fee capture</strong>, which is defined as fees over bleed. The intuition behing this measure is that arbitrageurs will never pay more in fees than they can earn on the bleed, to we will always have<em> fee capture &lt; 100%</em>. The question is how which percentage of their potential gains will the arbitrageurs pay over to the AMM LPs — this percentage being the fee capture.</p><p>Looking at the chart below it seems that in efficient markets, fee capture moves very close to unity, and it stands to reason that in highly efficient markets (ie very many path segments) unity is asymptotically reached.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/386/1*mtIBdPazG-QPIiUNUlDPTw.png" /><figcaption>Chart 8</figcaption></figure><p>As a technical measure, below is the percentage of reverted trades. Unsurprisingly, most of them are as it takes a very long time observing the markets before an arbitrageurs can pounce on a gain at least big enough to compensate for the fees.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/386/1*mN1LkhHcNdmy-L88jiprtQ.png" /><figcaption>Chart 9</figcaption></figure><p>The below chart shows a longer running analysis where the number of path segments is not randomly chosen, but according to a specific schedule (note the log axis!). The green curve shows the <em>average</em> fee capture ratio, estimated over a sufficiently large number of paths of the same length to remove sampling variance. Fee levels are at 0.5%. The grey curve shows the average percentage reverted. It seems obvious from this chart that both curves converge to unity, albeit slowly</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/390/1*V2sPv1CUt2IUNHQ_JC67xA.png" /><figcaption>Chart 10</figcaption></figure><p>The chart below finally shows the average fee capture at fee levels of 0.1%, 0.5% (the previous curve) and 1% respectively. We see that, the lower the fees, the more efficient the market need to be to achieve the same level of fee capture. However, eventually when markets become perfectly efficient, fee capture converges to unity, whatever the fee level.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/390/1*b2bq5eYEaWsflgI1wgAXLg.png" /><figcaption>Chart 11</figcaption></figure><h3>Discussion</h3><h4>The limitations of Brownian motion to describe AMM finance</h4><p>Before getting into the core of the discussion I want to say a few things about the use of Brownian motion and the divergence we see appearing in the case <em>fees=0</em>. Firstly — we are operating under somewhat inconsistent assumptions here: using Brownian motion for derivatives makes sense: we assume a deep and liquid market in the underlying as backstop, and we see what we can derive from this for options markets, and those of other derivatives. If we combine this with the robustness of quadratic profiles <a href="https://medium.com/@odtorson/why-amm-gamma-and-derivatives-gamma-is-different-70b51c4692f0">discussed in article 1</a> then we can see how the Brownian motion assumptions can be extremely powerful for pricing and hedging derivatives.</p><p>Our situation is slightly different however — we are trying to understand market infrastructure, and finance, especially quantitative finance does not generally do well analysing market infrastructure. The reason for that is easy — market infrastructure exists because markets are <em>not</em> perfectly efficient, and you can generally prove that in efficient markets, most of our market infrastructure would not exist. Looking for example at AMMs — the assumption that there is some spot price process (which implies a deep and liquid market) does not really make sense: if there was a deep and liquid market where people could trade at the price of that process, why would anyone trade on the AMM at a worse price?</p><p>Secondly — Brownian motion is rather pathological at very short time periods / high frequencies. That’s a problem well known in many areas of modern physics where <em>renormalization</em> techniques like high-frequency cutoffs need to be applied to make the models work in a manner consistent with the real-world experience. That is not different here, and the divergence we find for <em>fee=0 </em>must be interpreted very carefully, because of course there can not be an infinite value transfer to arbitrageurs from LPs because the wallet of available value is limited. The issue is related to the fact that the <em>length </em>of a Brownian trajectory is infinite: if you sample a Brownian motion at intervals <em>dt, </em>and add up the associated <em>|dx| </em>as positive numbers regardless of direction, then this sum diverges for <em>dt-&gt;0.</em> Mathematically this is exactly the same that happens in the formulas in this paper.</p><p>To cut a long and complex story short — we must be careful with this analysis in the case <em>fee=0</em>. This fortunately is not as bad as it sounds as we know rather well what happens in this case: the LPs are left with <em>sqrt(xi)</em>, and the remaining gains of the square root profile — detailed in<a href="https://medium.com/bancor/what-we-all-got-wrong-about-calculating-impermanent-loss-37925604ef1a"> this article on how we all got IL/DL wrong </a>— go to the arbitrageurs.</p><h4>Fees and market microstructure</h4><p>With the theoretical part out of the way, I now will focus on the interesting part of the analysis, which is what happens when we actually have fees. The most important chart in this respect is this one, or the equivalent Charts 2 and 4 above.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/386/1*ujHca_4E_DFF4yNnwyfN2Q.png" /><figcaption>Chart 12</figcaption></figure><p>What all those charts show is that, in the presence of any positive fee, however small it is, arbitrageurs need to wait a moment for markets to move before they can come in profitably. This however makes the arbitrage process effectively a Dutch auction: a lot of people are watching the market, and each other, and they need to decide when to move in, keeping in mind that they (a) only want to do so when it is profitable for them, but (b) there are other players with exactly the same economics out there that may also move in.</p><p>In theory this process will drive profits of arbitrageurs to zero — they will move in at exactly the point when they break even. In practice this of course does not happen like this, because no-one will be carefully watching a market just to not make any money. However — how much money they are willing to accept to monitor those markets is a question that can only be answered empirically, and Brownian motion and continuous time finance is not of great help for that. It simply is the wrong tool.</p><p>Chart 10 and 11 are interesting but require some thought: clearly there is a relationship between market efficiency and rebalancing frequency, but equally clearly this relationship is not strong enough to allow for precise numerical analysis. However — the result shown seems (a) intuitive, and (b) powerful, and (c) seems in line with market experience: fee capture levels can be anywhere between 0 and 100%, and there is a strong dependency on (i) the efficiency of the associated market, and (ii) the actual fee levels: the lower the fees the further one has to go to the right on the (log!) efficiency chart to get reasonable fee capture levels. As a topic of further research it would be very interesting to design an appropriate framework that would allow to better measure and quantify those issue.</p><p>As a closing remark I want to mention that this is a rather positive result for liquidity providers on AMMs (and arguably more positive than we have <a href="https://arxiv.org/abs/2111.09192">empirically</a> <a href="https://twitter.com/thiccythot_/status/1589022227437039616">seen</a>). If we are able to design protocol with fee capture ratios of close to 100% then LPs will receive the entire delta hedge corresponding to their IL position which, at least in an ideal world would make them break even. The end-customer flow from people wanting to trade outright rather than for arbitrage reasons in this case is just the cherry on the cake, and actual net profit.</p><p>This close the circle back to the AMM triangle <a href="https://medium.com/@odtorson/liquidity-providers-options-and-amms-c5e4ca50819e">with which this longer cycle of posts started</a>: if fee capture is 100% then this triangle is perfectly balanced, ie the net gain or loss along all three edges is zero <em>from market movements</em>, but liquidity providers of course on top of it earn the fees from the non-arbitrage flow.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/914/1*i22_0xQYfdp7rPF5gk6AKA.png" /><figcaption>Chart 13. The AMM Triangle</figcaption></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b5c93b60630c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Why AMM Gamma is not so different from derivatives Gamma after all; or is it? (after-fees edition)]]></title>
            <link>https://medium.com/@odtorson/why-amm-gamma-is-not-so-different-from-derivatives-gamma-after-all-or-is-it-after-fees-edition-cf375a699804?source=rss-b8621923f1b5------2</link>
            <guid isPermaLink="false">https://medium.com/p/cf375a699804</guid>
            <category><![CDATA[optimal-fees]]></category>
            <category><![CDATA[options]]></category>
            <category><![CDATA[gamma]]></category>
            <category><![CDATA[amm]]></category>
            <category><![CDATA[delta-hedging]]></category>
            <dc:creator><![CDATA[Stefan Loesch]]></dc:creator>
            <pubDate>Tue, 20 Dec 2022 08:36:52 GMT</pubDate>
            <atom:updated>2022-12-20T08:36:52.065Z</atom:updated>
            <content:encoded><![CDATA[<p><em>Note: the associated Jupyter notebook is </em><a href="https://github.com/topazeblue/notebooks/blob/main/AMMs/2022/202212_AMM_Gamma_vs_Derivatives_Gamma.ipynb"><em>on Github</em></a><em> and </em><a href="https://mybinder.org/v2/gh/topazeblue/notebooks/main?labpath=AMMs/2022/202212_AMM_Gamma_vs_Derivatives_Gamma.ipynb"><em>on Binder</em></a><em>.</em></p><h3>No fees (recap part 1)</h3><p>In the <a href="https://medium.com/@odtorson/why-amm-gamma-and-derivatives-gamma-is-different-70b51c4692f0">previous post</a>, I have shown that — for fee levels of zero — the AMM profile looks very different from a residual profile after Delta hedging: whilst the latter is in first order quadratic (because the hedge takes care of level and slope), the AMM profile has a cusp</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/386/1*GD1ytFfldgaG7jyeb6O9Gw.png" /></figure><p>This has important implications for the value transfer that is induced by that “Gamma”: when hedging options, the Gamma bleed is relatively independent of the rebalancing frequency: for a perfect square profile it is flat (green dotted line), and for another profile it only moves to the extent that higher order terms become important (blue line). An AMM however behaves <em>at every point in time</em> like a straddle at maturity, ie it has infinite Gamma. As a consequence, for instantaneous rebalancing the value transfer diverges, ie it becomes infinite.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/386/1*gbWbezLs-y0wkh_mjEJMIg.png" /></figure><h3>With fees</h3><p>We have seen above that for instantaneous rebalancing the value transfer diverges because of the extremely violent behaviour of the Brownian motion when looked at over short time scales. We remind ourselves however that this was in the case where <em>fees=0. </em>I will show here that fees effectively operate as a high-frequency cutoff and that with fees the AMM case is similar to — albeit not quite the same as — the option hedging case.</p><p>What happens when fees are introduced is that the straddle-like cusp of the AMM profile is pulled apart and transformed into a straddle-like profile, as shown below. I also show a square profile that approximates this particular straddle reasonably well</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/386/1*0APqvuZAsY0BQpYhDbWvxg.png" /></figure><p>Here the same chart zoomed in where the straddle-like nature becomes even more clear.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/400/1*9bTvF7qh_mEoSDyMffknWA.png" /></figure><p>We also see from the chart that there are three distinct regimes with respect to the AMM profile and its square approximation</p><ul><li>In the <strong>central area</strong> (around <em>x=1</em>), the square profile dominates the AMM profile, ie the square profile is above the AMM profile</li><li>In the <strong>intermediate area, </strong>the AMM profile dominates, and finally</li><li>In the <strong>wings area,</strong> the square profile dominates again.</li></ul><p>When we look again at the chart drawing rebalancing P&amp;L vs rebalancing frequency (or rather, rebalancing time) then we recognise those three regimes clearly: the red curve starts below the green one (central area), rises above it (intermediate area), and finals falls below it again (wings area)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/394/1*-OFPOZI-mNIu2r5BptFkBw.png" /></figure><p>Comparing this chart to the <em>fees=0 </em>chart (dashed red line) we see that indeed the pole at <em>t=0</em> is removed, and instead the rebalancing P&amp;L goes to zero:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/376/1*ULdiygeG-ia5dlSfhqV4mg.png" /></figure><p>Below I zoom in on the interesting area around the instantaneous rebalancing point (t=0). We see that the P&amp;L starts are zero flat (corresponding to the flat region of the strangle), then increases quickly when the rebalancing period starts covering the two strikes of the strangle. Finally reverses course and falls again when the rebalancing time is so long that the dominance of the square profile in the wings starts becoming important.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/386/1*ujHca_4E_DFF4yNnwyfN2Q.png" /></figure><p>In conclusion — we have seen that the AMM Gamma is not that different from derivatives Gamma in that once one introduces fees (or any other type of transaction cost for that matter) this introduces a high-frequency cut-off on the rebalancing, and entirely removes the divergence. However, whilst the pole is removed, we overshot the target: instead of landing at a nice flat’ish curve, we ended up with a curve where the rebalancing P&amp;L goes to zero when rebalancing frequency goes up. This implications of this are profound, and they actually solve the optimal-AMM-fee conundrum. But this is the topic of an upcoming post.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=cf375a699804" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Why AMM Gamma is different from derivatives Gamma]]></title>
            <link>https://medium.com/@odtorson/why-amm-gamma-and-derivatives-gamma-is-different-70b51c4692f0?source=rss-b8621923f1b5------2</link>
            <guid isPermaLink="false">https://medium.com/p/70b51c4692f0</guid>
            <category><![CDATA[options]]></category>
            <category><![CDATA[hedging]]></category>
            <category><![CDATA[derivatives]]></category>
            <category><![CDATA[gamma]]></category>
            <category><![CDATA[amm]]></category>
            <dc:creator><![CDATA[Stefan Loesch]]></dc:creator>
            <pubDate>Sun, 18 Dec 2022 19:38:33 GMT</pubDate>
            <atom:updated>2022-12-19T10:52:38.162Z</atom:updated>
            <content:encoded><![CDATA[<p><em>Note: the associated Jupyter notebook is </em><a href="https://github.com/topazeblue/notebooks/blob/main/AMMs/2022/202212_AMM_Gamma_vs_Derivatives_Gamma.ipynb"><em>on Github</em></a><em> and </em><a href="https://mybinder.org/v2/gh/topazeblue/notebooks/main?labpath=AMMs/2022/202212_AMM_Gamma_vs_Derivatives_Gamma.ipynb"><em>on Binder</em></a><em>.</em></p><p>My last few posts were inspired by <a href="https://medium.com/@odtorson/liquidity-providers-options-and-amms-c5e4ca50819e">the AMM Triangle</a>, and I was discussing the relationship between <a href="https://medium.com/bancor/what-we-all-got-wrong-about-calculating-impermanent-loss-37925604ef1a">Divergence Loss (formerly known as Impermanent Loss)</a> and <a href="https://medium.com/@odtorson/why-loss-versus-rebalancing-lvr-and-impermanent-loss-il-are-essentially-the-same-85796c7df4d3">Loss versus Rebalancing</a>. The key thread connecting all of those is the relationship between AMMs, self-financing strategies, and option pricing. In this post I will add another important piece to this puzzle — I will discuss how the Gamma income or bleed is different hedging options versus LPing in an AMM. This may seem only of academic importance, but I am expecting this to have profound implications when looking for optimal fee levels in an AMM. Stay tuned!</p><h3>Delta hedging and Gamma bleed / gains</h3><p>It is well known that since Black Scholes Merton’s seminal work from the 1970s onwards that the option pricing formulas they developed are not that much pricing them — this was known at least since Bachelier — but about actually hedging them using the Greek (Delta, Gamma, Theta and friends; see the <a href="https://theammbook.org/page/paper/">theammbook.org paper, section 4</a>). BSM’s important insight was that, in a Brownian motion world, options are risk free. Whilst there is a cost replicating them — the Gamma bleed when hedging optionality — but provided volatilities are known, this cost is deterministic.</p><p>The way options are replicated is through the so-called <em>delta hedge</em>: the option trader runs at every point in time the linear portfolio (ie containing only cash and the risk asset) that best matches the option portfolio. Graphically, this is the well known tangent portfolio in the PV vs spot-price graph below where we see the square-root profile (blue solid line) and its delta hedge (the blue dotted line)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/394/1*XocHd8tY54WYf6YkX5V0Jw.png" /></figure><p>The value of the hedged profile — ie the difference between the profile and its linear approximation — is shown in the blue line below. We also show the quadratic profile that best matches the hedged profile, ie the next term in the <a href="https://en.wikipedia.org/wiki/Taylor_series">Taylor series approximation</a> of it.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/392/1*pveavZJZ3LPM6wFipWWy5A.png" /></figure><p>The equations for the chart shown above are (ignoring the scaling factors)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/472/1*A9Pj_P6cZBqJAjvp5pndvA.png" /></figure><p>Below is the same chart, zoomed in:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/386/1*3XLpGp4MOo7NjoantPLAug.png" /></figure><p>Now we are looking what happens when we are delta hedging this profile. We know from Black Scholes Merton that, if we rebalance instantaneously, the replication is perfect. However, what happens when we rebalance less often? We have drawn the expected rebalancing gain (the Gamma gain) against the rebalancing time in the chart below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/400/1*TClbb6db_BxCS7Q_fqQk1A.png" /></figure><p>First looking at the green dotted line, we see that for the square root profile, the rebalancing time does not matter: as the standard deviation grows in square root t and the gain in x-squared, those two cancel each other out at every horizon. For our actual profile this is not the case, and the reason for this is that the 3rd-order and above terms in the Taylor expansion of the profile become more important.</p><p>This is the key reason why the Black Scholes Merton model works so well in practice — markets are not Brownian motions, and rebalancing is not instantaneous, but it does not really matter, as the rebalancing P&amp;L is relatively robust against changes in the rebalancing time because the profile is locally quadratic. So, as long as the rebalancing time is sufficiently short that the quadratic term dominates the Taylor expansion, the effect of Gamma remains relatively stable.</p><h3>Rebalancing the AMM portfolio</h3><p>The Gamma in an AMM portfolio is different: it stems from the fact that an AMM this is currently arbitraged to a price <em>x0</em> trades towards a new price <em>x</em> at the geometric average of <em>x </em>and <em>x0</em>. In our case <em>x0=1, </em>and therefore</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/414/1*QqE-SaIGAV13BDqyrCEQ5A.png" /></figure><p>which plotted looks like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/386/1*39KIzURxFr1OqU1wCeF0Yg.png" /></figure><p>We see that there is a cusp a <em>x=1</em>, rather than the nice quadratic term that appears in derivatives replication</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/386/1*Iyb9SsX2f1pY6dtW4wpDCA.png" /></figure><p>This linear rather than quadratic behaviour around <em>x=1</em> makes it much steeper for small rebalancing time. In fact, the PV diverges when the rebalancing time goes to zero</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/384/1*VS_znSrzim4ZVKyO1-PE7Q.png" /></figure><p>For larger rebalancing times of course it crosses over as at this stage the quadratic function outpaces the linear one</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/386/1*60ll3EUMFWYhvvsElbmX_g.png" /></figure><p>Note that the behaviour for small rebalancing times is an extremely important result:</p><blockquote>In a perfect Brownian motion world, the value transfer from an AMM to its arbitrageurs diverges, ie it becomes infinite.</blockquote><p>This related to the fact that Brownian motion at the microscopic level becomes extremely violent. In other words, the divergence is driven by the small moves: it is well known that a Brownian motion that crosses a given level will cross it an infinite number of times within any open interval containing the touch point (except on a space with measure 0).</p><p>However, this is more of a theoretical problem than a practical one: in the real world, there is a maximum frequency at which prices are updated and at which trades happen. This limits the divergence even in a zero-fee environment. In the presence of strictly positive fees, the divergence should disappear even in a Brownian motion environment, because any level of fees strictly greater than zero breaks the divergence at the rebalancing time t=0. Having said this — this also suggests that the profitability of a liquidity position depends non-trivially on the fee levels, but this is subject of future work. In this context I would like to point out the <a href="https://pdfhost.io/v/50Gn6WL07_AMM_returns_good">paper by Tassy and White</a> that has some interesting analytics in this respect.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=70b51c4692f0" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[What we all got wrong about calculating Impermanent Loss]]></title>
            <link>https://blog.bancor.network/what-we-all-got-wrong-about-calculating-impermanent-loss-37925604ef1a?source=rss-b8621923f1b5------2</link>
            <guid isPermaLink="false">https://medium.com/p/37925604ef1a</guid>
            <category><![CDATA[amm]]></category>
            <category><![CDATA[impermanent-loss]]></category>
            <category><![CDATA[il]]></category>
            <category><![CDATA[divergence-loss]]></category>
            <category><![CDATA[cfmm]]></category>
            <dc:creator><![CDATA[Stefan Loesch]]></dc:creator>
            <pubDate>Sat, 17 Dec 2022 10:51:46 GMT</pubDate>
            <atom:updated>2022-12-17T10:51:46.762Z</atom:updated>
            <content:encoded><![CDATA[<p>I have recently written about Impermanent Loss (“IL”) and <a href="https://medium.com/@odtorson/why-loss-versus-rebalancing-lvr-and-impermanent-loss-il-are-essentially-the-same-85796c7df4d3">how it is essentially the same thing as Loss Versus Rebalancing (“LVR”)</a> and in the course of discussing it (thanks <a href="https://twitter.com/0x94305">Alex</a>) <a href="https://medium.com/@odtorson/one-more-thing-on-lvr-and-impermanent-loss-36c64e17f411">I realized that we defined IL badly</a>. I will here redraw the arguments made <a href="https://medium.com/@odtorson/one-more-thing-on-lvr-and-impermanent-loss-36c64e17f411">in this post</a> in a more thorough manner, and provide an improved definition of IL, or rather DL (for Divergence Loss), because under the new definition there is nothing impermanent with this loss. For more in-depth explanation of some of the techniques employed here — notably on the linkage between AMMs and option pricing — I recommend to <a href="https://theammbook.org/page/paper/">read my paper on theammbook.org first, specifically chapter 4</a>.</p><p>The IL is currently defined as the <em>opportunity loss against HODL</em>, ie the difference of the 50/50 initial position simply held, and the value of the AMM position. If the define <em>xi</em> as the ratio between the price now and the price when the position was entered into, then IL is</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/526/1*XEEUwFeSeTTbYNGFpzl_tw.png" /><figcaption>IL as function of normalized price xi</figcaption></figure><p>If prices return to the original point then <em>xi=1</em> and therefore the loss becomes zero — hence the moniker “Impermanent”. People have pointed out that there is nothing impermanent about this loss if prices do not return to their initial value— as one hopes on a pool like WBTC/USDC where one expects for WBTC to moon — and therefore the term “Divergence Loss” or “DL” was coined. We will see below that properly defined “IL” is non-zero even if <em>xi</em> returns to be unity, therefore we will drop the IL moniker from this point onwards and refer exclusively to DL.</p><p>To understand the issue with the current definition of DL, I first want to go back to the basics and consider a fixed income investment — say $100 when rates are at 5%. If I give those $100 away and I get $100 back in a year risk free (no upside, no downside), then I emphatically did not break even: at 5% interest I should have got back $105, so if I made a loss of $5. I will now show that the same thing applies for an CFMM liquidity position: it should make grow over time, and after a year if <em>xi</em> returns to 1 I should get back <em>1+r </em>times my initial investment with the rate <em>r&gt;0</em> to be determined below. If I only get back my investment, my loss ratio is <em>r</em>.</p><p>So how much <em>should</em> an investment into an AMM liquidity position earn? The method I use can be applied universally, but for simplicity I will restrict myself to a CFMM, ie <em>k=x*y</em>, and I will assume that the pool is ETH/USDC for ease of language. In this case it is well known that (assuming efficient markets throughout this paper)</p><ol><li>at any point of time, the value of the ETH position is exactly the same as that of the USDC position; this holds for every numeraire, but for simplicity I assume “dollar value”</li><li>if the position was contributed at a normalized price ratio of <em>xi=1</em>, then at any point in time in the future, the value of the total position is proportional to <em>sqrt(xi)</em></li></ol><p>The best framework for analyzing AMMs is that of a self-financing trading strategy. The latter is defined as a time varying multi-asset position (possibly long and short), where the value of the position only changes because of market moves. Importantly, no assets are to be added or removed, they can only be traded. In this case, trading <em>must</em> happen at exactly the current market price, therefore trading does not impact the value of the portfolio. Because of point (1) above, it is clear that an AMM LP position can be considered a continuously rebalanced strategy that ensures that at any point of time 50% of the portfolio value is in ETH and 50% in USDC.</p><p>To show that this implies (2), it is easier to go backwards: we assume that we have a strategy whose value at any time is <em>k(t) sqrt(S) </em>where S is the spot exchange rate (and, for reference, <em>xi=S(t)/S(0)</em>). If we delta hedge this profile then the Cash Delta (see <a href="https://theammbook.org/page/paper/">here</a>, section 4) is <em>CashDelta = S d/dS sqrt(S) </em>and it is easy to see that also <em>CashDelta = 0.5 sqrt(S)</em>. In other words: <em>when delta hedging the square root profile, at any point in time 50% of the cash is invested in the risk asset, and therefore the other 50% in the numeraire. Therefore the 50/50 strategy is the replicating strategy for the square root profile. </em>/QED</p><p>I have shown <a href="https://theammbook.org/page/paper/">here (section 4.3)</a> that the Black Scholes constituent operators are diagonal on power law functions, ie if we have</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/202/1*1cRbtw4CzH3xPxTRVbdJeQ.png" /><figcaption>Definition of a power law function in the price ratio xi</figcaption></figure><p>then the constituent differential operators of the Black Scholes PDE becomes diagonal</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/564/1*bQV8AJU0ptjmtmHI_SYegA.png" /><figcaption>Diagonal action of Black Scholes constituent operators on power law functions</figcaption></figure><p>and therefore the Black Scholes PDE simplifies on this eigen basis to the following ordinary differential equation (ODE)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/876/1*YBw4hCOPE0lNUgMatjCE0g.png" /><figcaption>Black Scholes ODE on the power law eigen basis</figcaption></figure><p>Note that the term in parentheses is just a constant, so this ODE is of the well-known form <em>f’ = kf</em>, and we know that the solution to this ODE is simply <em>f(t)=f(0) exp(kt)</em>.</p><p>The square root profile is the power law function at <em>alpha=0.5</em>, so we can plug in 0.5 into the above equation to get the factor k which becomes</p><p><em>k = sigma²/8 + 0.5(r-d)+r</em></p><p>Assuming zero rates, and moving to the decay time scale <em>tau = 1/k</em> we find</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/520/1*86KpXWugQvFkSl5_VHp9Ew.png" /><figcaption>solution to the Black Scholes ODE</figcaption></figure><p>and</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/204/1*Im9mKIG3DC6TKCritAjwDA.png" /><figcaption>tau value for square root profile with zero rates</figcaption></figure><p>Now we have all we need to define Divergence Loss properly. The key insight here is that an CFMM investment strategy — 50/50 in each asset — should yield a return of <em>exp(t/tau) sqrt(xi)</em>. Instead it yields <em>sqrt(xi)</em>. This is an outright loss, akin to the “getting back $100 after a year at 5% rates” scenario discussed above. Therefore the DL has two components</p><ol><li>the difference between HODL and the CFMM value, and</li><li>the difference between the CFMM value and the fair value of the 50/50 self financing investment strategy</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/829/1*CCUImEkDo6AyAXWb6drTSQ.png" /><figcaption>Correct definition for divergence loss, including the Gamma correction term</figcaption></figure><p>In summary, the Gamma / time correction term — corresponding to the Gamma income a 50/50 strategy should make — is an integral part of the calculation of the Divergence Loss. Including this term makes Divergence Loss strictly greater than zero for t&gt;0, therefore the moniker Impermanent Loss is no longer adequate. When calculating DL in this way <a href="https://medium.com/@odtorson/why-loss-versus-rebalancing-lvr-and-impermanent-loss-il-are-essentially-the-same-85796c7df4d3">it is equivalent to the LVR measure</a>, with the DL being the macroscopic measure, and the LVR being the equivalent infinitesimal measure.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=37925604ef1a" width="1" height="1" alt=""><hr><p><a href="https://blog.bancor.network/what-we-all-got-wrong-about-calculating-impermanent-loss-37925604ef1a">What we all got wrong about calculating Impermanent Loss</a> was originally published in <a href="https://blog.bancor.network/">Bancor</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[One more thing on LVR and Impermanent Loss]]></title>
            <link>https://medium.com/@odtorson/one-more-thing-on-lvr-and-impermanent-loss-36c64e17f411?source=rss-b8621923f1b5------2</link>
            <guid isPermaLink="false">https://medium.com/p/36c64e17f411</guid>
            <category><![CDATA[il]]></category>
            <category><![CDATA[amm]]></category>
            <category><![CDATA[lvrs]]></category>
            <category><![CDATA[cfmm]]></category>
            <category><![CDATA[defi]]></category>
            <dc:creator><![CDATA[Stefan Loesch]]></dc:creator>
            <pubDate>Fri, 16 Dec 2022 09:07:01 GMT</pubDate>
            <atom:updated>2022-12-16T09:07:01.604Z</atom:updated>
            <content:encoded><![CDATA[<p>Yesterday I’ve posted an article showing that LVR and IL are essentially the same thing, at least in a Black Scholes world. Alex (<a href="https://twitter.com/0x94305">@0x94305</a>) made a good point which was “If the path starts at price p at time zero and returns to it at time 1, what is the IL between time 0 and 1?”. I realised that I need to work a bit harder here, and in fact the standard definition of IL is not suited to option analysis of AMMs. TLDR though — my point stands even though there is a trivial modification to the definition of IL to make the equivalence.</p><figure><img alt="Skinner meme — it is not my analysis that was wrong, it is the definition of IL that is wrong" src="https://cdn-images-1.medium.com/max/500/1*f8rPvcpHFXswz1b7HEK-pQ.jpeg" /></figure><p>As in my previous post I will be heavily referring to<a href="https://theammbook.org/page/paper/"> my paper on theammbook.org, specifically chapter 4.</a> The key insight here is that a liquidity provider in an AMM follows a self-financing investment strategy, and those strategy can, at least for a CFMM, be integrated into a European payoff profile. This is easiest to see backwards: if we start with a power law profile (eg the square root profile)…</p><figure><img alt="We now look at a specific class of payoff profiles, the power law profiles, ie profiles of the form να(ξ) = ξα. Those are particularly easy to deal with under the Black Scholes equation because they are eigenvectors of the Black Scholes operator. What this means is the following: the two non-trivial spatial operators in the Black Scholes equation are ξ ∂ ∂ξ and ξ2 ∂2 ∂ξ2 ." src="https://cdn-images-1.medium.com/max/1024/1*UvYXGUf8Xe1Jj9STJSTqUw.png" /></figure><p>…then the terms of our Black Scholes operator become thus…</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/694/1*JcVwbgitox5GJVoflXpwFg.png" /><figcaption>Black Scholes operators applied on power law eigen functions</figcaption></figure><p>…and our Black Scholes equation becomes thus</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/862/1*MTWvRT5SUAitAWDSBICB_Q.png" /><figcaption>The full Black Scholes PDE on the power law eigen functions</figcaption></figure><p>Ignoring the carry terms and only considering the one relating to Gamma, the solution of this equation is</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/516/1*AdkfCTteRRsOmU0RPW99dQ.png" /><figcaption>The solution to the previous equation</figcaption></figure><p>For the specific case alpha=0.5, the function nu_alpha(xi) is sqrt(xi), and the “time decay constant” tau becomes</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/198/1*5MzfNTkQcXkQgBVBVf-UqA.png" /><figcaption>Calculating tau</figcaption></figure><p>Usually in option pricing, time runs backwards, so t&lt;0 and therefore tau indeed corresponds to a decay. Here however we go forward in time: when we delta-hedge the square root profile then it <em>remains</em> a square root profile; however it expands exponentially with a time constant of <em>8/sigma²</em>. I leave it as an exercise to the reader to prove that the square root-profile indeed corresponds to the payoff profile of a CFMM <em>(hint: calculate the replicating portfolio; its value is sqrt(x), and its delta is 1/(2sqrt(x)), so at any time the strategy is invested 50/50 in each of the assets /QED)</em>.</p><p>Usually IL is defined as <em>HODL-sqrt(x)</em>. However, <em>sqrt(x)</em> is not a term the carries well over time — it is like comparing $100 today with $100 in a year’s time when rates are at 10%: you know when in a year you only get $100 back you’ve been screwed. That’s exactly the same here: if you run the 50/50 strategy then you <em>should</em> get <em>exp(t/tau)*sqrt(x)</em> after a time t. If you only get <em>sqrt(x)</em> — and Alex’s case is a special case here with <em>x=1</em> — then you have been short changed by (<em>exp(t/tau)-1)*sqrt(x). </em>In Alex’s case where x=1 your properly defined IL is essentially <em>exp(t/tau)-1 &gt; 0, </em>and this is the value that will, in a Black Scholes world, exactly correspond to the LVR.</p><p>In other words — with the appropriate definition of IL (let’s call it IL*) the initial statement is entirely correct.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/971/1*ECJGQLsJWuYV0rkKSp2rQA.png" /><figcaption>Cover Image</figcaption></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=36c64e17f411" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Why Loss Versus Rebalancing (LVR) and Impermanent Loss (IL) are essentially the same]]></title>
            <link>https://medium.com/@odtorson/why-loss-versus-rebalancing-lvr-and-impermanent-loss-il-are-essentially-the-same-85796c7df4d3?source=rss-b8621923f1b5------2</link>
            <guid isPermaLink="false">https://medium.com/p/85796c7df4d3</guid>
            <category><![CDATA[impermanent-loss]]></category>
            <category><![CDATA[loss-versus-rebalancing]]></category>
            <category><![CDATA[amm]]></category>
            <category><![CDATA[il]]></category>
            <category><![CDATA[lvrs]]></category>
            <dc:creator><![CDATA[Stefan Loesch]]></dc:creator>
            <pubDate>Thu, 15 Dec 2022 10:26:36 GMT</pubDate>
            <atom:updated>2022-12-18T15:05:57.000Z</atom:updated>
            <content:encoded><![CDATA[<p><strong>PLEASE ALSO SEE </strong><a href="https://medium.com/@odtorson/one-more-thing-on-lvr-and-impermanent-loss-36c64e17f411"><strong>THIS POST FOR AN IMPORTANT AMENDMENT</strong></a></p><p>I recently <a href="https://medium.com/@odtorson/liquidity-providers-options-and-amms-c5e4ca50819e">wrote about the AMM Triangle</a> that establishes a relationship between what I’ve call Gamma Income, Fee Income, and Option Profile. In this post I want to related those items to well-known measures in the AMM space, notably Impermanent Loss (IL) and the recently popularised Loss Versus Rebalancing. TLDR: they are the same. If you want to know more, read on.</p><p>The Impermanent Loss (that should really be called Divergence Loss) is well known and described in more detail for example <a href="https://theammbook.org/page/paper/">here (page 30)</a>. The key formula is</p><figure><img alt="IL definion (1+xi)/2 — sqrt(xi)" src="https://cdn-images-1.medium.com/max/522/1*BK4ExzA8D3GHPclNUEl9DA.png" /><figcaption>Definition of the Impermenant Loss Lambda vs normalised price ratio xi</figcaption></figure><p>Above, xi is the normalised price ratio of the two assets (it is unity to begin with), the fraction on the left is the HODL term when you hold the 50% in each asset, and the interesting term is the square-root term on the left: that is the actual value of a CFMM portfolio, and this is where the optionality of AMMs comes from. This optionality is of course linked to the fact that the AMM operates a <em>replication strategy </em>aka a <em>delta hedge</em>, and it can be shown that the strategy <em>“at every time hold 50% of your assets in either token”</em> does indeed replicated the square root profile. See <a href="https://theammbook.org/page/paper/">here (chapter 4, page 19) </a>for a more thorough discussion of this.</p><p>The concept of Loss Versus Rebalancing (LVR) AMMs has been proposed i<a href="https://moallemi.com/ciamac/papers/lvr-2022.pdf">n this paper</a> and explained for example <a href="https://twitter.com/jason_of_cs/status/1558510325770633216">in this thread</a>. The key formula here is the definition of LVR which is as follows</p><figure><img alt="LVR definition as sigma² P²/2 V’’(P)" src="https://cdn-images-1.medium.com/max/454/1*cN7rNucRgknjQgumRg1lmw.png" /><figcaption>Definition of instantaneous LVR</figcaption></figure><p>The definition above is that of the instantaneous LVR, and to obtain the macroscopic figure one needs to perform the usual stochastic integration process outlined in the paper that is usual to Brownian-motion based finance.</p><p>The term above is of course well known — it is the operative “Gamma” term of the Black Scholes equation (see <a href="https://theammbook.org/page/paper/">here, page 19</a>)</p><figure><img alt="Black Scholes equation with Gamma term highlighed; Gamma term same as LVR term above" src="https://cdn-images-1.medium.com/max/774/1*wqL56AEamvYaVmcONPgwgg.png" /><figcaption>Black Scholes formula</figcaption></figure><p>As a reminder the two terms to the left of this are the cost of borrowing for financing the delta hedge and the interest income on the option premium respectively, and whilst important in the real world, we don’t really care about them if we only want to study optionality. Below we show the same formula rewritten with the so-called “<em>Greeks”</em> which are explained in more detail <a href="https://theammbook.org/page/paper/">here (page 19–20)</a></p><figure><img alt="Black Scholes equation with Greeks" src="https://cdn-images-1.medium.com/max/716/1*X0FqlBmNngOsMOC7wDAOpg.png" /><figcaption>Black Scholes formula, rewritten with “Greeks”</figcaption></figure><p>People often think the the groundbreaking part of Black, Scholes and Merton’s work was about pricing options, but this is not entirely true: Bachelier already knew how to price options with essentially the Black Scholes formula, and even the ancient Greeks had some ideas about it. Their ground breaking idea was instead the <em>hedging</em>: they showed that, in a Brownian motion context, options could be <em>perfectly replicated via delta hedging</em>, because <a href="https://en.wikipedia.org/wiki/It%C3%B4%27s_lemma">Ito’s Lemma</a> says essentially that <em>dW²=dt</em> is deterministic and that therefore if you take care of the first order terms (the Delta) via hedging, then you pay a cost for this (the Gamma bleed; the term in red in the equation above) because you buy high sell low, but this term is deterministic.</p><p>To summarize what we’ve seen so far: the LVR is really the well-known Gamma term of Black Scholes. We know that we integrate that Gamma term we get a profile, and it turns that for a CFMM that profile is the square root component (see <a href="https://theammbook.org/page/paper/">here, chapter 4.4, page 24</a>) that is the key component of the IL. Here is therefore our update AMM triangle</p><figure><img alt="The AMM Triangle showing fee income, gamma income and option profile, with option profile replaced with IL and gamma income with LVR" src="https://cdn-images-1.medium.com/max/899/1*Ainv52l59VhMu7ftg56POw.png" /><figcaption>The updated AMM Triangle</figcaption></figure><p>In other words</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/744/1*CjtYJodL7WR_q65LX4Oomg.png" /></figure><p>—</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*l_DrBsT5ae2qeANXb0aBCQ.png" /><figcaption>Cover Image</figcaption></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=85796c7df4d3" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>