### Install UniswapPy Package Source: https://github.com/defipy-devs/uniswappy/blob/main/README.md Clone the repository and install locally or install directly from PyPI. ```bash > git clone https://github.com/defipy-devs/uniswappy > pip install . ``` ```bash > pip install UniswapPy ``` -------------------------------- ### Install Project Requirements Source: https://github.com/defipy-devs/uniswappy/blob/main/python/application/quant_terminal/README.md Clone the repository and install project dependencies using pip. ```bash > git clone https://github.com/defipy-devs/uniswappy > pip install -r requirements.txt ``` -------------------------------- ### Install Pytest Source: https://github.com/defipy-devs/uniswappy/blob/main/README.md Install the pytest framework, which is required for running the test suite. ```bash > pip install pytest ``` -------------------------------- ### Exchange and Liquidity Pool Setup Source: https://github.com/defipy-devs/uniswappy/blob/main/notebooks/tutorials/tree_quotes.ipynb Initializes various ERC20 tokens, IndexVaults, Uniswap factories, and liquidity pools. It then adds initial liquidity to these pools and prints their summaries. ```python dai1 = ERC20("DAI", "0x111") sys1 = ERC20("SYS", "0x09") exchg_data = UniswapExchangeData(tkn0 = sys1, tkn1 = dai1, symbol="LP", address="0x011", version = 'V2') iVault1 = IndexVault('iVault1', "0x7") iVault2 = IndexVault('iVault2', "0x7") factory = UniswapFactory("SYS pool factory", "0x2") lp = factory.deploy(exchg_data) Join().apply(lp, user_nm, sys_amount, dai_amount) lp.summary() sys2 = ERC20("SYS", "0x09") isys1 = IndexERC20("iSYS", "0x09", sys1, lp) exchg_data1 = UniswapExchangeData(tkn0 = sys2, tkn1 = isys1, symbol="LP1", address="0x012", version = 'V2') lp1 = factory.deploy(exchg_data1) lp1.summary() dai2 = ERC20("DAI", "0x09") isys2 = IndexERC20("iSYS", "0x09", sys1, lp) exchg_data2 = UniswapExchangeData(tkn0 = dai2, tkn1 = isys2, symbol="LP2", address="0x012", version = 'V2') lp2 = factory.deploy(exchg_data2) lp2.summary() dai3 = ERC20("DAI", "0x09") idai1 = IndexERC20("iDAI", "0x09", dai1, lp) exchg_data3 = UniswapExchangeData(tkn0 = dai3, tkn1 = idai1, symbol="LP3", address="0x012", version = 'V2') lp3 = factory.deploy(exchg_data3) lp3.summary() sys3 = ERC20("SYS", "0x09") idai2 = IndexERC20("iDAI", "0x09", dai1, lp) exchg_data4 = UniswapExchangeData(tkn0 = sys3, tkn1 = idai2, symbol="LP4", address="0x012", version = 'V2') lp4 = factory.deploy(exchg_data4) lp4.summary() isys3 = IndexERC20("iSYS", "0x09", sys1, lp) idai3 = IndexERC20("iDAI", "0x09", dai1, lp) exchg_data5 = UniswapExchangeData(tkn0 = isys3, tkn1 = idai3, symbol="LP5", address="0x012", version = 'V2') lp5 = factory.deploy(exchg_data5) lp5.summary() ``` -------------------------------- ### Setup and Simulation of Liquidity Pool Source: https://github.com/defipy-devs/uniswappy/blob/main/notebooks/issues/zero_liquidity_bug.ipynb Sets up a liquidity pool with initial reserves and then runs a simulation. This is used to test scenarios that might lead to zero liquidity issues. ```python lp, tkn0, tkn1 = setup_lp( tenv, [ [tenv.reserve0, tenv.reserve1, 0.9, 1.0] ] ) do_sim(tenv, lp, tkn0, tkn1) ``` -------------------------------- ### Initialize Uniswap Environment Source: https://github.com/defipy-devs/uniswappy/blob/main/notebooks/tutorials/revenue_univ2.ipynb Sets up the user and initial token amounts for simulating Uniswap operations. These variables define the starting state for liquidity and swaps. ```python from uniswappy import * user_nm = 'user0' dai_amount = 10000 sys_amount = 10000 ``` -------------------------------- ### Setup and Deploy a Liquidity Pool Source: https://github.com/defipy-devs/uniswappy/blob/main/notebooks/medium_articles/basic_intro.ipynb Initializes ERC20 tokens, a Uniswap factory, deploys a liquidity pool, and adds initial liquidity. Use this to set up a new trading pair. ```python from uniswappy.erc import ERC20 from uniswappy.cpt.factory import UniswapFactory from uniswappy.utils.data import UniswapExchangeData dai = ERC20("DAI", "0x111") eth = ERC20("ETH", "0x09") exchg_data = UniswapExchangeData(tkn0 = eth, tkn1 = dai, symbol="LP", address="0x011") factory = UniswapFactory("ETH pool factory", "0x2") lp = factory.deploy(exchg_data) lp.add_liquidity(user_nm, eth_amount, dai_amount, eth_amount, dai_amount) lp.summary() ``` -------------------------------- ### SwapDeposit() Example: Deposit LP with ETH Source: https://github.com/defipy-devs/uniswappy/blob/main/notebooks/tutorials/uniswap_v2.ipynb Demonstrates depositing LP tokens by performing a 50% swap and then a 50/50 deposit. Use when depositing with only ETH. ```python tkn = ERC20("TKN", "0x111") eth = ERC20("ETH", "0x09") exchg_data = UniswapExchangeData(tkn0 = eth, tkn1 = tkn, symbol="LP", address="0x011") factory = UniswapFactory("ETH pool factory", "0x2") lp = factory.deploy(exchg_data) Join().apply(lp, user_nm, eth_amount, tkn_amount) lp.summary() amount_out = SwapDeposit().apply(lp, eth, user_nm, 1) lp.summary() ``` -------------------------------- ### Initial Exchange Summaries Source: https://github.com/defipy-devs/uniswappy/blob/main/notebooks/tutorials/tree_quotes.ipynb Displays the initial state of the liquidity pools after setup and initial liquidity provision. ```text Exchange SYS-DAI (LP) Reserves: SYS = 100000.0, DAI = 10000.0 Liquidity: 31622.776601683792 Exchange SYS-iSYS (LP1) Reserves: SYS = 0.0, iSYS = 0.0 Liquidity: 0.0 Exchange DAI-iSYS (LP2) Reserves: DAI = 0.0, iSYS = 0.0 Liquidity: 0.0 Exchange DAI-iDAI (LP3) Reserves: DAI = 0.0, iDAI = 0.0 Liquidity: 0.0 Exchange SYS-iDAI (LP4) Reserves: SYS = 0.0, iDAI = 0.0 Liquidity: 0.0 Exchange iSYS-iDAI (LP5) Reserves: iSYS = 0.0, iDAI = 0.0 Liquidity: 0.0 ``` -------------------------------- ### Install Uniswappy Python Package Source: https://github.com/defipy-devs/uniswappy/blob/main/python/application/quant_terminal/README.md Install the Uniswappy Python package locally. ```bash > pip install . ``` ```bash > pip install uniswappy ``` -------------------------------- ### Setup Uniswap V3 Exchange and Initial Liquidity Source: https://github.com/defipy-devs/uniswappy/blob/main/notebooks/medium_articles/order_book.ipynb Initializes a Uniswap V3 exchange with specified tokens, fee, and tick spacing. It then deploys the exchange and adds initial liquidity within a defined tick range. ```python eth = ERC20("ETH", "0x09") tkn = ERC20("TKN", "0x111") exchg_data = UniswapExchangeData(tkn0 = eth, tkn1 = tkn, symbol="LP", address="0x011", version = 'V3', tick_spacing = tick_spacing, fee = fee) factory = UniswapFactory("ETH pool factory", "0x2") lp = factory.deploy(exchg_data) lwr_tick = UniV3Helper().get_price_tick(lp, -1, 10, 1000) upr_tick = UniV3Helper().get_price_tick(lp, 1, 10, 1000) Join().apply(lp, user_nm, eth_amount, tkn_amount, lwr_tick, upr_tick) lp.summary() ``` -------------------------------- ### Install pytest Source: https://github.com/defipy-devs/uniswappy/blob/main/notebooks/tutorials/machine_precision_univ3.ipynb Installs the pytest library, which is commonly used for writing and running tests in Python. ```python #!pip install pytest ``` -------------------------------- ### Setup and Liquidity Addition for Uniswap Exchange Source: https://github.com/defipy-devs/uniswappy/blob/main/notebooks/medium_articles/indexing_problem.ipynb Initializes ERC20 tokens, defines exchange data, deploys a Uniswap factory, creates an LP, and adds initial liquidity. This sets up the environment for subsequent valuation comparisons. ```python dai = ERC20("DAI", "0x111") eth = ERC20("ETH", "0x09") exchg_data = UniswapExchangeData(tkn0 = eth, tkn1 = dai, symbol="LP", address="0x011") factory = UniswapFactory("ETH pool factory", "0x2") lp = factory.deploy(exchg_data) lp.add_liquidity(user_nm, eth_amount, dai_amount, eth_amount, dai_amount) lp.summary() ``` -------------------------------- ### Swap() Example: Swap ETH for LP tokens Source: https://github.com/defipy-devs/uniswappy/blob/main/notebooks/tutorials/uniswap_v2.ipynb Swaps ETH for LP tokens. This involves creating two liquidity pools and then performing the swap operation on the second pool. ```python tkn = ERC20("TKN", "0x111") eth = ERC20("ETH", "0x09") exchg_data = UniswapExchangeData(tkn0 = eth, tkn1 = tkn, symbol="LP", address="0x011") factory = UniswapFactory("ETH pool factory", "0x2") lp_tkn = factory.deploy(exchg_data) Join().apply(lp_tkn, user_nm, eth_amount, tkn_amount) lp_tkn.summary() tkn2 = ERC20("TKN", "0x112") lp_tkn_amount = lp_tkn.get_liquidity() exchg_data = UniswapExchangeData(tkn0 = lp_tkn, tkn1 = tkn2, symbol="LP2", address="0x012") lp2 = factory.deploy(exchg_data) Join().apply(lp2, user_nm, lp_tkn_amount, tkn_amount) lp2.summary() out = Swap().apply(lp2, tkn2, user_nm, 100) lp2.summary() ``` -------------------------------- ### Setup Uniswap V3 Pool for ETH-TKN Swap Source: https://github.com/defipy-devs/uniswappy/blob/main/notebooks/medium_articles/univ3_math.ipynb Deploys a Uniswap V3 exchange contract for ETH-TKN pair and initializes liquidity. ```python eth = ERC20("ETH", "0x09") dai = ERC20("TKN", "0x111") exchanges_data = UniswapExchangeData(tkn0 = eth, tkn1 = dai, symbol="LP", address="0x011", version = 'V3', tick_spacing = tick_spacing, fee = fee) factory = UniswapFactory("ETH pool factory", "0x2") lp = factory.deploy(exchg_data) Join().apply(lp, user_nm, eth_amount, dai_amount, lwr_tick, upr_tick) lp.summary() ``` -------------------------------- ### Run Full Test Suite Source: https://github.com/defipy-devs/uniswappy/blob/main/README.md Execute the complete test suite for Uniswappy from the repository root. Ensure pytest is installed. ```bash > python -m pytest python/test/ -v ``` -------------------------------- ### Swap() Example: Swap LP tokens for ETH Source: https://github.com/defipy-devs/uniswappy/blob/main/notebooks/tutorials/uniswap_v2.ipynb Swaps LP tokens for ETH. This involves creating two liquidity pools and then performing the swap operation on the second pool. ```python tkn = ERC20("TKN", "0x111") eth = ERC20("ETH", "0x09") exchg_data = UniswapExchangeData(tkn0 = eth, tkn1 = tkn, symbol="LP", address="0x011") factory = UniswapFactory("ETH pool factory", "0x2") lp_tkn = factory.deploy(exchg_data) Join().apply(lp_tkn, user_nm, eth_amount, tkn_amount) lp_tkn.summary() tkn2 = ERC20("TKN", "0x112") lp_tkn_amount = lp_tkn.get_liquidity() exchg_data = UniswapExchangeData(tkn0 = lp_tkn, tkn1 = tkn2, symbol="LP2", address="0x012") lp2 = factory.deploy(exchg_data) Join().apply(lp2, user_nm, lp_tkn_amount, tkn_amount) lp2.summary() out = Swap().apply(lp2, lp_tkn, user_nm, 100) lp2.summary() ``` -------------------------------- ### Run 0x Quant Terminal Locally Source: https://github.com/defipy-devs/uniswappy/blob/main/README.md Command to start the 0x Quant Terminal application locally using Bokeh server. ```bash > bokeh serve --show python/application/quant_terminal/bokeh_server.py ``` -------------------------------- ### Initialize QuantTerminal Simulator Source: https://github.com/defipy-devs/uniswappy/blob/main/notebooks/tutorials/quant_terminal.ipynb Initializes the QuantTerminal simulator with specified tokens, time window, trade bias, and API. It also initializes the liquidity pool with a starting amount and investment. ```python # ------------------- # QuantTerminal # ------------------- sim = QuantTerminal(buy_token = chain.get_buy_token(), sell_token = chain.get_sell_token(), time_window = chain.time_window, trade_bias = chain.trade_bias, td_model = chain.get_td_model(), api = api) sim.init_lp(init_x_tkn = chain.get_buy_init_amt(), x_tkn_nm = chain.buy_tkn_nm, init_x_invest = chain.init_investment) ``` -------------------------------- ### Full SwapDeposit Simulation (ETH Input) Source: https://github.com/defipy-devs/uniswappy/blob/main/notebooks/tutorials/deposit.ipynb Simulates a complete SwapDeposit process starting with ETH. It initializes an LP, performs a swap, adds liquidity, and prints a summary of the deposited amounts. ```python tkn = ERC20("TKN", "0x111") eth = ERC20("ETH", "0x09") exchg_data = UniswapExchangeData(tkn0 = eth, tkn1 = tkn, symbol="LP", address="0x011") factory = UniswapFactory("ETH pool factory", "0x2") lp = factory.deploy(exchg_data) lp.add_liquidity(user_nm, eth_amount, tkn_amount, eth_amount, tkn_amount) print('***\nInitial LP\n***') lp.summary() s_in = 100 alpha = calc_deposit_portion(lp, eth, s_in) s_out = Swap().apply(lp, eth, user_nm, alpha*s_in) print('***\nLP post step 1\n***') lp.summary() balance1 = s_out balance0 = lp.quote(s_out, lp.reserve1, lp.reserve0) lp.add_liquidity(user_nm, balance0, balance1, balance0, balance1) print('***\nLP post step 2\n***') lp.summary() print('Given {} initial ETH:'.format(s_in)) print(' (step 1) {} ETH must first get swapped for {} TKN'.format(alpha*s_in, s_out)) print(' (step 2) The received TKN gets deposited along with the remaining {} ETH'.format(balance0)) print('\nTotal deposited is {:.6f} + {:.6f} = {:.6f} ETH:'.format(alpha*s_in, balance0, alpha*s_in + balance0)) ``` -------------------------------- ### Uniswap V2 Add Liquidity Example Source: https://github.com/defipy-devs/uniswappy/blob/main/notebooks/tutorials/compare_v2_v3.ipynb Demonstrates adding liquidity to a Uniswap V2 exchange. Requires pre-defined ERC20 tokens and exchange data. ```python user_nm = 'user_intro' eth_amount = 3162.277660168379 dai_amount = 316227.7660168379 dai = ERC20("DAI", "0x111") eth = ERC20("ETH", "0x09") exchg_data = UniswapExchangeData(tkn0 = eth, tkn1 = dai, symbol="LP", address="0x011") factory = UniswapFactory("ETH pool factory", "0x2") lp = factory.deploy(exchg_data) lp.add_liquidity("user0", eth_amount, dai_amount, eth_amount, dai_amount) lp.summary() ``` -------------------------------- ### Full SwapDeposit Simulation (TKN Input) Source: https://github.com/defipy-devs/uniswappy/blob/main/notebooks/tutorials/deposit.ipynb Simulates a SwapDeposit process starting with TKN. It initializes an LP, performs a swap, adds liquidity, and prints a summary of the deposited amounts, verifying the process for the opposing token. ```python tkn = ERC20("TKN", "0x111") eth = ERC20("ETH", "0x09") exchg_data = UniswapExchangeData(tkn0 = eth, tkn1 = tkn, symbol="LP", address="0x011") factory = UniswapFactory("ETH pool factory", "0x2") lp = factory.deploy(exchg_data) lp.add_liquidity(user_nm, eth_amount, tkn_amount, eth_amount, tkn_amount) print('***\nInitial LP\n***') lp.summary() s_in = 1000 alpha = calc_deposit_portion(lp, tkn, s_in) s_out = Swap().apply(lp, tkn, user_nm, alpha*s_in) print('***\nLP post step 1\n***') lp.summary() balance1 = lp.quote(s_out, lp.reserve0, lp.reserve1) balance0 = s_out lp.add_liquidity(user_nm, balance0, balance1, balance0, balance1) print('***\nLP post step 2\n***') lp.summary() print('Given {} initial ETH:'.format(s_in)) print(' (step 1) {} ETH must first get swapped for {} TKN'.format(alpha*s_in, s_out)) print(' (step 2) The received TKN gets deposited along with the remaining {} ETH'.format(balance0)) print('\nTotal deposited is {:.6f} + {:.6f} = {:.6f} TKN:'.format(alpha*s_in, balance1, alpha*s_in + balance1)) ``` -------------------------------- ### Uniswap V3 Add Liquidity Example Source: https://github.com/defipy-devs/uniswappy/blob/main/notebooks/tutorials/compare_v2_v3.ipynb Shows how to add liquidity to a Uniswap V3 exchange, mimicking V2 behavior by using extreme tick values. Initializes the pool with a specific price. ```python user = 'user_intro' fee = UniV3Utils.FeeAmount.MEDIUM tick_spacing = UniV3Utils.TICK_SPACINGS[fee] lwr_tick = UniV3Utils.getMinTick(tick_spacing) upr_tick = UniV3Utils.getMaxTick(tick_spacing) init_price = UniV3Utils.encodePriceSqrt(100, 1) dai = ERC20("DAI", "0x09") eth = ERC20("ETH", "0x111") exchg_data = UniswapExchangeData(tkn0 = eth, tkn1 = dai, symbol="LP", address="0x011", version = 'V3', tick_spacing = tick_spacing, fee = fee) factory = UniswapFactory("ETH pool factory", "0x2") lp = factory.deploy(exchg_data) lp.initialize(init_price) lp.mint(user, lwr_tick, upr_tick, 31622.776601683792) lp.summary() ``` -------------------------------- ### Set up simulation environment and parameters Source: https://github.com/defipy-devs/uniswappy/blob/main/notebooks/issues/zero_liquidity_bug.ipynb Initializes simulation parameters including fee, tick spacing, initial price, and token scenario details. ```python fee = UniV3Utils.FeeAmount.MEDIUM tick_spacing = UniV3Utils.TICK_SPACINGS[fee] init_price = UniV3Utils.encodePriceSqrt(1000,1000) usdt_in = 10**6 tenv = TokenScenario( user = 'user', reserve0 = usdt_in * 0.2, reserve1 = usdt_in * 0.2, name0 = "TKN", name1 = "USDT", address0 = "0x111", address1 = "0x09", usdt_in = usdt_in, tick_spacing = tick_spacing, fee = fee, init_price = init_price ) nsteps = 50 lp_prices = [] lp_liquidity = [] lp_swap = [] ``` -------------------------------- ### Initialize user and token amounts Source: https://github.com/defipy-devs/uniswappy/blob/main/notebooks/medium_articles/withdraw_like_an_og.ipynb Sets up initial amounts for a user and tokens involved in liquidity provision. ```python user_nm = 'user0' eth_amount = 1000 tkn_amount = 100000 ``` -------------------------------- ### Initialize Simple DEX Tree and Liquidity Pools Source: https://github.com/defipy-devs/uniswappy/blob/main/notebooks/medium_articles/simple_tree_pt1.ipynb Sets up the Uniswap V2 factory, deploys initial liquidity pools (USDC-USDT and USDC-iUSDC), and adds initial liquidity. It also re-balances the LP price after initial joins. ```python usdt1 = ERC20(usdt_nm, "0x111") tkn1 = ERC20(tkn_nm, "0x09") exchg_data = UniswapExchangeData(tkn0 = tkn1, tkn1 = usdt1, symbol="LP", address="0x011") TKN_amt = TokenDeltaModel(tkn_delta_param) iVault1 = IndexVault('iVault1', "0x7") factory = UniswapFactory(f"{tkn_nm} pool factory", "0x2") lp = factory.deploy(exchg_data) Join().apply(lp, user_nm, tkn_amount, usdt_amount) tkn2 = ERC20(tkn_nm, "0x09") itkn1 = IndexERC20(itkn_nm, "0x09", tkn1, lp) exchg_data1 = UniswapExchangeData(tkn0 = tkn2, tkn1 = itkn1, symbol="LP1", address="0x012") lp1 = factory.deploy(exchg_data1) JoinTree().apply(lp1, user_nm, iVault1, 10000) # Re-balance LP price after JoinTree SwapDeposit().apply(lp, usdt1, user_nm, lp.get_reserve(tkn1) - lp.get_reserve(usdt1)) lp.summary() lp1.summary() ``` -------------------------------- ### Install UniswapPy Source: https://context7.com/defipy-devs/uniswappy/llms.txt Install the UniswapPy package using pip. This command makes the library available for use in your Python projects. ```bash pip install UniswapPy ``` -------------------------------- ### Initialize User and Token Amounts Source: https://github.com/defipy-devs/uniswappy/blob/main/notebooks/medium_articles/simple_tree_pt1.ipynb Sets up the initial amounts for a user's tokens, linking them to the simulated price data. ```python user_nm = 'user0' tkn_amount = init_tkn_lp usdt_amount = p_arr[0]*tkn_amount ``` -------------------------------- ### Install Dependencies and Run Pytest Source: https://context7.com/defipy-devs/uniswappy/llms.txt Provides commands to install necessary Python packages for testing and execute the test suite using pytest. ```bash # Install dependencies pip install pytest scipy numpy pandas # Run all tests from the repo root python -m pytest python/test/ -v # Run only V2 tests python -m pytest python/test/v2/ -v ``` -------------------------------- ### Initialize user and token amounts Source: https://github.com/defipy-devs/uniswappy/blob/main/notebooks/medium_articles/univ2_math.ipynb Sets up initial values for user names and token amounts for simulation. ```python user_nm = 'user_intro' eth_amount = 1000 dai_amount = 1000000 ``` -------------------------------- ### Set up test LP using UniswapPy Source: https://github.com/defipy-devs/uniswappy/blob/main/notebooks/medium_articles/indexing_problem.ipynb Initializes ERC20 tokens, a Uniswap exchange data object, a factory, deploys an LP, and adds liquidity. Requires `uniswappy` library. ```python from uniswappy.cpt.quote import LPQuote from uniswappy.cpt.factory import UniswapFactory from uniswappy.erc import ERC20 from uniswappy.utils.data import UniswapExchangeData user_nm = 'user_test' eth_amount = 1000 dai_amount = 1000000 dai = ERC20("DAI", "0x111") eth = ERC20("ETH", "0x09") exchg_data = UniswapExchangeData(tkn0 = eth, tkn1 = dai, symbol="LP", address="0x011") factory = UniswapFactory("ETH pool factory", "0x2") lp = factory.deploy(exchg_data) lp.add_liquidity(user_nm, eth_amount, dai_amount, eth_amount, dai_amount) lp.summary() ``` -------------------------------- ### Get Liquidity Pool Information Source: https://github.com/defipy-devs/uniswappy/blob/main/notebooks/tutorials/quant_terminal.ipynb Retrieves and displays summary information for a liquidity pool, including reserves and liquidity. ```python lp = sim.get_lp() lp.summary() ``` -------------------------------- ### Initialize user and token amounts Source: https://github.com/defipy-devs/uniswappy/blob/main/notebooks/medium_articles/deposit_like_a_baller.ipynb Sets up initial amounts for user accounts and tokens to be used in liquidity operations. ```python user_nm = 'user0' eth_amount = 1000 usdc_amount = 1000000 ``` -------------------------------- ### Get Index Token Quote Source: https://github.com/defipy-devs/uniswappy/blob/main/notebooks/tutorials/quant_terminal.ipynb Calculates the index token quote based on the LP and initial LP token quote. ```python IndexTokenQuote().get_x(lp, init_lp) ``` -------------------------------- ### Get Total LP Tokens from iVault Source: https://github.com/defipy-devs/uniswappy/blob/main/notebooks/tutorials/liqleak2.ipynb Retrieves the total LP tokens held by an iVault. Requires the iVault and its index tokens to be initialized. ```python iVault1.index_tokens['iSYS']['total_lp'] ``` -------------------------------- ### Get Amount After Swap Fees on Uniswap V2 Source: https://github.com/defipy-devs/uniswappy/blob/main/notebooks/tutorials/machine_precision_univ2.ipynb Calculates the amount of a token received after accounting for swap fees. Use `include_fee=True` to factor in fees. ```python amt_eth = LPQuote(include_fee = True).get_amount(lp, eth, UniV3Helper().dec2gwei(1)) amt_dai = LPQuote(include_fee = True).get_amount(lp, dai, UniV3Helper().dec2gwei(1)) print(f'{UniV3Helper().dec2gwei(1)} {eth.token_name} token is worth {amt_dai} {dai.token_name} after swap fees') print(f'{UniV3Helper().dec2gwei(1)} {dai.token_name} token is worth {amt_eth} {eth.token_name} after swap fees') ``` -------------------------------- ### Define TokenScenario dataclass and utility functions Source: https://github.com/defipy-devs/uniswappy/blob/main/notebooks/issues/zero_liquidity_bug.ipynb Defines a dataclass for token scenarios and utility functions for plotting, getting ticks, and setting up liquidity pools. ```python @dataclass class TokenScenario: user: str usdt_in: int reserve0: int reserve1: int name0: str name1: str address0: str address1: str tick_spacing: any fee: any init_price: any def plotme(df, title, annotation): plt.figure(figsize=(10,6)) for key, grp in df.groupby('lower'): plt.plot(grp['swap'], grp['price'], label=key) plt.text(25000, 0.6, annotation ) plt.legend(title=title) plt.xlabel('Tokens sold (TKN)') plt.ylabel('Swap price (USDT/TKN)') plt.show() def get_tick(lp, x): if x == "min_tick": return UniV3Utils.getMinTick(lp.tickSpacing) elif x == "max_tick": return UniV3Utils.getMaxTick(lp.tickSpacing) return UniV3Helper().get_price_tick(lp, 0, x) def setup_lp(tenv, pool_params): factory = UniswapFactory("ETH pool factory", "0x%d" ) tkn0 = ERC20(tenv.name0, tenv.address0) tkn1 = ERC20(tenv.name1, tenv.address1) exchg_data = UniswapExchangeData( tkn0 = tkn0, tkn1 = tkn1, symbol="LP", address="0x011", version="V3", tick_spacing = tenv.tick_spacing, fee=tenv.fee ) lp = factory.deploy(exchg_data) #lp.initialize(tenv.init_price) for pool_param in pool_params: # AddLiquidity().apply( # lp, tkn1, tenv.user, pool_param[0], # get_tick(lp, pool_param[1]), # get_tick(lp, pool_param[2]) # ) # lp.summary() init_p = tenv.reserve1/tenv.reserve0 lwr_tick = UniV3Helper().get_price_tick(lp, -1, init_p, 1000) upr_tick = UniV3Helper().get_price_tick(lp, 1, init_p, 1000) Join().apply( lp, tenv.user, tenv.reserve0, tenv.reserve1, lwr_tick, upr_tick) return (lp, tkn0, tkn1) def do_calc(tenv): results = [] for lower in [0.95, 0.9, 0.8, 0.7, 0.5, 0.1, 0.000001]: for swap in np.geomspace(100, tenv.usdt_in, num=100): (lp, tkn0, tkn1) = setup_lp(tenv, [[ tenv.reserve, lower, 1.0 ]]) try: out = Swap().apply(lp, tkn0, tenv.user, swap) results.append({ "lower": lower, "swap": swap, "out": out, "price": float(out) / float(swap) }) except AssertionError: pass return pd.DataFrame(results) def do_calc1(tenv): results = [] insurance_lower = 0.95 insurance_upper = 0.98 for frac_reserve in np.geomspace(0.0001, 0.99, num=10): for swap in np.geomspace(100, tenv.usdt_in, num=100): (lp, tkn0, tkn1) = setup_lp( tenv, [ [tenv.reserve * (1.0 - frac_reserve), "min_tick", 1.0], [tenv.reserve * frac_reserve, insurance_lower, 1.0] ] ) try: out = Swap().apply(lp, tkn0, tenv.user, swap) results.append({ "lower": frac_reserve * 100, "swap": swap, "out": out, "price": float(out) / float(swap) }) except AssertionError: pass return pd.DataFrame(results) __all__ = ['plotme', 'do_calc', 'do_calc1', 'setup_lp', 'TokenScenario'] ``` -------------------------------- ### Initialize DEX Tree and Liquidity Pools Source: https://github.com/defipy-devs/uniswappy/blob/main/notebooks/medium_articles/simple_tree_pt2.ipynb Sets up the Uniswap V2 exchange data, deploys liquidity pools (LP and LP1), and joins liquidity. It also re-balances the LP price after the initial join. ```python dai1 = ERC20(usd_nm, "0x111") tkn1 = ERC20(tkn_nm, "0x09") exchg_data = UniswapExchangeData(tkn0 = tkn1, tkn1 = dai1, symbol="LP", address="0x011") TKN_amt = TokenDeltaModel(tkn_delta_param) TKN_amt_arb = TokenDeltaModel(100) lp1_state = MarkovState(stochastic = True) iVault1 = IndexVault('iVault1', "0x7") factory = UniswapFactory(f"{tkn_nm} pool factory", "0x2") lp = factory.deploy(exchg_data) Join().apply(lp, user_nm, tkn_amount, dai_amount) tkn2 = ERC20(tkn_nm, "0x09") itkn1 = IndexERC20(itkn_nm, "0x09", tkn1, lp) exchg_data1 = UniswapExchangeData(tkn0 = tkn2, tkn1 = itkn1, symbol="LP1", address="0x012") lp1 = factory.deploy(exchg_data1) JoinTree().apply(lp1, user_nm, iVault1, 10000) # Re-balance LP price after JoinTree SwapDeposit().apply(lp, dai1, user_nm, lp.get_reserve(tkn1) - lp.get_reserve(dai1)) lp.summary() lp1.summary() ``` -------------------------------- ### Initialize Simulation Parameters Source: https://github.com/defipy-devs/uniswappy/blob/main/notebooks/medium_articles/simple_tree_pt2.ipynb Sets up initial parameters for the simulation, including token amounts, deltas, and names for different stablecoins and their indexed versions. ```python init_tkn_lp = 100000 tkn_delta_param = 1000 tkn_invest_amt = 100 tkn_nm = 'USDC' itkn_nm = 'iUSDC' usd_nm = 'USDT' iusd_nm = 'iUSDT' ``` -------------------------------- ### Demonstrate SwapDeposit with ETH and USDC Source: https://github.com/defipy-devs/uniswappy/blob/main/notebooks/tutorials/deposit.ipynb Illustrates the SwapDeposit process by adding liquidity, performing a partial swap, and then adding the remaining liquidity. It highlights the initial state, state after the swap, and the final state after the deposit, along with a summary of deposited amounts and unaccounted tokens. ```python eth = ERC20("ETH", "0x09") usdc = ERC20("USDC", "0x111") exchg_data = UniswapExchangeData(tkn0 = eth, tkn1 = usdc, symbol="LP", address="0x011") factory = UniswapFactory("ETH pool factory", "0x2") lp = factory.deploy(exchg_data) lp.add_liquidity(user_nm, eth_amount, tkn_amount, eth_amount, tkn_amount) print('***\nInitial LP\n***') lp.summary() s_in = 100 alpha = 0.5 s_out = Swap().apply(lp, eth, user_nm, alpha*s_in) print('***\nLP post step 1\n***') lp.summary() balance0 = alpha*s_in balance1 = lp.quote(balance0, lp.reserve0, lp.reserve1) lp.add_liquidity(user_nm, balance0, balance1, balance0, balance1) print('***\nLP post step 2\n***') lp.summary() print('Given {} initial ETH:'.format(s_in)) print(' (step 1) {} ETH must first get swapped for {} '.format(alpha*s_in, s_out)) print(' (step 2) The received TKN gets deposited along with the remaining {} ETH'.format(balance0)) print('\nTotal deposited is {:.6f} + {:.6f} = {:.6f} ETH:'.format(alpha*s_in, balance0, alpha*s_in + balance0)) print('However, we have {} unaccounted USDC which need to be considered when using a 50/50 split'.format(colored(str(tkn_amount-lp.get_reserve(usdc)), 'red', attrs=['bold']))) ``` -------------------------------- ### Get Upper Tick for Uniswap V3 Source: https://github.com/defipy-devs/uniswappy/blob/main/notebooks/issues/Untitled.ipynb Calculates the upper tick for a Uniswap V3 liquidity pool. This is used to define the price range for liquidity provision. ```python upr_tick ``` -------------------------------- ### Get Lower Tick for Uniswap V3 Source: https://github.com/defipy-devs/uniswappy/blob/main/notebooks/issues/Untitled.ipynb Calculates the lower tick for a Uniswap V3 liquidity pool. This is used to define the price range for liquidity provision. ```python lwr_tick ``` -------------------------------- ### Initialize and Deploy Exchange Source: https://github.com/defipy-devs/uniswappy/blob/main/notebooks/tutorials/liqleak2.ipynb Sets up ERC20 tokens, Uniswap exchange data, and index vaults, then deploys a Uniswap V2 exchange and adds initial liquidity. ```python user_nm = 'user0' dai_amount = 10000 sys_amount = 100000 dai1 = ERC20("DAI", "0x111") sys1 = ERC20("SYS", "0x09") exchg_data = UniswapExchangeData(tkn0 = sys1, tkn1 = dai1, symbol="LP", address="0x011", version = 'V2') iVault1 = IndexVault('iVault1', "0x7") iVault2 = IndexVault('iVault2', "0x7") factory = UniswapFactory("SYS pool factory", "0x2") lp = factory.deploy(exchg_data) Join().apply(lp, user_nm, sys_amount, dai_amount) lp.summary() ``` -------------------------------- ### Calculate Rebased Index Token Amount Source: https://github.com/defipy-devs/uniswappy/blob/main/notebooks/tutorials/tree_quotes.ipynb Calculates the amount of a rebased index token in a liquidity pool. This example uses `RebaseIndexToken` to apply the rebase logic. ```python amt_x = lp1.reserve0 + RebaseIndexToken().apply(lp, sys1, lp1.reserve1) ``` -------------------------------- ### Uniswap V3: Deploy Exchange and Add Liquidity Source: https://github.com/defipy-devs/uniswappy/blob/main/README.md Shows how to deploy a Uniswap V3 exchange with specified tick spacing and fee, then add liquidity. ```python from uniswappy import * user_nm = 'user' eth_amount = 1000 tkn_amount = 100000 eth = ERC20("ETH", "0x09") tkn = ERC20("TKN", "0x111") exchg_data = UniswapExchangeData(tkn0 = eth, tkn1 = tkn, symbol="LP", address="0x011", version = 'V3', tick_spacing = tick_spacing, fee = fee) factory = UniswapFactory("ETH pool factory", "0x2") lp = factory.deploy(exchg_data) out_v3 = Join().apply(lp, user_nm, eth_amount, tkn_amount, lwr_tick, upr_tick) lp.summary() ``` -------------------------------- ### Deploy Exchange and Add Liquidity Source: https://github.com/defipy-devs/uniswappy/blob/main/notebooks/tutorials/uniswap_v2.ipynb Deploys an exchange with ETH and TKN, then adds liquidity. This is useful for setting up initial liquidity for a trading pair. ```python tkn = ERC20("TKN", "0x111") eth = ERC20("ETH", "0x09") exchg_data = UniswapExchangeData(tkn0 = eth, tkn1 = tkn, symbol="LP", address="0x011") factory = UniswapFactory("ETH pool factory", "0x2") lp_tkn = factory.deploy(exchg_data) Join().apply(lp_tkn, user_nm, eth_amount, tkn_amount) lp_tkn.summary() tkn2 = ERC20("TKN", "0x112") lp_tkn_amount = lp_tkn.get_liquidity() exchg_data = UniswapExchangeData(tkn0 = lp_tkn, tkn1 = tkn2, symbol="LP2", address="0x012") lp2 = factory.deploy(exchg_data) Join().apply(lp2, user_nm, lp_tkn_amount, tkn_amount) lp2.summary() AddLiquidity().apply(lp2, lp_tkn, user_nm, 10) lp2.summary() ``` -------------------------------- ### Deploy and Initialize Uniswap V3 Liquidity Pool Source: https://github.com/defipy-devs/uniswappy/blob/main/notebooks/issues/Untitled.ipynb This snippet demonstrates the full process of deploying a Uniswap V3 liquidity pool. It involves defining tokens, exchange data, calculating initial ticks, deploying the factory, and adding liquidity. Ensure all necessary imports and configurations are set up before execution. ```python from defipy import * user_nm = 'user0' eth_amount = 100.0 tkn_amount = 200000.0 fee = UniV3Utils.FeeAmount.MEDIUM tick_spacing = UniV3Utils.TICK_SPACINGS[fee] eth = ERC20("ETH", "0x09") tkn = ERC20("TKN", "0x111") exchg_data = UniswapExchangeData(tkn0 = eth, tkn1 = tkn, symbol="LP", address="0x011", version = 'V3', tick_spacing = tick_spacing, fee = fee) init_p = tkn_amount/eth_amount lwr_tick = UniV3Helper().get_price_tick(lp, -1, init_p, 10000) upr_tick = UniV3Helper().get_price_tick(lp, 1, init_p, 10000) factory = UniswapFactory("ETH pool factory", "0x2") lp = factory.deploy(exchg_data) Join().apply(lp, user_nm, eth_amount, tkn_amount, lwr_tick, upr_tick) lp.summary() ``` -------------------------------- ### Add Liquidity to Uniswap V3 Pool Source: https://github.com/defipy-devs/uniswappy/blob/main/notebooks/tutorials/machine_precision_univ3.ipynb Demonstrates adding liquidity to an existing Uniswap V3 pool after initial setup. Use this to increase the pool's depth. ```python dai = ERC20("DAI", "0x111") eth = ERC20("ETH", "0x09") exchg_data = UniswapExchangeData(tkn0 = eth, tkn1 = dai, symbol="LP", address="0x011", version = 'V3', tick_spacing = tick_spacing, precision = UniswapExchangeData.TYPE_GWEI, fee = fee) factory = UniswapFactory("ETH pool factory", "0x2") lp = factory.deploy(exchg_data) Join().apply(lp, user_nm, eth_amount, dai_amount, lwr_tick, upr_tick) lp.summary() AddLiquidity().apply(lp, eth, user_nm, UniV3Helper().dec2gwei(10), lwr_tick, upr_tick) lp.summary() ``` -------------------------------- ### Initialize Arbitrage and Token Delta Models Source: https://github.com/defipy-devs/uniswappy/blob/main/notebooks/medium_articles/simple_tree_pt1.ipynb Sets up arbitrage calculators for parent and child LPs, and initializes a model to generate token amount deltas for simulation runs. ```python arb = CorrectReserves(lp, x0 = 1) arb1 = CorrectReserves(lp1, x0 = lp1.reserve1/lp1.reserve0) TKN_amt = TokenDeltaModel(n_sim_runs) ``` -------------------------------- ### Add Liquidity to Uniswap V3 Pool Source: https://github.com/defipy-devs/uniswappy/blob/main/notebooks/tutorials/uniswap_v3.ipynb Demonstrates adding initial liquidity to a Uniswap V3 pool using the Join function. Requires pool setup and parameter initialization. ```python eth = ERC20("ETH", "0x09") tkn = ERC20("TKN", "0x111") exchg_data = UniswapExchangeData(tkn0 = eth, tkn1 = tkn, symbol="LP", address="0x011", version = 'V3', tick_spacing = tick_spacing, fee = fee) factory = UniswapFactory("ETH pool factory", "0x2") lp = factory.deploy(exchg_data) out_v3 = Join().apply(lp, user_nm, eth_amount, tkn_amount, lwr_tick, upr_tick) lp.summary() ``` -------------------------------- ### Initialize Uniswap V3 Order Book Simulation Source: https://github.com/defipy-devs/uniswappy/blob/main/notebooks/medium_articles/order_book.ipynb Sets up necessary imports and initial parameters for simulating a Uniswap V3 order book. Includes mock addresses, token amounts, and fee configurations. ```python from uniswappy import * import pandas as pd import seaborn as sns import matplotlib.pyplot as plt user_nm = MockAddress().apply() eth_amount = 100 tkn_amount = 1000 fee = UniV3Utils.FeeAmount.MEDIUM tick_spacing = UniV3Utils.TICK_SPACINGS[fee] ``` -------------------------------- ### Configure Chain and API for QuantTerminal Source: https://github.com/defipy-devs/uniswappy/blob/main/notebooks/tutorials/quant_terminal.ipynb Sets up the blockchain network, tokens for trading, and time window. The API is initialized with the selected chain. ```python # Buy token selections # - Chain0x.WETH # - Chain0x.LINK # - Chain0x.UNI # - Chain0x.WBTC # - Chain0x.BNB # Sell token selections # - Chain0x.USDC # - Chain0x.USDT # - Chain0x.DAI chain = Chain0x(chain_nm = Chain0x.ETHEREUM, buy_tkn_nm = Chain0x.WETH, sell_tkn_nm = Chain0x.USDC, time_window = 1.5) #chain = Chain0x(chain_nm = Chain0x.POLYGON, buy_tkn_nm = Chain0x.WETH, sell_tkn_nm = Chain0x.USDC, time_window = 1.5) #chain = Chain0x(chain_nm = Chain0x.OPTIMISM, buy_tkn_nm = Chain0x.LINK, sell_tkn_nm = Chain0x.DAI, time_window = 1.5) #chain = Chain0x(chain_nm = Chain0x.AVALANCHE, buy_tkn_nm = Chain0x.BNB, sell_tkn_nm = Chain0x.DAI, time_window = 0.5) api = API0x(chain = chain.chain_nm) ``` -------------------------------- ### Integrate SwapDeposit into SwapDeposit Class Source: https://github.com/defipy-devs/uniswappy/blob/main/notebooks/medium_articles/deposit_like_a_baller.ipynb This snippet demonstrates the integration of the SwapDeposit logic into a SwapDeposit class, applying it to an existing liquidity pool. It requires the same initial setup as the previous snippet. ```python usdc = ERC20("USDC", "0x111") eth = ERC20("ETH", "0x09") exchg_data = UniswapExchangeData(tkn0 = eth, tkn1 = usdc, symbol="LP", address="0x011") factory = UniswapFactory("ETH pool factory", "0x2") lp = factory.deploy(exchg_data) lp.add_liquidity(user_nm, eth_amount, usdc_amount, eth_amount, usdc_amount) lp.summary() s_in = 100 dep = SwapDeposit().apply(lp, eth, user_nm, s_in) lp.summary() ``` -------------------------------- ### Get Uniswap V3 LP Prices Source: https://github.com/defipy-devs/uniswappy/blob/main/notebooks/tutorials/machine_precision_univ3.ipynb Calculates and prints the price of ETH in DAI and DAI in ETH using the LPQuote utility. Assumes LP and token objects are initialized. ```python p_eth = LPQuote().get_price(lp, eth) p_dai = LPQuote().get_price(lp, dai) print(f'The price of {eth.token_name} in {dai.token_name} is {p_eth}') print(f'The price of {dai.token_name} in {eth.token_name} is {p_dai}') ``` -------------------------------- ### Uniswap V2: Deploy Exchange and Add Liquidity Source: https://github.com/defipy-devs/uniswappy/blob/main/README.md Demonstrates deploying a Uniswap V2 exchange and adding initial liquidity using ERC20 tokens. ```python from uniswappy import * user_nm = 'user' eth_amount = 1000 tkn_amount = 100000 tkn = ERC20("TKN", "0x111") eth = ERC20("ETH", "0x09") exchg_data = UniswapExchangeData(tkn0 = eth, tkn1 = tkn, symbol="LP", address="0x011") factory = UniswapFactory("ETH pool factory", "0x2") lp = factory.deploy(exchg_data) Join().apply(lp, user_nm, eth_amount, tkn_amount) lp.summary() ``` -------------------------------- ### Get Current State of Vault Source: https://github.com/defipy-devs/uniswappy/blob/main/notebooks/medium_articles/simple_tree_pt2.ipynb Retrieves the current state of a 'dVault' from a given LP state object. This is typically used to check the amount of assets held or managed by the vault. ```python lp1_state.get_current_state('dVault') ```