Python UNISWAP子图 - 恒定产品公式

发布于 2025-02-03 07:45:42 字数 2250 浏览 4 评论 0 原文

我正在尝试计算对交易的价格影响,并取得奇怪的结果。

我正在使用uniswap v2子图来获取WETH/USDC的当前数据。

def loadUni2():
    query = """

{
    pairs (
    first: 10
    orderBy: volumeUSD
    orderDirection:desc
  
  ){
    id
    reserve0
    token0Price
    token0 {
      id
      symbol
      decimals
    }
    token1Price
    reserve1
    token1{
      id
      symbol
      decimals
    } 
  }
}

"""

然后,我将此查询的结果保存到单个变量中,并为“恒定产品公式”进行相同的数学,该数学与Uniswap表示它用于池,

pair = pairs[0]


#sort dataframe by lowest price 
low = pair.sort_values(by='token0Price', ascending=True)

quoteReserve = low['reserve0'].values[0]   #USDC Tokens in pair verified by checking info.uniswap.org
baseReserve = low['reserve1'].values[0]    #WETH tokens in pair verified by checking info.uniswap.org
token0Price = low['token0Price'].values[0] 
token1Price = low['token1Price'].values[0]

#Buy Low
amount = 1   # purchase amount in USD
constant = quoteReserve * baseReserve

newReserve = (quoteReserve + amount)

output = constant / newReserve

wethPurchaseAmount = baseReserve - output

pricePerToken = amount / wethPurchaseAmount

if (newReserve * output) == constant:
  check = True

print(f'Token0Price before trade : {token0Price}')
print(f'Token1Price before trade: {token1Price}')
print(f'Quote Reserves: {quoteReserve}')
print(f'Base Reserves: {baseReserve}')
print(f'Constant: {constant}')
print(f'New Reserve: {newReserve}')
print(f'Output: {output}')
print(f'WETH Purchased Amount: {wethPurchaseAmount}')
print(f'Price paid Per Token : {pricePerToken}')
print(check)

因为我的金额仅为1美元,即每电代币支付的价格应与Token0price相匹配。但是我的结果看起来像是:


Token0Price : 1942.4506384054528
Token1Price: 0.0005148135969215
Quote Reserves: 121784650.548786
Base Reserves: 105869.64875708237
Constant: 12893298177603.992
New Reserve: 121784651.548786
Output: 105869.64788776389
WETH Purchased Amount: 0.0008693184790899977
Price Per Token: 1150.3264040203076
True

我要么缺少某些东西,要么以某种方式错了?任何建议/想法将不胜感激。

这是我找到常数产品公式< /a>

另外,我唯一的进口是“请求”和“熊猫” 在Google合作笔记本中运行它。

如果很难阅读,我对此表示歉意,我完全是新手。

I'm trying to calculate the price impact on trades and am getting strange results.

I am using uniswap v2 subgraph to get current data for WETH/USDC.

def loadUni2():
    query = """

{
    pairs (
    first: 10
    orderBy: volumeUSD
    orderDirection:desc
  
  ){
    id
    reserve0
    token0Price
    token0 {
      id
      symbol
      decimals
    }
    token1Price
    reserve1
    token1{
      id
      symbol
      decimals
    } 
  }
}

"""

I then save the results of this query into individual variables and do the same math for the "constant product formula" that uniswap says it uses for its pools

pair = pairs[0]


#sort dataframe by lowest price 
low = pair.sort_values(by='token0Price', ascending=True)

quoteReserve = low['reserve0'].values[0]   #USDC Tokens in pair verified by checking info.uniswap.org
baseReserve = low['reserve1'].values[0]    #WETH tokens in pair verified by checking info.uniswap.org
token0Price = low['token0Price'].values[0] 
token1Price = low['token1Price'].values[0]

#Buy Low
amount = 1   # purchase amount in USD
constant = quoteReserve * baseReserve

newReserve = (quoteReserve + amount)

output = constant / newReserve

wethPurchaseAmount = baseReserve - output

pricePerToken = amount / wethPurchaseAmount

if (newReserve * output) == constant:
  check = True

