How to Simulate a Liquidity Pool for Decentralized Finance

Ian Moore, PhD
9 min readMar 10, 2023
  • Mini tutorial on how to simulate a Liquidity Pool (LP) using the UniswapPy python package
  • Utilizes Geometric Brownian Motion process to simulate asset price
  • Solves LP holdings of x, y pairing given asset price

February 2024: for all major protocols checkout our DeFiPy python package

1. Introduction

An automated market maker (AMM) protocol is the mechanism used by decentralized exchanges (DEXs) and was first introduced by Uniswap, which was launched on the Ethereum mainnet in November 2018. These DEXs consist of liquidity pools (LPs) represented by various trading pairs (eg. ETH/USDC, ETH/WBTC, etc.) acting as the AMM. Trading activity within these LPs are governed via smart contract through the constant product trading formula (i.e., xy = k).

In this article we will cover the basics on how to simulate a LP for Decentralized Finance (DeFi) using the UniswapPy python package. The motivation for this tool came out of the need to mitigate losses and maximize yield for a new smart DAO (i.e,, DAOSYS [1]) that we are setting up on Syscoin’s soon to be launched L2 network (Rollux) which is expected to go live mid-to-late 2023 [1]. In this article we provide the considerations on how to simulate LPs using python, which can be used as a starting template for researchers and devs looking to design, enhance or research their own DEX.

2. Geometric Brownian Motion

Brownian motion (or Wiener Process) is a type of non-stationary stochastic process used to model natural phenomena studied in the Applied Sciences, and is represented as the following distribution:

where t represents some time period. A well-known risky asset model for prices, Sₜ, are represented by the following differential equation:

where μ represents the drift and σ represents the volatility of the asset. The solution to the asset model of dSₜ is given by:

which is known as Geometric Brownian Motion (GBM). The idea of using Sₜ to model stock prices was first discovered by Bachelier [2] and popularized by Samuelson [3]; details on the derivation of this solution can be found in Chapter 1 of [4]. For this discussion, we will be using a GBM to simulate the prices our SYS/USD asset using our BrownianModel class. See the following code block for the setup:

# -----------------------------#
# BLOCK 1: Generate GBM
# -----------------------------#

from uniswappy.math.model import BrownianModel
import numpy as np

# Instantiation Parameters
n_steps = 5000 # Number of steps
start_price = 0.1 # Initial price SYS/USD
mu = 0.3 # mu GBM process
sigma = 0.5 # sigma GBM process
n_paths = 25 # Number of simulationed paths

# Brownian Model
bm = BrownianModel(start_price)
p_arr = bm.gen_gbms(mu, sigma, n_steps, n_paths)

# Calc. price expectation
exp_p_arr = numpy.median(p_arr, axis = 1)

In Fig. 1 we plot the outcomes from the above implementation.

Fig. 1 Set of simulated geometric Brownian motion (GBM) price sequences paths, where σ = 0.1 and μ= 0.1 representing simulated SYS/USD prices

3. DeFi Python Simulator

Despite popular perception, treasuries of Decentralized Autonomous Organizations (DAOs) tend to be centrally controlled and do not reflect the true ethos of cryptocurrency (i.e., not your keys, not your coins). Syscoin is solving this problem via DAOSYS [1], which is a new smart DAO protocol technology for DeFi, which will be launched sometime in 2024 on Syscoin’s L2 Rollux platform.

To realize proper tokenomics design, it is highly inefficient to invest resources into development without first simulating the design to test specifications for various outcomes. This is what every DeFi project in the crypto space is not doing. This is why we are working on an open source python package to simulate various sandboxed DeFi components of DAOSYS so that project engineers, managers and designers can pre-plan outcomes prior to investing valuable resources into development.

