Exploring DeFi trading strategies: Arbitrage in DeFi
November 4, 2019, 5:25PM EST · 24 min read
- DeFi markets are fragmented and inefficient which are fertile ground for arbitrageurs to develop strategies in. Two categories of arbitrage strategies in DeFi we focus on in this piece are yield arbitrage (interest rate and staking) and cross-DEX arbitrage
- DeFi infrastructure has new features such as atomic batch-based processing of transactions which potentially enable new trading strategies with no analog in traditional financial markets
- Both yield and cross-DEX arbitrage seem to be short-lived opportunities for arbitrageurs, the former because of aggregators like Topo Finance and the latter because they’re being stopped outright by DEX builders because of their negative effect on liquidity and on Ethereum more broadly
Alex Obadia leads Research and Platform efforts at Cambrial Capital, a fund of crypto funds based in London and Berlin. He also organizes the London DeFi Summit and the monthly Zero Knowledge London meetups. This piece is purely for informational purposes; nothing in this post should be construed as investment advice.
Decentralized Finance (DeFi) is a term created around a year ago to describe the movement of projects dedicated to building a new transparent, permissionless and programmable financial infrastructure. A year later, the movement has grown in size, followers and diversity to be considered a promising short-term catalyst for the next wave of blockchain-based technology adoption. Although DeFi has grown, its markets remain inefficient and fragmented compared to their centralized counterparts.
Market fragmentation and inefficiencies are music to the ears of traders seeking alpha. This piece is a product of Cambrial’s research on the investability of these opportunities and the novel considerations they involve. As a fund of crypto funds, we’re interested in these opportunities as a potential source of durable, absolute, uncorrelated to traditional markets, attractive risk-adjusted returns. We believe those returns are subject to different risks than ‘traditional’ crypto trading returns and therefore can improve risk diversification within a portfolio of crypto trading strategies.
This post will examine arbitrage opportunities in DeFi splitting them into yield arbitrage and cross-exchange arbitrage. The aim is to provide 1) an understanding of some of the strategies being run on this new infrastructure including the risks they involve, 2) beginning of thoughts on the durability of these strategies and the (re)definition of arbitrage in DeFi. Some knowledge of DeFi is assumed and we recommend reading this introduction to DeFi if you’re new to the subject.
The quasi-simultaneous purchase and sale of an asset, or similar assets, to profit from an imbalance in its price on different markets or in different forms. (Source)
The fragmentation and inefficiencies of DeFi markets mean that prices for the same financial instruments vary across different DeFi venues (fragmentation) and adjust differently to the same market movements (inefficiencies). In other words, these are fertile ground for arbitrage trades. We split DeFi arbitrage strategies in two categories: yield arbitrage and cross-exchange arbitrage.
1. Yield arbitrage
Yield arbitrage strategies are executed between different lending products (i.e. interest rate arbitrage) or between staked assets. These strategies are profitable today as rates are significantly fragmented across the space and relatively non-competitive. Capacity (i.e. how much money can be put into these), although hard to estimate, is a function of traded volume and outstanding available tokens. Below are three examples of yield arbitrage trades, along with the risks involved with them, executed by our imaginary trader Bernie:
Eg1. Cross-asset single platform interest rate arbitrage
⇒ On May 18th, our trader Bernie is using Compound V2, a transparent, autonomous money market that allows users & applications to frictionlessly earn interest or borrow Ethereum assets without relying on a counterparty.
⇒ He notices the borrowing APR of USDC (7.8% p.a.) is below the supply APR of DAI (14.5% p.a.).
⇒ Suppose Bernie is already in possession of DAI.
⇒ Bernie borrows USDC stablecoin against DAI collateral.
⇒ He then converts said USDC into DAI.
⇒ Finally, he lends his newly acquired DAI, making a 6.7% p.a. spread.
(Data source: Loanscan)
The main risk of this opportunity is its episodic nature and the potential for disadvantageous rate changes possible with variable interest rate debt products. Other risks include variable transaction costs (i.e. gas) that have to be included in the inequality (USDC borrowing APR < DAI supply APR + transaction costs), the implicit market risk of the USDC/DAI and DAI/USD pairs (i.e. peg deviation risk) and systemic risk (i.e. failure of Compound smart contracts).
Chart: Spread between DAI lending rate and USDC borrowing rate on Compound V2
One can imagine other declinations of this strategy such as cross-asset cross-platform interest rate arbitrage (eg. between margin trading platform DyDx and Compound) and single-asset cross-platform interest rate arbitrage. Executing a trade across lending platforms invites new considerations such as the different rate change mechanisms. (i.e. Compound has linear borrow and superlinear supply rate curves while dYdX has a superlinear borrow and supply rate curve).
Eg2. BlockFi/DyDx interest rate arbitrage
⇒ DyDx is an open trading platform for crypto assets where users can margin trade with up to 5x leverage, borrow and lend trustlessly. BlockFi is a custodial lending platform that allows users to borrow and lend large market-cap cryptoassets such as Bitcoin (BTC) or Ethereum (ETH).
⇒ Again, suppose Bernie is already in possession of DAI or USDC.
⇒ Bernie borrows ETH on DyDx (at an initial rate of 0.99% p.a.) with DAI or USDC as collateral.
⇒ Bernie can then lend that ETH on BlockFi for 3.3% p.a.
(Source: Binance research)
The risks to this opportunity are the variable rate change risk mentioned above (which have shown to change rather fast in the past for BlockFi), liquidation risk on DyDx (which includes basis risk/social loss risk too and depends on price volatility of ETH), smart contract risk and loan matching delay on BlockFi’s side should you not find a borrower immediately.
Eg3. Staking yield arbitrage
⇒ Staking can enable token holders to generate yield on their tokens as a reward for contributing to the token’s network.
⇒ Suppose Bernie’s token X is currently making 5% p.a. staked.
⇒ As Bernie currently doesn’t need to use his token X, he swaps it for another asset, say XTZ (Tezos), which has a higher yield of 7.1% at the moment.
⇒ When Bernie needs to use the X token he swaps his XTZ back to X, pocketing the extra 2.1% p.a. yield generated.
(Data source: Staked)
There are five key risks to this opportunity:
1) Asset swapping can prove difficult depending on the liquidity profile of the asset X and where it is available. For long-tail low liquidity assets there is a risk of market impact and slippage dependent on the size of your position.
2) While an asset can be staked, it can sometimes have a lockup period which makes the succinct swapping hard although staking secondary markets are opening (e.g. Vest),
3) Staking yield is token-denominated which means your staking reward is subject to the token’s network inflation rate and to the possibility of a depreciation in value in $ terms.
4) Similar to the previous risk, Bernie will be exposed to the X/XTZ pair market risk before he swaps back to X. Bernie could hedge himself to be protected against that risk.
5) There are new risk dimensions to take into account such as smart-contract risk and slashing risk (i.e. improper staking will be punished by slashing a fraction of the amount staked).
Table of stakeable assets ranked by ‘share’. ‘Share’ represents the token-denominated yield left after accounting for the network’s inflation. (Source: https://beta.stakingrewards.com/)
While the examples above seem to be easy to reproduce, we believe an edge in yield arbitrage will come from efficient allocation to the relevant protocols/platforms and rigorous risk management practices. For interest rate arbitrage, lending rates change dynamically as users allocate funds to lending protocols. This means a large amount of capital (~$40k today) allocated at once will suffer from significant slippage costs. Proper order execution that keeps in mind the rate change mechanics of each of the lending platforms you’re interacting with and allocates efficiently dollar for dollar is required in order to be successful and we believe is a legitimate edge.
However, this edge doesn’t seem very durable as aggregation services like Topo Finance are cropping up. These services offer users the best lending rates and borrowing rates in DeFi through their aggregation and optimisation of many available rates. While they are currently not offering cross-asset lending optimisation, the Topo Finance team has indicated this is on their roadmap. The question then becomes how long it will take for this edge to fade away.
The argument above points to a short timeline yet it’s worth remembering that a lot of institutional players will feel more comfortable investing in a fund that runs such a strategy rather than putting money in a retail focused product. The answer might therefore not be as binary as we’ve put it above but rather both might co-exist, at least for the medium term, catering to different pools of capital.
On the longer term, services like Topo Finance are chipping away at the arbitrage opportunity by effectively redistributing to the users value that yield arbitrageurs would usually capture while at the same time tightening the spreads between lending rates and the gaps between lending protocols. This is a major reason DeFi could be the catalyst to retail blockchain adoption as it offers a clear advantage over traditional financial infrastructure: public, machine-readable data combined with open endpoints, resulting in lower barriers to entry and, ultimately, better value redistribution for the user.
2. Cross-exchange arbitrage
Moving on from yield arbitrage trading opportunities which have diffuse return distribution dynamics, we now focus on finite, scarce and winner-take-all arbitrage opportunities in decentralized finance. Of particular interest to this piece is cross-exchange arbitrage between decentralized exchanges and the resulting gas bidding wars trading bots engage in. In cross-DEX arbitrage, traders will typically continuously scan decentralized exchanges order books to execute a series of trades sequentially between different trading venues with the goal to end up with more money than they started with. Below is an example of a triangular arbitrage trade between two decentralized exchanges OasisDEX (now Eth2DAI) and Uniswap, and the pairs DAI/MKR, MKR/WETH and WETH/DAI which leads to a 1.6% profit.
http://ethtx.info, Analysis for: 0xa595a252a5324d520d17de440e71ba23c622dbdaf8a5f6a3d88c866b0fbdf88c. Thanks to OasisDEX for developing this tool and to Bartek for sharing it in his excellent presentation at DeFi Summit London.
This is where it gets interesting! Although the above looks like any other triangular arbitrage trade there are two fundamentally new aspects of trading on this infrastructure absent from traditional cross-exchange arbitrage: atomic batch-based processing of transactions and priority gas auctions.
2.1 Atomic batch-based processing of transactions
Since Ethereum is a smart contract system that is Turing-complete (i.e. allows encoding of arbitrary smart contract functionality) and smart contracts atomically-execute programs written in Turing complete scripting languages, one can ‘encode’ within a single transaction sent to a smart contract an arbitrary number of orders which will be atomically executed by miners.
These orders can be of arbitrary complexity and can have complex conditional preferences on trade execution. An example of a conditional preference is throwing an exception to the atomic batch execution if one order fails (i.e. everything gets cancelled, similar to traditional complex order types like ‘fill or kill’). Several people have caught onto this feature of Ethereum, including for a moment Marble, a service that offered flash lending for exchange arbitrage. “A trader can borrow from the Marble [smart contract] bank, buy a token on a DEX, sell the token on another DEX for a higher price, repay the bank, and pocket the arbitrage profit all in a single atomic transaction.”
https://github.com/marbleprotocol/flash-lending Marble’s Flash Lender basic architecture which can be used to execute arbitrage trades on decentralized exchanges.
This is interesting as, traditionally, success of multi-legged arbitrage is measured probabilistically as there are chances individual legs fail (‘legging risk’). While the success of multi-legged arbitrage in DeFi is also measured probabilistically, this non-determinism now stems from the likeliness of being included in an Ethereum block (and it not being orphaned) rather than the success of an individual leg since these are executed atomically and fully cancelled should one not work.
You can now build arbitrarily complex orders all within a single Ethereum transaction which has no analogue in traditional markets. This has implications in the types of strategies one could run in this new world. In the old world, some complex multi-legged arbitrages strategies never see the light of day because they rely on many components, each with a risk of failure. Since these compound, win rates can collapse dramatically. How many discarded strategies will work on this new infrastructure and what will new complex systematic arbitrage strategies look like?
It's worth noting this property might not exist anymore as Ethereum upgrades to Ethereum 2.0. In short, the Ethereum 2.0 network will be broken into different parts (shards). In this sharded world, it is possible two DEXs you execute arbitrage strategies between are on two different shards, meaning also two different network states. While transactions within a shard could happen as before, transactions between shards can still happen but in an asynchronous fashion, using receipts. This worried entrepreneurs who depend on this feature for their service/product during DevCon 5 and prompted Vitalik to write a post about it.
Back to the current version of Ethereum, it seems like traders can now execute arbitrarily complex riskless multi-legged arbitrage without worrying about traditional exchange counterparty credit risk (as they’re operating on non-custodial venues) and legging risk (as they execute all their trade legs ‘at once’). However there are novel nuances and risks to take into consideration:
- Smart contract risk: the risk that a bug in the smart contract you’re interacting with puts your funds at risk which has happened in the past. Although it is hard to assess that risk, there are ways to minimize it such as purchasing smart contract insurance, limiting yourself to interacting with audited and regularly kept up smart contracts.
- Gas spend: the risk that excessive gas spend makes the trade unprofitable. The more computational steps your transaction has, the more gas you will pay to execute it. This can make the whole trade unprofitable if optimized badly, more on this in the next section.
- Liquidation risk: the risk that a sudden price swing in Ethereum or other volatile collateral used wipe out leveraged positions. Arbitrageurs who use leverage in DeFi interact with lenders/borrowers and overcollateralized loans. While posting additional collateral to avoid liquidations can mostly be done independently from liquidity, there is an important risk that in a case where the Ethereum network is overloaded, you cannot post additional margin and get liquidated. This happened recently to DeFi Saver.
- Structural risks: no DeFi product today is fully decentralized but rather sits on a spectrum of decentralization. This has an impact on the security of your funds and exposes you to risks that include oracle manipulation risk (eg. the recent Synthetix oracle attack) and administrative control risks where you entrust the teams building the product you use.
Even though the infrastructure is transparent and its information available for anyone to tinker with, these risks today are hard to quantify and therefore hard to price in trades. Many are hard at work on these issues, such as ConsenSys who have recently released a risk-scoring system and Nexus Mutual who have started evaluating smart contract cover in order to offer smart contract insurance (e.g. insuring Uniswap). In a world where smart contracts can be insured and risks of trading with them are better understood, does multi-legged arbitrage in DeFi become less risky than on centralized trading platforms?
2.2 Priority Gas Auctions (PGAs)
Since arbitrage opportunities are scarce and offer winner take all returns, traders have to optimize their latency to compete effectively. In contrast to traditional finance where latency is about connectivity, computational speed optimization and special rights such as co-location, here, on Ethereum-based infrastructure, latency is related to gas spend and efficient blockchain networking monitoring.
As a reminder, Ethereum transactions consume gas, akin to a transaction fee, distributed to the miner executing the transaction. The more gas is spent, the higher the chances are of the transaction being selected from the mempool to be included in the next block and being confirmed. Think of the mempool like the waiting room for transactions before they are confirmed.
Practically, when a trading bot goes for an arbitrage opportunity this is what happens:
- Bot #1 submits its transaction containing several sub-orders at a certain gas price, hoping it’ll be enough to go through based on current gas prices which can be seen on platforms such as EthGasStation.
- Meanwhile, bot #2 may either have also spotted the same opportunity, or can see the transaction of bot #1 in the mempool.
- In both cases, bot #2 will submit the same transaction with a slightly higher gas fee, in order to ensure it will be picked first by miners.
- Meanwhile, bot #1 notices someone is trying to ‘frontrun’ them and ‘modifies’ its transaction to include a higher gas fee. Bot #1 can alternatively have a strategy to naively up its gas spend at frequent intervals expecting competition.
This game goes on until a bot ‘wins’ or the opportunity becomes unprofitable (i.e. gas spend > total profit through arbing the spread) for one of the bots, and they cancel their bid entirely, paying only ‘cancellation gas fees’ which are significantly less than execution fees.
Interestingly, Phil Daian et.al in the paper Flash Boys 2.0: Frontrunning, Transaction Reordering, and Consensus Instability in Decentralized Exchanges found bidding bots organically collaborate with each other to maximize their profits through ‘grim-trigger’ cooperative strategies (i.e. if a bot ‘misbehaves’, another in the auction will immediately raise its bid to the maximum amount thereby eliminating all profitability from the auction). The expected payoff from adhering to such cooperative strategy is larger than the expected payoff from deviating from it. The paper formally describes this strategy and goes on to prove there exists a cooperative Nash equilibrium for a 2-player auction where both players follow the grim-trigger cooperative strategy mentioned above!
You can visualize real time auctions taking place on frontrun.me
One example PGA that was observed over the Ethereum network. The top graph shows the gas bids of two observed bots over time, while the bottom table details the first and last two bids placed by each bot and the two mined bids (center),
Diagram taken from page 5 of Flash Boys 2.0: Frontrunning, Transaction Reordering, and Consensus Instability in Decentralized Exchanges. Although the auction has ended after 4.94 seconds by a miner including it in the next Ethereum block, bots will only know it once the block is mined and the new Ethereum network state propagated. They therefore keep bidding.
Optimising for gas spend is therefore the most obvious way to compete. To do so, traders trim down their execution logic (since expressing the same set of instructions using less computations results in lower gas spend for an equal outcome) and use tools such as the GasToken to essentially buy gas earlier on, when it is cheaper, and use it when it is more expensive to make the economics of their trade more profitable. A way to think of the GasToken is like setting up your electric boiler so it heats up water during non-peak hours so that you can then use it during peak hours.
‘Deployed PGA measurement infrastructure architecture’, Diagram taken from page 6 of Flash Boys 2.0: Frontrunning, Transaction Reordering, and Consensus Instability in Decentralized Exchanges
Aside from gas optimisations, other dimensions traders will compete on include infrastructure (running nodes with high uptime and more flexible actions, geographically distributed nodes to monitor Ethereum mempools) and data analysis capabilities which we believe are both sources of edge.
An example of an infrastructure architecture is shown above. It’s worth noting the cost of deploying such an infrastructure using for example AWS is in the low five-figures a month. The current size of the investment opportunity as outlined in Flashboys 2.0 therefore does not seem worth the infrastructure costs, especially given the uncertainty around the gossip topology of Eth2.0 which might render this infrastructure useless.
Additionally, beyond infrastructure there is the matter of efficient blockchain data analysis. While getting a global image of the mempool is no easy feat, picking a transaction sitting there, looking into the address that triggered it and its transaction history and simulating the transaction (and its sub-transactions) to verify it is a net profit for you is an arduous task. Add to that the time constraint of 10-20s block time for Ethereum (vs microseconds for traditional HFT) to participate in the PGA and you can understand how important efficient data processing and parsing becomes in these strategies. This is especially true as off-the-shelf monitoring tools currently don’t exist and therefore have to be developed in house. More generally there are no standards around data interpretation in DeFi even when it comes to simple data points like DEX volumes of the most traded pair, ETH/DAI. (Source: Past, Present and Future of OasisDEX by Bartek Kiepuszweki (MakerDAO))
To learn more about these auctions, I recommend reading the excellent paper Phil Daian et al. authored on the subject entitled Flash Boys 2.0: Frontrunning, Transaction Reordering, and Consensus Instability in Decentralized Exchanges where the title of this section, Priority Gas Auctions (PGAs), originates. These PGAs are fascinating as they are changing the way arbitrage traders operate and sustain their advantage over other traders. This is interesting to us at Cambrial as we spend our time talking to managers and understanding their strategies’ edge. However, similar to the point in the previous section about the yield arbitrage opportunity disappearing, we believe cross-DEXs arbitrage strategies won’t remain for much longer primarily because many are working to stop them as they are bad for DeFi and Ethereum more broadly:
- Bad for Ethereum consensus security: As detailed in Flashboys 2.0, PGA bot activity provides economic incentives for miners to ‘frontrun traders in the past’ via runtime bandit and fee based forking attacks. Effectively, miners take on costs of attacking the chain to rewrite its history and put themselves on the other side of winning trades. This undermines Ethereum’s consensus security by misaligning miners with the rest of the Ethereum ecosystem. More specifically, you could imagine the network effectively halt as the same block keeps being mined over and over.
- Bad for Ethereum bandwidth: Gas optimization tools such as GasToken bloat the Ethereum network by filling Ethereum blocks with ‘ghost’ transactions which has a negative impact on all Ethereum users by raising transaction fees unnecessarily.
- Bad for market makers: Whenever a sudden price movement occurs on one exchange, there is a transient period where mis-priced (‘stale’) limit orders remain available at other venues. Automated trading bots take advantage of this by filling these orders before market makers are able to cancel them. These bots are therefore forcing market makers to quote more widely compared to traditional exchanges to compensate for their losses. This results in a higher price of liquidity for everyone. Projects such as Kyber Network, with their recently announced gas limit, and 0x with Coordinators have started taking steps to mitigate such issues.
3. Generalized taking strategies in DeFi
Congrats on making it this far! The TL;DR on part 1 and 2 above is that both yield arbitrage and cross-DEXs arbitrage strategies seem to be short-lived opportunities for traders. The former because the value it traditionally creates for traders is being redistributed to the users, the latter because it’s being stopped outright. The natural following question then becomes do arbitrageurs as we know them traditionally even have a place in this new world?
The answer is a resounding yes, at least for now, as there are financial protocols where arbitrageurs are needed to ensure the good functioning of the protocol. One example is the automated market maker Uniswap where constant arbitrage between Uniswap pair pools and other decentralized exchanges is required to keep the rate offered in lockstep with the market rate for the pair’s assets. However, the tide seems to be turning, not necessarily pointing to a disappearance of arbitrageurs rather a redefinition of what it means in DeFi.
One example of this redefinition is the recently announced Balancer: “Balancer turns the concept of an index fund on its head: instead of paying fees to portfolio managers to rebalance your portfolio, you collect fees from traders, who rebalance your portfolio by following arbitrage opportunities.”
In other words, the value arbitrageurs usually capture for themselves is partly redistributed to the users who will now enjoy a unique index fund product. However while arbitrageurs are recognized as useful to the system, they are limited in their profit capabilities.
Another example is the asset-backed stablecoin DAI. DAI relies on arbitrageurs (Keepers) to liquidate CDPs when they fall below the required collateralization ratio. These liquidation opportunities are latency sensitive and Keepers engage in priority gas auctions with each other to fill them. DAI is set to switch to Multi-collateral DAI (MCD) from its current single collateral system (i.e. ETH). When MCD happens, liquidations for each collateral involved in MCD will switch to English auctions by default. This means competition between takers will be about their internal systems optimization rather than external latency games.
MKR.tools 3-months Maker CDP bites overview where every circle represents a CDP liquidated. At the centre is CDP 16619 of nearly $4M which was liquidated on September 24th when ETH suddenly dropped from $200 to $165. This resulted in about $120k in liquidation profits.
Other DeFi protocols have also chosen to use auctions such as TokenSets rebalancings that use a Dutch auction and Gnosis’ decentralized exchange DutchX. Auctions contribute to a healthier DeFi ecosystem by shifting the competition to price (and a traders’ internal systems) rather than network latency which we’ve seen above causes a plethora of issues. This is ultimately fairer and allows for better price discovery. This again changes the definition of an arbitrageur as the individual with the best optimized internal systems to be able to fill opportunities which wouldn’t be profitable to others. We wonder here again how limited profit capabilities will be in such a system.
This leads us to question how much money can be made by developing a trading system in DeFi. This is a hard question to answer as the capacity and the profitability of these strategies is rather hard to estimate, especially considering what is mentioned above is simplistic and in reality multiple strategies are run in parallel, often with synergistic relationships. Nonetheless, this question is important to us as it dictates the fee structure a fund would explore in order to sustain their costs and whether the current opportunity is attractive enough to justify the necessary team and upfront investment in infrastructure to run it.
As an example of synergistic relationships between strategies, one could market make on the ETH/DAI pair (the most liquid pair) on DEXs while also biting Maker CDPs opportunistically and arb’ing any peg deviation of DAI. That way, your DAI inventory is kept active, your market making infrastructure is also used for biting MakerCDPs + arb’ing any peg deviation and you already have enough supply to bite CDPs should a lot of liquidations become available after a sudden depreciation of the price of ETH.
DeFi markets are a small percentage of overall trading volume related to blockchain-based products. While they have a long way to go to grow that volume to meaningful numbers, we’ve seen some encouraging growth in this sector and are excited about the trading strategies its new features enable.
However, our excitement is balanced by our suspicion that the strategies described above are short lived opportunities for traders and imply more risks than first anticipated. This is especially true of strategies like cross-DEX arbitrage and liquidation premiums which are used as bootstrapping mechanisms by protocol builders but will become a pure drag when those networks reach a steady state. This invites the question whether these strategies warrant a trader’s interest and an investor’s work.
We built Cambrial on the premise that ‘crypto’ is a new asset class, and that similar to the rise of hedge funds in the late 90s, out of a new asset class are born new trading opportunities and strategies. This is right in our sweet spot and we’re looking forward to following, and investing in, these strategies as they evolve.
© 2021 The Block Crypto, Inc. All Rights Reserved. This article is provided for informational purposes only. It is not offered or intended to be used as legal, tax, investment, financial, or other advice.