Cryptocurrency exchange

How to swap crypto currencies

A cryptocurrency exchange is an application that allows customers to trade cryptocurrencies for other assets, such as conventional fiat money or other digital currencies. It can be centralized (CEX) or decentralized (DEX).

An exchange is assessed according to the following quantitative metrics:

  1. daily trade volume: it reflects the amount of cryptocurrency that is bought and sold in a single day

  2. number of cryptocurrencies and number of fiat currencies supported

  3. number of markets: the number of coin pairs A/B such that it is possible to exchange coin A with coin B and vice versa

  4. liquidity: the average liquidity of markets (pairs of coins). For a given market, liquidity is proportional to the number and size of buy and sell orders that have been placed and reflects the ease or rapidity with which one can buy or sell a coin close to its market price in the market

  5. web traffic: the traffic of the website of the exchange, in terms of number of visits, unique visitors, bounce rate, time on site

Centralized cryptocurrency exchange

  • a centralized cryptocurrency exchange (CEX) is a platform owned by a private company where you can buy or sell digital assets

  • on a centralized exchange you have to trust a third party to monitor the transaction and secure the assets

  • such exchanges require you to submit your personal information for verification (Know Your Customer or KYC process)

  • the KYC process is also a legal requirement intended as an Anti-Money Laundering (AML) measure, which describes the legal controls that require financial institutions to prevent, detect and report money laundering activities

  • here is a list of most popular centralized cryptocurrency exchanges

Order book and orders in CEXs

  • in a centralized exchange each listed pair of coins has an order book, which is a digital book where sell orders (colored in red) and buy orders (colored in green) are placed

  • the price is determined in real time by the match of sell and buy orders

  • each sell order (red) has a price larger than the market price and must match some buy orders to fulfill it; it will decrease the price of the coin

  • each buy order (green) has a price smaller than the market price and must match some sell orders to fulfill it; it will increase the price of the coin

  • orders can be of three types:

    • market, executed at market price; these orders are not included in the order book but will remove some orders from the book, hence they are referred to as market taking

    • limit, executed if and only if the price reaches a given value or better (lower than market price for buy orders and higher than market price for sell orders); these orders enter the order book when placed and hence they are referred to as market making

    • stop-limit: if the stop price is reached, a limit order at a given price is placed in the order book. These are used to limit the losses (stop-loss). For instance:

      • I buy a coin hoping in an increase of the price (to sell higher), but instead the price decreases and I stop-loss by selling at a given lower price (for instance, the limit is 10% lower than the buy price)

      • I sell a coin hoping in a decrease of the price (to buy lower), but instead the price increases and I stop-loss by buying at a given higher price (for instance, the limit is 10% higher than the sell price)

  • see here an example for the market pair BTC/USDC on Binance exchange

Decentralized cryptocurrency exchange

A decentralized cryptocurrency exchange (DEX) is similar to a centralized exchange, except:

  1. it does not have a third party on which you can rely and must trust. Instead, the exchange activity is automatically operated by smart contracts (that you must trust)

  2. you do not need to deposit your funds on a custodial wallet but you operate directly from your non-custodial (hot or cold) wallet

  3. you can swap only fungible tokens (ERC-20 on Ethereum); you cannot exchange native cryptos (like bitcoin and ether) or fiat (like USD and EUR). For this reason, native cryptos are wrapped into tokens (like WETH and WBTC for ETH and BTC) and fiat are represented by stablecoins

A popular and long-lived example is Uniswap.

How Uniswap works

  • Uniswap is a protocol for exchanging ERC-20 tokens on Ethereum

  • the original idea comes from Vitalik Buterin, the mind behind Ethereum blockchain

  • each liquidity pool on Uniswap is a pair of tokens on Ethereum (a market on a CEX)

  • a pool is defined by a smart contract that contains functions in order to:

    • swap the tokens of the pool (market taking, you pay a fee)

    • add liquidity to the pool (market making, you receive a reward)

  • the price of the tokens are defined by the ratio of the balances of the two tokens of the pool; in particular there is no order book with sell and buy orders

The invariant formula

  • at its core each pool uses the invariant function xy=kx \cdot y = k to maintain a curve along which trades can happen, where x is the balance of the first token and y is the balance of the second token in the pool, while k is a positive constant

  • for each trade (swap) a certain amount of tokens are removed from the pool for an amount of the other token: if I swap A for B, I'm adding A and removing B from the pool. The amount of B tokens received is computed so that the invariant formula holds

  • this changes the balances held by the smart contract, therefore changing the price (the balance ratio). If I swap A for B, I am selling A and buying B. The quantity of A tokens in the pool will increase (and its price decrease), and the quantity of B tokens in the pool will decrease (and its price increase)

  • notice you can't empty the pool on either side since if either x or y is 0, the invariant equation doesn't hold anymore

Swap tokens on a DEX
# balance of token X
x = 100

# balance of token Y
y = 10

# price of X (wrt Y): X is worth 0.1 Y 
y / x

# price of Y (wrt X): Y is worth 10 X
x / y

# constant k
(k = x * y)

# swap X against Y (sell X to buy Y)
# swap x1 = 10 tokens of X for a number y1 of tokens of y 
# use invariant formula (x + x1) * (y - y1) = k to compute y1 = y - k/(x + x1) 
x1 = 10
(y1 = y - k/(x + x1))

# new balances of X and Y
(xn =  x + x1)
(yn = y - y1)

# check invariant
xn * yn

# new price of X wrt Y 
# (lower than before since there is more X in the pool or you sold X)
yn / xn

# new price of Y wrt X  
# (higher than before since there is less Y in the pool or you bought Y)
xn / yn

Liquidity providing

  • but to swap tokens, you have to fill the pool: who fills the pool with liquidity?

  • anyone can become a liquidity provider for a pool by depositing an equivalent value of each underlying token in return for liquidity provider (LP) tokens

  • these tokens track liquidity provider shares of the total reserves, and can be redeemed for the underlying assets at any time

  • sometimes these LP tokens can be stacked to farm additional tokens (like token UNI for Uniswap)

  • recall that each trade costs a fee, which is added to the pool reserves; this functions as a payout to liquidity providers, which is realized when they burn their LP tokens to withdraw their portion of total reserves

  • divergences between the Uniswap price for tokens and external prices (for tokens listed elsewhere) create arbitrage opportunities

  • arbitrage ensures that Uniswap prices always trend toward the market-clearing price (the equilibrium price at which quantity supplied is equal to quantity demanded)

  • however, this arbitrage process is costly, and thus liquidity providers might incur in the so-called divergence or impermanent loss:

    • divergence: the loss is proportional to the difference in price of tokens between deposit and withdrawal

    • impermanence: the loss is realized if and when the liquidity provider withdraws their liquidity

Swap tokens on Uniswap
  1. connect Metamask to Sepolia testnet

  2. go to Uniswap

  3. swap some ETH into WETH (wrapped ETH)

  4. view the WETH token on your account on Etherscan

Notice there are no WETH tokens in your Metamask. This is because you have to first import the token WETH into Metamask. Let's do it:

  1. view the swap transaction on Etherscan

  2. click on WETH contract address

  3. manually add the token to your Metamask under Tokens

Last updated