Chapter 7: Decentralized Exchanges (DEX)
Although centralized exchanges (CEX) allow for large transactions in a liquid environment, they still carry significant risks because users do not own their assets on the exchange. In 2019, over $290 million worth of cryptocurrency was stolen, and more than 500,000 login credentials were leaked from exchanges. ^10^
More and more people are becoming aware of these risks and are turning to decentralized exchanges (DEX). DEX reduces or eliminates the need for intermediaries by using smart contracts and on-chain transactions. Popular decentralized exchanges include projects like Kyber Network, Uniswap, Dex Blue, and dYdX.
There are two types of DEX—order book-based DEX and liquidity pool-based DEX. Order book DEX like dYdX and dex.blue operate similarly to CEX, allowing users to submit buy and sell orders at limit or market prices. The main difference between the two types of exchanges is that for CEX, trading assets need to be held in the exchange's wallet, while for DEX, trading assets can be held in the user's own wallet.
However, one of the biggest challenges faced by order book-based DEX is liquidity. Orders in the order book may take a long time to execute. To address this issue, liquidity pool-based DEX were introduced. A liquidity pool is essentially a reserve of tokens in a smart contract, and users can buy and sell available tokens in the liquidity pool instantly. The price of the tokens is determined algorithmically and can rise due to large transactions. DEX liquidity pools can be shared across multiple DEX platforms, which will increase the available liquidity on any single platform. Examples of liquidity pool-based DEX include Kyber Network, Bancor, and Uniswap. We will study Uniswap as a case in this book.
One of the features offered by CEX is margin trading. Margin trading allows investors to trade with leverage, increasing users' purchasing power for potentially higher returns. Innovations have also emerged to introduce margin trading on DEX. Examples of DEX that offer decentralized margin trading include dYdX, NUO Network, and DDEX. In this book, we will explore dYdX, which combines a decentralized lending market with margin trading on its exchange.
Uniswap
The Uniswap exchange is a decentralized token trading protocol built on Ethereum that allows users to swap tokens directly without using a centralized exchange. When using a centralized exchange, you need to deposit tokens into the exchange, submit an order on the order book, and then withdraw the exchanged tokens.
On Uniswap, you can easily swap your tokens directly from your wallet without going through the three steps mentioned above. You simply send your tokens from your wallet to the Uniswap smart contract address, and then you will receive the tokens you want in exchange in your wallet. There is no order book, and the exchange rate of the tokens is determined by an algorithm. All of this is achieved through liquidity pools and an automated market maker mechanism.
Liquidity Pools
Liquidity pools are reserves of tokens located on the Uniswap smart contract that users can swap tokens with. For example, through an ETH-DAI liquidity pool containing 100 ETH and 20,000 DAI, a user wanting to buy ETH can send 202.02 DAI to the Uniswap smart contract to exchange for 1 ETH. Once the exchange is completed, the liquidity pool will have 99 ETH and 20,202.02 DAI left.
The reserves in the liquidity pool are provided by liquidity providers, who earn a proportional share of the 0.3% transaction fee on Uniswap as an incentive. This fee is charged for every token swap on Uniswap.
Uniswap imposes no restrictions on liquidity providers; anyone can become a liquidity provider—the only requirement is that the liquidity provider must provide ETH and another trading token to swap (according to the current Uniswap exchange rate). As of February 2020, over 125,000 ETH had been locked in Uniswap. The amount of reserves held in the liquidity pool plays a significant role in determining how the automated market maker mechanism sets prices.
Automated Market Maker Mechanism
The price of assets in the liquidity pool is determined algorithmically through an Automated Market Maker (AMM) algorithm. The AMM works by maintaining a constant product based on the liquidity on both sides of the fund pool.
Continuing with the ETH-DAI liquidity pool example, which has 100 ETH and 20,000 DAI, Uniswap calculates the constant product by multiplying these two amounts.
ETH liquidity (x) * DAI liquidity (y) = Constant Product (k)
100 * 20,000 = 2,000,000
Using the AMM, the constant product (k) must always be maintained at 2,000,000 at any given time. If someone wants to buy ETH with DAI, ETH will be removed from the liquidity pool, and DAI will be added to the liquidity pool.
The price of ETH will be determined progressively. The larger the order size, the higher the premium. The premium refers to the additional amount of DAI required to purchase 1 ETH compared to the original price of 200 DAI/ETH.
The table on page 79 further illustrates the progressive pricing and liquidity changes when an order to purchase ETH is placed.
From the table, it can be seen that the larger the amount of ETH a user wants to buy, the higher the premium. This ensures that the liquidity pool never loses liquidity.
How to Add a New Token on Uniswap?
Unlike centralized exchanges, Uniswap, as a decentralized exchange, does not have a team or auditors to evaluate and decide which tokens to list. Instead, any ERC-20 token can be listed on Uniswap by anyone, and trading can occur as long as the given trading pair has liquidity. All users need to do is interact with the platform to register a new token, and then a trading market for that new token will be created.
That's Uniswap. If you want to get started or experiment with it, we provide a step-by-step guide on how to: (i) swap tokens, (ii) provide liquidity, and (iii) stop providing liquidity. Otherwise, please proceed to the next section to read more about the next DeFi application!
Uniswap: Step-by-Step Guide
Swap Tokens
Step 1
- Go to https://uniswap.io/ and click on "Swap Tokens."
- To start using Uniswap, you will need to connect your wallet. You can connect your Metamask wallet. Connecting your wallet is free; you just need to sign a transaction.
Step 2
- After connecting your wallet, select the token you want to trade; in this example, we will use DAI to buy ETH.
Step 3
- If this is your first time trading this token, you will need to unlock it by paying a small fee.
- The system will then prompt you to perform another transaction.
- Once your transaction is confirmed, you will receive your ETH!
Provide Liquidity
Step 4
- Go to the liquidity pool and fill in the amount of liquidity you want to provide. In this example, we will provide liquidity worth 10 DAI + 0.0461 ETH.
- Note: You must have an equivalent amount of ETH to provide liquidity for that token.
- After clicking "Add Liquidity," the system will prompt you to sign another transaction.
- Once the transaction is completed, you will be confirmed as a liquidity provider and can expect to earn a portion of the transaction fees.
Stop Providing Liquidity
Step 5
- What should you do if you no longer want to provide liquidity?
- Return to the liquidity pool and select "Remove Liquidity."
- As you can see, we will gain an additional 0.0417 DAI from just 10 DAI.
- Note that my ETH and DAI exchange rate has now changed, so this is one of the warnings of the liquidity pool; if I later remove liquidity, I may have a very different DAI to ETH exchange rate.
- Another thing to note is that when removing liquidity, I am actually trading liquidity pool tokens (Pool tokens). We can think of it as proof of your share in that liquidity pool. When you remove liquidity, you will destroy the liquidity pool tokens to retrieve your DAI and ETH.
Recommended Reading
Getting Started (Uniswap) https://docs.uniswap.io/https://docs.uniswap.io/
The Ultimate Guide to Uniswap. (DefiZap)
https://defitutorials.substack.com/p/the-ultimate-guide-to-uniswap
- A Graphical Guide for Understanding Uniswap (EthHub)
https://docs.ethhub.io/guides/graphical-guide-for-understanding-uniswap
- Uniswap --- A Unique Exchange (Cyrus Younessi)
https://medium.com/scalar-capital/uniswap-a-unique-exchange-f4ef44f807bf
- What is Uniswap? A Detailed Beginner's Guide (Bisade Asolo)
https://www .mycryptopedia.com/what-is-uniswap-a-detailed-beginners-guide/
- Are Uniswap's Liquidity Pools Right for You? (Chris Blec)
https://defiprime.com/uniswap-liquidity-pools
- Understanding Uniswap Returns (Pintail)
https://medium.com/@pintail/understanding-uniswap-returns-cc593f3499ef
- UniSwap Traction Analysis (Ganesh)
https://www.covalenthq.com/blog/understanding-uniswap-data-analysis/
- A Deep Dive into Liquidity Pools (Rebecca Mqamelo)
https://blog.zerion.io/liquidity-pools-8ac8cf8cf230
dYdX
dYdX is a decentralized exchange protocol that supports lending and margin/leverage trading. It currently supports three assets—ETH, USDC, and DAI. By using off-chain order books and on-chain settlement, the dYdX protocol aims to create efficient, fair, and trustless financial markets not controlled by any centralized entity.
At first glance, dYdX seems somewhat similar to Compound—users can provide assets (lend) to earn interest and can also borrow assets (borrow). However, dYdX further supports margin and leveraged trading, allowing for up to 5x leverage on ETH margin trading using DAI or USDC.
Lending
If you are a cryptocurrency holder looking to generate some passive income through crypto assets, you might consider lending them to dYdX for some yield. The risk is relatively low, and by depositing cryptocurrency into dYdX, interest is generated every second without any additional maintenance or management. As a lender on dYdX, you only need to focus on the interest rate (APR) you earn—which represents how much you will earn from the assets you provide.
Who Pays My Deposit Interest?
The interest you earn will be paid by other users borrowing the same asset. dYdX only allows over-collateralized loans. This means that borrowers must always have enough collateral to repay their loans. If a borrower's collateral falls below the 115% collateralization threshold (i.e., for a $100 DAI loan, below $115 worth of ETH collateral), the borrower's collateral will be automatically sold until their position is fully covered.
This adjusts according to supply and demand, ensuring that users always earn market rates. Additionally, the initial funds and earned interest can be accessed at any time.
Borrowing
As long as you maintain a 1.25x initial collateralization ratio/1.15x minimum collateralization ratio, you can borrow any supported asset (ETH, DAI, and USDC) on dYdX. The borrowed funds will be directly deposited into your wallet and can be freely transferred, swapped, or traded.
As a borrower on dYdX, the two numbers you need to pay attention to are:
(i) Interest Rate (APR) -- the amount you need to pay to repay the loan
(ii) Account Collateralization Ratio -- this is the ratio of collateralized assets to the loan amount. You can borrow until this ratio reaches 125%, and if it falls below 115%, you will be liquidated.
Margin & Leverage Trading
Trading Page
On dYdX, you can establish short or long positions with up to 5x leverage. When margin trading on dYdX, funds are automatically borrowed from the platform's lenders.
Assuming a scenario where your dYdX account initially has 300 DAI and 0 ETH. If you plan to short ETH (assuming the current price of ETH is $150), you will:
- Borrow 1 ETH ($150)
- Sell ETH for 150 DAI, leaving your dYdX balance at 450 DAI and -1 ETH
- Assuming the price of ETH drops to $100, you can now buy back 1 ETH for $100 to repay the debt
- Your final balance will be 350 DAI—your profit will be 50 DAI ($50)
Using dYdX, you do not need to actually own ETH to establish a short position. You can borrow ETH and establish a short position all in one place.
Tip:
The collateral used for margin trading will continue to earn interest, meaning you do not have to worry about interest loss while waiting for orders to complete. As of writing, this is a unique feature of dYdX.
What is Leverage?
For a trader holding 10 ETH (at $150/ETH or $1500), consider two different leverage position scenarios (using approximate numbers). In the first scenario, the trader establishes a 5x long position with 1 ETH ($150).
a. Position size is 5 ETH ($750);
b. 10% of the portfolio is at risk (using 1/10 ETH);
c. The position will be liquidated when the price drops about 10% (ETH drops $15), meaning there is very little buffer for price increases.
On the other hand, if the trader establishes a 2x long position with 1 ETH ($150):
a. Position size is 2 ETH ($300);
b. 10% of the portfolio is at risk (using 1/10 ETH);
c. The position will be liquidated when the price drops about 45% (ETH drops $65).
Essentially, leverage is just a factor that reflects how much risk a trader wants to take on (in terms of price volatility exposure), which in turn determines how far the trader is from being liquidated. Higher risk, higher reward!
Note: As of February 2020, margin positions traded in the U.S. are limited to 28 days.
What is liquidation? On dYdX, whenever a position falls below the 115% collateral threshold, any existing borrowings are considered at risk, and to protect lenders, at-risk positions will be liquidated. The collateral backing the borrowings will be sold until the negative balance is zero, and a 5% liquidation fee will be charged.
How to Calculate Profit/Loss?
For example, you opened a 5x long position with a deposit of 3 ETH at an opening price of $220.
You will need to borrow $220*12 = 2640 DAI to purchase an additional 12 ETH (locking a total of 15 ETH in your position).
If you close the position at $250, you will need to repay the loan of 2640 DAI = 2640/250 ETH = 10.56 ETH.
This will leave you with 15-10.56 = 4.44 ETH. Therefore, your profit will be 4.44-3 = 1.44 ETH.
Steps to calculate profit:
- Determine the initial leverage and deposit amount to determine position size (leverage * deposit)
- Loan amount = (position size - deposit) * opening price
- Repay loan = loan amount / closing price
- Balance = position - repay loan
- Profit = balance - initial deposit
That's dYdX. If you want to get started or experiment with it, we provide a step-by-step guide on how to: (i) earn interest through lending, (ii) borrow, and (iii) margin/leverage trading. Otherwise, please proceed to the next section to read more about the next DeFi application!
dYdX: Step-by-Step Guide
Step 1
- Go to https://dydx.exchange/
- Click on "Start Trading"
- Click on "Connect Wallet" in the sidebar
Step 2
- Select the wallet you want to connect
Step 3
- Your dYdX account has no balance
- Click on "Deposit"
- If you are a beginner, you will need to approve the token you want to deposit. In this example, I will deposit DAI
Step 4
- Enter the amount of DAI you want to deposit and continue
- After confirming the transaction, you will see your balance
Step 5
- You can now start trading.
- Here are some guidelines:
a. You can engage in margin trading or regular spot trading. Margin trading incurs interest since you are trading with borrowed funds.
b. You can choose to take a long or short position.
c. Position size refers to how much you want to buy to trade.
d. This is the amount you are borrowing. If you have 1 ETH on dYdX, you can borrow up to 5 times (your position size should now be 5 ETH).
e. Here you can set the allowable slippage for your position price.
f. The size of your margin (borrowed funds) determines the interest you will pay.
Step 6
- Alternatively, you can borrow ETH, USDC, or DAI
- You will need to provide collateral before borrowing
- You will need to approve the tokens used for collateral before you start borrowing
Recommended Reading
dYdX Exchange Review http://defipicks.com/2019/11/23/dydx-exchange-review/
Margin Trading on Centralized vs. Decentralized Exchanges (Syed Shoeb) https://medium.com/nuo-news/why-you-should-choose-decentralized-margin-trading-over-centralized-e309e61e6e72
Liquidators: The Secret Whales Helping DeFi Function