With this tool, DAOSYS designers can utilize the plug and play components of our simulator to build tokenomics mockups for business planning purposes so that teams can come together and get collective consensus alongside potential users and investors. Not only is this tool applicable to DAOSYS, it can be used as a general purpose tool to simulate DEX activity for anyone wishing to setup their own LP to stress test various ideas prior to development. This can be used as a powerful design tool to explore the limitations of a DeFi project idea prior to committing valuable resources on development costs (i.e., devs and project managers). The following list highlights the key components of the UniswapPy python package used to address this problem:

  • BrownianModel: Generate Geometric Brownian motion (GBM) price simulation for a given μ, σ, t, and # of steps
  • SolveDeltas: Solve swap values Δxₖ and Δyₖ for a given price change Δpₖ
  • Factory : Create liquidity pools for given token pairs
  • Exchange: Refactor of the Uniswap V2 pairing code. Governs how Uniswap calls the liquidity pools; each exchange is associated with a single ERC20 token pairing. Maintains reserve asset holdings (ie, xₖ, yₖ), total liquidity pool token supply, and collected fees
  • SwapDeposit: Process to swap approx. half of single token X for token Y (and vice verse) and deposit proceeds plus remaining other approximated half (exact proportion is mathematically calculated)
  • WithdrawSwap: Process to withdraw liquidity from LP and swap opposing token which is added to specifed token to receive a single amount of specified token
  • TokenDeltaModel: Generates deposit and withdrawals deltas Δxₖ and Δyₖ randomly sampled from a gamma distribution
  • SimpleLPSimulation: Simulates LP activity of swaps, deposits and withdrawals given TokenDeltaModel, Exchange objects and pre-generated GBM simulation

The LP simulator is one working component of the overall system that we are working to build. At the moment, we have a working beta version of the simulator which is available through DeFiPy’s Github repository which is being built alongside DAOSYS. We are using this to understand the ROI and design considerations for DAOSYS’s first usecase (i.e., Masternode Yield Farming) [5]. Since the simulator is still in the beta stage, the setup is currently not realized to its full intention. However, a usable demo of this tool is available from DeFiPy’s Github repository for the community to begin using. For a mini python tutorial on how to use this tool, please refer to [5, 6] for a series of example Jupyter notebooks.

The purpose of this tool is primarily for the design aspect of DAOSYS, and is still in its early stages of development. The next stages involve feeding the output of various mathematical models into the simulator framework and to use this tool to simulate other DeFi usecases. This allows us to test a roster of edge cases for building more robust systems. The final goal is to bring this system to a level of maturity so that it can be utilized in parallel with the contracts in real time. Hence, exposing DeFi to a scientific way of design, testing, and implementation.

4. Numerical LP Simulations

In this section, we provide numerical outcomes using our LP simulator covered in the last section. To simulate LP Activity using GBM price simulations, we implemented the following steps using the components described above:

  • Generate GBM price sequence simulation {pₖ} using BrownianModel
  • Create Exchange object to maintain LP state
  • Instantiate SimpleLPSimulation object to govern LP simulation events
  • Using SimpleLPSimulation object, run LP simulation, for every time sample, k, do:
    - Solve swap deltas Δxₖ and Δyₖ using SolveDeltas given pₖ
    - Perform WithdrawSwap or SwapDeposit depending on the direction of the swap deltas from previous step
    - Data capture price and reserve amounts
  • Repeat above steps n_path times

Solve LP Swap Deltas

Here we address the problem of updating asset balances (i.e., Δxₖ, Δyₖ) upon each price change Δpₖ, where {pₖ} is a simulated GBM process representing the prices of our asset (valued in USD) over time sample k. Price change, Δpₖ, in a liquidity pool are determined as:

and asset trade price is determined as:

Thus, given the above equations, we derive the following system of non-linear equations:

Since we have the previous balances yₖ₋₁, xₖ₋₁, price change Δpₖ, and the current price, pₖ, from our simulated GBM, we can solve for the swap balances Δxₖ and Δyₖ under the constraints Δyₖ> 0 and Δxₖ> 0 for every k. To achieve this, we used the optimize.fsolve function from the scipy package in python, which can be found in the SolveDeltas class.

The python code for the above procedure is openly available through DeFiPy’s Github repository [6]. Using this stepwise process, we generate the simulations. See the following code block for the implementation:

# ---------------------------------#
# BLOCK 2: Generate LP Simulations
# ---------------------------------#

from uniswappy.simulate import SimpleLPSimulation
from uniswappy.erc import ERC20

# Generate simulations
print(f'Trial run {k}')
p_trial_arr = p_arr[:,k]

tkn = ERC20('TKN', "0x09")
dai = ERC20('DAI', "0x111")

lp_sim = SimpleLPSimulation()
lp_sim.init_amts(10000, p_trial_arr[0])
lp_sim.create_lp(tkn, dai)
lp_sim.run(p_trial_arr)