print(f'Token0Price before trade : {token0Price}')
print(f'Token1Price before trade: {token1Price}')
print(f'Quote Reserves: {quoteReserve}')
print(f'Base Reserves: {baseReserve}')
print(f'Constant: {constant}')
print(f'New Reserve: {newReserve}')
print(f'Output: {output}')
print(f'WETH Purchased Amount: {wethPurchaseAmount}')
print(f'Price paid Per Token : {pricePerToken}')
print(check)

Since my amount is only $1 the price paid per token should match the token0Price. But my results look like:


Token0Price : 1942.4506384054528
Token1Price: 0.0005148135969215
Quote Reserves: 121784650.548786
Base Reserves: 105869.64875708237
Constant: 12893298177603.992
New Reserve: 121784651.548786
Output: 105869.64788776389
WETH Purchased Amount: 0.0008693184790899977
Price Per Token: 1150.3264040203076
True

I'm either missing something or somehow my math is wrong? Any suggestions/ideas would be greatly appreciated.

Here's the link for where I found an example of the Constant Product Formula

Also, the only imports I have are 'requests' and 'pandas'
Running it in a google collab notebook.

I apologize in advance if this is hard to read, I'm completely new to this.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

凉城已无爱 2025-02-10 07:45:42

您不包括影响回报量的0.3%费用。最初,我们有“ x”和“ y”量,因此恒定的乘积

 k = x * y

是x和y之间存在的反相关关系,因为一个增加会导致另一个

方程的图表

i.sstatic.net/izlf7.png“ rel =“ nofollow noreferrer 图表上的“ k”是恒定的

  k  = (x+dx) * (y-dy)
  xy = (x+dx) * (y-dy)

您添加了一些“ x”令牌,“ y”令牌的数量将减少,但是如果您乘以右侧paranthesse,则

  xy = xy - xdy + ydx -dydx

xy 取消

 0=ydx - xdy - dydx

我正在寻找我正在寻找的。 dy 所以

 xdy + dydx = ydx
 dy(x+dx)=ydx

请留下 dy

 dy = ydx / (x+dx)

到目前为止,我们一直在交换“ x”代币以接收“ y”令牌,我们正在计算多少“ y”令牌将从水池。当我们交换“ X”令牌时,我们还必须支付0.3%的费用,即0.3%的“ X”令牌。我们要发送交换的“ DX”金额,因为将占用此金额的0.3%,我们实际上将交换

(1 - 0.3%) dx
(1 - (0.3/100)) dx
(1 - (0.003))dx
0.997 dx

这是我们实际上交换的“ x”令牌的总数。我们的最终公式将是

 dy = y *(0.997dx) / (x + 0.997dx)

您应计算WETH购买金额的方式。

you are not including the 0.3% percent fee which affects the amount of return value. initially we have "x" and "y" amount so constant product is

 k = x * y

There is an inverse relationship between x and y because increase in one will lead to decrease on other

this is our graph for this equation

enter image description here

If you add some "x" token, the amount of "y" token will decrease, but "k" is constant in everwhere on the graph

  k  = (x+dx) * (y-dy)
  xy = (x+dx) * (y-dy)

If you multiply right side parantheses:

  xy = xy - xdy + ydx -dydx

xy cancels out

 0=ydx - xdy - dydx

I am looking for dy so

 xdy + dydx = ydx
 dy(x+dx)=ydx

leave dy alone

 dy = ydx / (x+dx)

So far we have been swapping "x" token to receive "y" token and we are calculating how much "y" tokens will be decreased from the pool. When we swap "x" token we also have to pay 0.3% fee which is 0.3% "x" token. "dx" here amount that we are sending to swap, since 0.3% of this amount will be taken, we will be actually swapping

(1 - 0.3%) dx
(1 - (0.3/100)) dx
(1 - (0.003))dx
0.997 dx

this is total amount of "x" token that we are actually swapping. Our final formula will be

 dy = y *(0.997dx) / (x + 0.997dx)

this is how you should calculate the weth purchase amount.

拥醉 2025-02-10 07:45:42

在您的计算中,您忘记了与每次交换相关的0.3%费用。使用费用时,恒定产品公式的常数实际上会改变,因此在计算输出储备时不会准确。混乱不是吗?我解释了为什么k-value在答案中会更改在这里

