Uniswap: How to read token price with API
Asked Answered
F

1

8

In my PHP code (or Javascript) I would like to read erc20 (Ethereum) token price from Uniswap - it is trading there. I cannot find any API call to return me the price.

I am looking to get price for this token: VIRGIN TOKEN: 0x1381F369D9D5df87a1A04Ed856C9dbc90f5DB2fA

How can I do it?

Ferromagnesian answered 5/11, 2020 at 18:38 Comment(1)
Documentation for how to do this for uniswap v2 is at docs.uniswap.org/sdk/2.0.0/guides/pricing.Carlow
M
9

You can query Uniswap data on The Graph using GraphQL.

One way is to query token directly:

{
  token(id: "0x1381f369d9d5df87a1a04ed856c9dbc90f5db2fa") {
    derivedETH
  }
}

... where derivedETH is ETH price.

Another is to query pair (by pair id or, in this example, using token id's):

{
  pairs(where: { token0: "0x1381f369d9d5df87a1a04ed856c9dbc90f5db2fa" token1: "0xc02aaa39b223fe8d0a0e5c4f27ead9083c756cc2" }) {
    token0Price
    token1Price
  }
}

... where token0Price and token1Price are prices of tokens relative to each other (VRGN\WETH).

You can play with these in sandbox or you might need a client.

Alternatively, to keep things simple, you can do request directly, like this:

curl -X POST -H "Content-Type: application/json" -d '{"query": "{ token(id: \"0x1381f369d9d5df87a1a04ed856c9dbc90f5db2fa\") { derivedETH } }"}' https://api.thegraph.com/subgraphs/name/uniswap/uniswap-v2

... to get:

{"data":{"token":{"derivedETH":"0.0004465905539042863338157407540331524"}}}
Myrmecology answered 5/7, 2021 at 20:1 Comment(3)
This looks like some 3rd party api. Is there a way to query a token on the polygon mainnet via uniswap api?Schumann
We can add bundle(id: "1") { ethPrice } to the same query for ETH price in USD, then calculate token price in USD.Shivaree
All the links are not workingCatenary

© 2022 - 2024 — McMap. All rights reserved.