【问题标题】:Python Uniswap Subgraph - Constant product formulaPython Uniswap 子图 - 常数乘积公式
【发布时间】:2022-06-13 04:07:10
【问题描述】:

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

我正在使用 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

我要么遗漏了什么,要么我的数学有问题?任何建议/想法将不胜感激。

这是我找到Constant Product Formula 示例的链接

另外,我唯一的导入是“请求”和“熊猫” 在 google 协作笔记本中运行它。

如果这很难阅读,我提前道歉,我对此完全陌生。

【问题讨论】:

  • 您能否阐明预期的行为应该是什么?您要准确计算什么?
  • 价格影响。 Uniswap 文档说他们使用恒定乘积公式。每个代币的价格应与 Token0Price 匹配

标签: python blockchain web3py uniswap thegraph


【解决方案1】:

在您的计算中,您忘记了与每次掉期相关的 0.3% 费用。使用费用时,恒积公式中的常数实际上会发生变化,因此在计算输出储备时将不准确。是不是很迷惑?我解释了为什么我的答案 here 中的 K 值会发生变化。

相反,我发现this 定积公式的形式化很有用。本质上,要在给定 USDC 输入量的情况下获得 WETH 输出量,公式为:

然后,usdcOutputReserve = usdcReserve - usdcInputwethOutputReserve = wethReserve - wethOutput。使用这些输出储备,您可以计算新的代币价格,从而计算先前交易的价格影响。

如果这回答了你的问题,请告诉我。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-04-26
    • 2020-08-30
    • 1970-01-01
    • 1970-01-01
    • 2021-08-21
    • 1970-01-01
    • 2017-08-17
    • 1970-01-01
    相关资源
    最近更新 更多