相反,我找到了恒定产品公式的有用。本质上,要获得USDC输入金额的Weth的输出量,公式将是:

” ,和 wethoutputreserve = wethreserve -wethoutput 。借助这些输出储备,您可以计算新的代币价格,从而对上一笔交易的价格产生影响。

让我知道这是否回答您的问题。

In your calculations you're forgetting to account for the 0.3% fee associated with each swap. When using a fee, the constant in the Constant Product Formula will actually change and so won't be accurate when calculating output reserves. Confusing isn't it? I explained why the K-value changes in my answer here.

Instead, I've found this formalization of the Constant Product Formula to be useful. Essentially to get an output amount in WETH given an input amount in USDC, the formula would be:

equation

Then, usdcOutputReserve = usdcReserve - usdcInput, and wethOutputReserve = wethReserve - wethOutput. With these output reserves you can calculate the new token prices and therefore price impact of the previous trade.

Let me know if this answers your question.

深者入戏 2025-02-10 07:45:42

您可以

def estimate_buy_price(
    uniswap: UniswapV2Deployment,
    base_token: Contract,
    quote_token: Contract,
    quantity: int,
    *,
    fee: int = 30,
    slippage: float = 0,
    intermediate_token: Optional[Contract] = None,
) -> int:
    """Estimate how much we are going to need to pay when doing buy.
    Calls the on-chain contract to get the current liquidity and estimates the
    the price based on it.
    Example:
    .. code-block:: python
        # Estimate how much ETH we will receive for 500 USDC.
        # In this case the pool ETH price is $1700 so this should be below ~1/4 of ETH
        amount_eth = estimate_buy_price(
            uniswap_v2,
            weth,
            usdc,
            1*10**18,
        )
        assert amount_eth / 1e18 == pytest.approx(0.28488156127668085)
    :param uniswap: Uniswap v2 deployment
    :param base_token: Base token of the trading pair
    :param quote_token: Quote token of the trading pair
    :param quantity: How much of the base token we want to buy
    :param fee: Trading fee express in bps, default = 30 bps (0.3%)
    :param slippage: Slippage express in bps
    :return: Expected base token to receive
    """
    fee_helper = UniswapV2FeeCalculator(uniswap)
    if intermediate_token:
        path = [quote_token.address, intermediate_token.address, base_token.address]
    else:
        path = [quote_token.address, base_token.address]
    return fee_helper.get_amount_in(quantity, path, fee=fee, slippage=slippage)

请参阅链接以获取更长的,完整的源代码。

如果您使用的是jupyter笔记本,您可能还会感兴趣,您可能会在此处感兴趣。 a>。

You can find example price impact calculations in Python here:

def estimate_buy_price(
    uniswap: UniswapV2Deployment,
    base_token: Contract,
    quote_token: Contract,
    quantity: int,
    *,
    fee: int = 30,
    slippage: float = 0,
    intermediate_token: Optional[Contract] = None,
) -> int:
    """Estimate how much we are going to need to pay when doing buy.
    Calls the on-chain contract to get the current liquidity and estimates the
    the price based on it.
    Example:
    .. code-block:: python
        # Estimate how much ETH we will receive for 500 USDC.
        # In this case the pool ETH price is $1700 so this should be below ~1/4 of ETH
        amount_eth = estimate_buy_price(
            uniswap_v2,
            weth,
            usdc,
            1*10**18,
        )
        assert amount_eth / 1e18 == pytest.approx(0.28488156127668085)
    :param uniswap: Uniswap v2 deployment
    :param base_token: Base token of the trading pair
    :param quote_token: Quote token of the trading pair
    :param quantity: How much of the base token we want to buy
    :param fee: Trading fee express in bps, default = 30 bps (0.3%)
    :param slippage: Slippage express in bps
    :return: Expected base token to receive
    """
    fee_helper = UniswapV2FeeCalculator(uniswap)
    if intermediate_token:
        path = [quote_token.address, intermediate_token.address, base_token.address]
    else:
        path = [quote_token.address, base_token.address]
    return fee_helper.get_amount_in(quantity, path, fee=fee, slippage=slippage)

See the link for longer, full, source code.

If you are using Jupyter notebooks, you might be also interested the example notebooks here.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文