5. Access LP Simulations

Here, we present simulated temporal LP outcomes from our DeFi simulator as shown in Figs. 2 and 3. Each temporal sample represents the aggregate activity of one time interval which account for typical LP actions such as swaps, deposits and withdraws. It is well-studied that GBM processes are an effective tool to model asset price behavior. Thus, activity due to swaps are driven by a set of GBM price sequence paths presented in Fig. 2, and swap deltas Δxₖ, Δyₖ are calculated using the non-linear set of equations presented in the last section. Using these solved deltas, we can systemically calculate the x and y holdings of SYS and DAI over time which are managed by a series of SimulateLiquidity objects held by the simLiq python dictionary. To access the simulations to each of the GMB paths, we walk through the dictionary keys to access each LP simulation, as shown below:

# ---------------------------------#
# BLOCK 3: Access LP simulations
# ---------------------------------#

sys_arr = np.zeros((n_steps, n_paths), np.float64)
x_amt_arr = np.zeros((n_steps, n_paths), np.float64)
y_amt_arr = np.zeros((n_steps, n_paths), np.float64)

for k in range(n_paths):

# ---------------------------------#
# Block 2 goes here
# ---------------------------------#

sys_arr[:,k] = lp_sim.get_tkn_price_sim()
x_amt_arr[:,k] = lp_sim.get_x_amt_sim()
y_amt_arr[:,k] = lp_sim.get_y_amt_sim()

The performance of these LPs can be now analyzed probabilistically across each time sample k; see Fig. 2 for the plots of the temporal simulations.

Fig. 2 Simulation USD values of a LP position with an original value of $2,000 USD (10,000 SYS and $1,000 DIA); (TOP) LP USD value of position holdings, where the horizontal line represents initial investment, and dotted line represents the expectation; (MIDDLE) SYS reserve amounts; and (BOTTOM) DAI reserve amounts

Now that we have these LP simulations, we can start to do interesting things, like track the performance of a position or start experimenting with more advanced DeFi protocol designs.

6. Summary

The work presented in this article is a larger body of work for doing things like: (a) simulate the behaviour of a simple liquidity pool [1]; (b) studying the effects of Impermanent Loss in an LP [2]; and (c) analyzing the risk profile and profitability in more advanced DeFi systems. Here, we provide the basic setup for those who are interested in getting into researching LPs. Please be sure to look out for future medium posts on this!

See GH repos for Jupyter notebook of behind this presentation

7. References

[1] C. Doge, I.C. Moore, R. Arbour, and J. Sidhu, DAOSYS, Smart DAO Protocol for Decentralized Finance, Syscoin Github repos, Oct. 2022, Accessed on: Mar 2023. [Online]. Available: https://github.com/syscoin/latex_docs/blob/main/daosys/article.pdf

[2] L. Bachelier, Therorie de la speculation, Annales scientifiques de l’Ecole Normale Superieure, Serie 3, Tome 17 (1900), pp. 21–86.

[3] P. Samuelson, Rational Theory of Warrant Pricing, Industrial Management Review (pre-1986), Cambridge Vol. 6, Iss. 2, (Spring 1965): 13.

[4] N. Privault, Notes on Financial Risk & Analytics, Jan 2023, Accessed on: Feb 2023. [Online]. Available: https://personal.ntu.edu.sg/nprivault/MH8331/financial_risk_analytics.pdf

[5] I.C. Moore, Masternode Yield Farming as a DAOSYS Usecase: Part 2, Medium Article, Aug. 2022. Accessed on: Sept 2022. [Online]. https://icmoore.medium.com/masternode-yield-farming-as-a-daosys-usecase-part-2-8906d0a11c27

[6] I.C. Moore, Simulating a Liquidity Pool for Decentralized Finance, Syscoin Github repos, Accessed on: Mar 2023. [Online]. Available: https://github.com/icmoore/uniswappy/blob/main/notebooks/medium_articles/simple_simulation.ipynb

[7] I.C. Moore and J. Sidhu, An Analytical and Empirical Survey of Impermanent Loss, Syscoin Github repos, Accessed on: Mar 2023. [Online]. Available: https://github.com/syscoin/latex_docs/blob/main/impermanent_loss/article.pdf

--

--