What is a DEX Aggregator?
A decentralized exchange (DEX) aggregator is a platform that consolidates liquidity pools across multiple DEXs, allowing traders to find the best available prices and pools to optimize their DeFi transactions. DEX aggregators optimally match user exchange orders from multiple DEXs, helping traders reach pools of deep liquidity, similar to how Google Maps finds the optimal route for drivers.
Having sufficient liquidity in a trading pool allows users to execute trades without fear of slippage. An exchange or marketplace becomes more efficient with higher liquidity. When liquidity is low, dealer orders hold up, sellers struggle to match buyers, and prices fluctuate. During this time, the expected exchange price differs from the actual exchange price, causing slippage. With cryptocurrencies’ inherent volatility, liquidity pools can be unpredictable. So DEX aggregators are used by traders to find the most liquidated pools, and quickly execute an exchange order from a single dashboard.
GeckoTerminal DEX Aggregator
GeckoTerminal is a popular DEX aggregator that tracks tokens traded on decentralized exchanges (DEXs), providing information on price, trading volume, liquidity and more. It currently tracks cryptocurrencies across more than 100 chains and 700 decentralized exchanges (DEX), including Uniswap, Sushi, Pancakeswap, Curve, Balancer and more.
In today’s guide, we’ll explore how to use GeckoTerminal DEX data API to retrieve token trading information through its RESTful JSON endpoints. With just one API call, developers and traders can retrieve price, market data and historical OHLC charts. The endpoints we will cover in this guide are mapped accordingly on the GeckoTerminal front end:
Let’s dive in!
How to access chain data for tokens traded on DEXs
Access chain data for DEX traded tokens through CoinGecko API’s on-chain DEX data endpoints. Depending on what data you’re looking for, you can specify a contract address for specific pools, retrieve top or latest pools on a network, or get the latest pools across all networks.
More specifically, you can drill down and get data for:
A specific pool or multiple pools on a network, by specifying a given contract address in the query param. The top 20 or latest 20 pools on a network, for specific networks. The latest 20 pools across all networks. The top 20 pools on a given network’s DEX.
If we want to find the list of available networks from which we can pull data, we can use the /networks endpoints. This retrieves a complete list of supported networks and their IDs. Then, narrowing down our search, we can pull pool specific data using the /networks/{network}/tokens/{token_address}/pools endpoint to find a specific pool on a network.
💡 Pro tip: If you’re unsure how to set up your IDE, refer to this Python API guide.
This endpoint will appear as follows:
import requests url=”https://api.geckoterminal.com/api/v2/networks/eth/pools/0x60594a405d53811d3bc4766596efd80fd545a270″ parameters = {‘accept’: ‘application/json’} get response request = parameters) if response.status_code == 200: # Successful response data = response.json() else: print(f”Request failed with status code: {response.status_code}”)
Use the requests library to access the /networks/{network}/tokens/{token_address}/pools endpoint. We included the ‘eth’ network in the request parameters, and the specific pool address ‘0x60594a405d53811d3bc4766596efd80fd545a270’.
For error handling, should the request be unsuccessful, we print ‘Request failed with status code: {response.status_code}’. We can change both parameters to specify other DEXs, using the large amount of data hosted by GeckoTerminal. To find other pool addresses on the Ethereum mainnet, simply go to GeckoTerminal, select a desired pool and find the address at the bottom left.
The output of this endpoint includes trading volume, chain transactions for a specific token, along with buy and sell transactions.
How to find the liquidity pool of a coin
Use the /search/pools endpoint in GeckoTerminal’s DEX data API to find the liquidity pool of a coin, searching by pool address, token address, or symbol. It returns a set of pools, including the query data. For example, to search for pools on the Ethereum network, our query will simply be ‘ETH’ and we will replace our url with the new request url:
url=”https://api.geckoterminal.com/api/v2/search/pools?query=ETH”
This endpoint is extremely useful for crypto projects and developers as it separates DEXs with immense liquidity and tracks market efficiency. Pools with high liquidity experience price stability and enable seamless transactions, leading to greater investor confidence, which. persist in more developers establishing pools on the same DEX. Conversely, low liquidity can cause unsettling and unpredictable fluctuations for newly established projects. The request outputs the following JSON text:
{‘data’: [{‘id’: ‘eth_0x88e6a0c2ddd26feeb64f039a2c41296fcb3f5640’, ‘type’: ‘pool’, ‘attributes’: {‘base_token_price_usd’: ‘1827.82349971122’, ‘base_token_price_native_currency’: ‘1.0’, ‘quote_token_price_usd’: ‘0.997985290842797’, ‘quote_token_price_native_currency’: ‘0.000545991457703024’, ‘base_token_price_quote_token’: ‘1831.53’, ‘quote_token_price_base_token’: ‘0.00054599’, ‘address’: ‘0x88e6a0c2ddd26feeb64f039a2c41296fcb3f5640’, ‘name’: ‘WETH / USDC 0.05%’, ‘pool_created_at’: None, ‘fdv_usd’: ‘5911367354’, ‘market_cap_usd’: None, ‘price_change_percentage’: {‘h1’: ‘-0.02’, ‘h24’: ‘1.31’}, ‘transactions’: {‘h1’: {‘buys’: 76, ‘sells’: 88}, ‘h24’: {‘buys’: 2649, ‘sells’: 2746}}, ‘volume_usd’: {‘h24’: ‘366293316.2813256561009998’}, ‘reserve_in_usd’: ‘195144837.9232’}, ‘relationships’: {‘base_token’: {‘data’: {‘id’: ‘eth_0xc02aaa39b223fe8d0a0e5c4f27ead9083c756cc2’, ‘type’: ‘token’}}, ‘quote_token’: {‘data’: {‘id’: ‘eth_0xa0b86991c6218b36c1d19d4a2e9eb0ce3606eb48’, ‘type’: ‘token’}}, ‘dex’: {‘data’: {‘id’: ‘uniswap_v3’, ‘type’: ‘dex’}}}},
And thereafter goes to show the next pool’s data, and so on.
{‘id’: ‘eth_0x4585fe77225b41b697c938b018e2ac67ac5a20c0’, ….
How to Find Liquidity Pools on a Network
To find multiple liquidity pools on the network, use the /networks/{network}/pools/multi/{address} endpoint in GeckoTerminal’s DEX data API. For example, to pull data on all liquidity pools on Uniswap V3, simply include all pools’ addresses. The addresses will be separated by commas, like:
Pool_address_#1,Pool_address_#2,Pool_address_#3… The url, therefore, becomes: pool1 = ‘0x88e6a0c2ddd26feeb64f039a2c41296fcb3f5640’ pool2 = ‘0x11950d141ecb863f01007add7d1a342041227b58’ pool3 = ‘0x60594a405d53811d3bc4766596efd80fd545a270’
# Concatenate the pool addresses as a comma-separated string pools = f'{pool1},{pool2},{pool3}’
url = f’https://api.geckoterminal.com/api/v2/networks/eth/pools/multi/{pools}’
By doing so, we are able to get data from the DAI/WETH, WETH/USDC, and PEPE/WETH pools simultaneously. Now our output includes data concerning specific pools:
First: WETH/USDC Pool: {‘data’: [{‘id’: ‘eth_0x88e6a0c2ddd26feeb64f039a2c41296fcb3f5640’, ‘type’: ‘pool’, ‘attributes’: {‘base_token_price_usd’: ‘1828.45810660423’, ‘base_token_price_native_currency’: ‘1.0’, ‘quote_token_price_usd’: ‘0.997676722335158’, ‘quote_token_price_native_currency’: ‘0.000545627354443188’, ‘base_token_price_quote_token’: ‘1832.75’, ‘quote_token_price_base_token’: ‘0.00054563’, ‘address’: ‘0x88e6a0c2ddd26feeb64f039a2c41296fcb3f5640’, ‘name’: ‘WETH / USDC 0.05%’, ‘pool_created_at’: None, ‘fdv_usd’: ‘5913419738’, ‘market_cap_usd’: None, ‘price_change_percentage’: {‘h1’: ‘0.03’, ‘h24’: ‘1.31’}, ‘transactions’: {‘h1’: {‘buys’: 61, ‘sells’: 87}, ‘h24’: {‘buys’: 2645, ‘sells’: 2747}}, ‘volume_usd’: {‘h24’: ‘366072244.7173006110111998’}, ‘reserve_in_usd’: ‘195158456.8977’}, ‘relationships’: {‘base_token’: {‘data’: {‘id’: ‘eth_0xc02aaa39b223fe8d0a0e5c4f27ead9083c756cc2’, ‘type’: ‘token’}}, ‘quote_token’: {‘data’: {‘id’: ‘eth_0xa0b86991c6218b36c1d19d4a2e9eb0ce3606eb48’, ‘type’: ‘token’}}, ‘dex’: {‘data’: {‘id’: ‘uniswap_v3’, ‘type’: ‘dex’}}}},
After which, we see the data for the PEPE/WETH pool, and so on.
{‘id’: ‘eth_0x11950d141ecb863f01007add7d1a342041227b58’, ….
How to Get Market Data for a Liquidity Pool
Retrieve market data for a DEX liquidity pool by using the GeckoTerminal DEX data API endpoint /networks/{network}/pools/{address}. You can specify the query param to obtain data for the top 20 pools on a network.
For instance, to get market data for liquidity pools with the highest 24H trading volume on the Ethereum Mainnet we will use ‘eth’ for {network} and use the ‘volume_usd’ query param. This adjusts the API call to search for the top 20 pools befitting this criterion – an incredibly useful endpoint for developers! Additionally, we can improve the legibility of the JSON request by using a Pandas Dataframe:
Import pandas as pd url=”https://api.geckoterminal.com/api/v2/networks/eth/pools?include=volume_usd”
response = requests.get(url) data = response.json()
# Extract the ‘data’ field from the JSON response which includes all of our desired attributes data_list = data[‘data’]
# Initialize empty lists to store the data we choose to extract id_list = [] type_list = [] base_token_price_usd_list = [] volume_usd_list = [] # Add more empty lists for other properties
# Iterate through each data point in the created list to extract certain attributes for data_point in data_list: attributes = data_point[‘attributes’]
id_list.append(data_point[‘id’]) type_list.append(data_point[‘type’]) base_token_price_usd_list.append(attributes[‘base_token_price_usd’])
# Extract ‘volume_usd’ without ‘{‘, ‘h24’ and ‘}’ volume_usd = properties[‘volume_usd’][‘h24’] volume_usd = volume_usd.replace(‘{‘, ”).replace(‘}’, ”).replace(‘h24: ‘, ”) volume_usd_list.append(float(volume_usd)) # Add more properties to their respective lists if you want
# Create a DataFrame from the lists created df = pd.DataFrame({ ‘id’: id_list, ‘type’: type_list, ‘base_token_price_usd’: base_token_price_usd_list, ’24_hour_volume’: volume_usd_list, # Add more columns for other properties
})
# Now, ‘df’ contains the data in separate columns! df
This creates an easy-to-read DataFrame that we can manipulate while searching for certain data points:
How to Get OHLCV Candlestick Data for DEXs
The easiest way to get OHLCV candlestick data for DEXs is to use the GeckoTerminal DEX data API endpoint /networks/{network}/pools/{pool_address}/ohlcv/{timeframe}, which provides OHLCV data for draw desired pools for up to 6 months.
The data granularity of this endpoint covers daily, hourly and minute data across different aggregations. The resulting JSON response is incredibly hard to decipher, prompting the use of pandas dataframe, like so:
#Specify network, desired pool and time granularity network = ‘eth’ pool_address=”0x60594a405d53811d3bc4766596efd80fd545a270″ #DAI-WETH Pool parameters = f'{network}/pools/{pool_address}’ specificity
#URL with your specification url = f’https://api.geckoterminal.com/api/v2/networks/{parameters}/ohlcv/day?aggregate={specificity}’
response = requests.get(url) data = response.json()
#Change in pandas dataframe, change the date value to datetime format, make it the index data = data[‘data’][‘attributes’][‘ohlcv_list’]
df = pd.DataFrame(data, columns=[‘Date’, ‘Open’, ‘Close’, ‘High’, ‘Low’, ‘Volume’]) df[‘Date’] = pd.to_datetime(df[‘Date’]unit=”ms”) df.set_index(‘Date’, inplace = True) df
We can plot candlestick charts using matplotlibs.pyplot to visualize our newfound data. It will look like this:
import matplotlib.pyplot as plt
plt.figure(figsize = (12,6)) plt.plot(df[‘Open’]label=”Open”, alpha=0.5) plt.plot(df[‘Close’]label=”CLOSE”, alpha=0.5) plt.plot(df[‘High’]label=”High”, alpha=0.5) plt.plot(df[‘Low’]label=”Low”, alpha=0.5) plt.xlabel(‘Date’) plt.ylabel(‘Price’) plt.title(‘OHLC Data’) plt.xticcks(rotation=45) # Rotate x-axis labels for better readability
plt.show()
Now we can see the variation in price over the past few months in this one pool:
Build DeFi Apps with GeckoTerminal DEX Data API
DEX aggregators play a pivotal role in crypto by providing a unified and consolidated platform for DeFi projects and traders to access liquidity pool data across decentralized exchanges. It enables users to optimize exchange fees, reduce slippage, and identify volatile or strong liquidity – and by extension, impact investor confidence. New projects can use this data to influence L1 or L2 deployment decisions, predicting how user sentiment and participation in a DEX will change over time. DeFi Apps can use GeckoTerminal to access countless DEX data from the easy-to-use API.
GeckoTerminal’s DEX data API is currently in beta and will soon be integrated into CoinGecko API. Web3 developers and traders who want access to more crypto market data and avoid getting rate-capped can consider subscribing to our Analyst API plan. The CoinGecko API currently has 50+ endpoints, tracks 10,000+ coins across 900+ exchanges and 3,000+ NFT collections serving billions of API calls every month.
If you need a custom solution, fill out the form below to get in touch with our API sales team:
Disclaimer: This guide is for illustrative and informational purposes only, and does not constitute professional or financial advice. Always do your own research and be careful when putting your money into any crypto or financial asset.
Looking for further API resources? Check out this guide on 5 popular crypto trading strategies and how to backtest using historical crypto data.
Tell us how much you like this article!
Jackson Henning
Jackson Henning has a background in economics and spent 3 years in crypto, mainly entrenched in NFTs and DeFi. He is particularly intrigued by the perpetual ingenuity common to crypto trading, along with the use of technical analysis and the ability of DeFi to push the boundaries of traditional finance. Follow the author on Twitter @Henninng
Read more about Jackson Henning
Disclaimer for Uncirculars, with a Touch of Personality:
While we love diving into the exciting world of crypto here at Uncirculars, remember that this post, and all our content, is purely for your information and exploration. Think of it as your crypto compass, pointing you in the right direction to do your own research and make informed decisions.
No legal, tax, investment, or financial advice should be inferred from these pixels. We’re not fortune tellers or stockbrokers, just passionate crypto enthusiasts sharing our knowledge.
And just like that rollercoaster ride in your favorite DeFi protocol, past performance isn’t a guarantee of future thrills. The value of crypto assets can be as unpredictable as a moon landing, so buckle up and do your due diligence before taking the plunge.
Ultimately, any crypto adventure you embark on is yours alone. We’re just happy to be your crypto companion, cheering you on from the sidelines (and maybe sharing some snacks along the way). So research, explore, and remember, with a little knowledge and a lot of curiosity, you can navigate the crypto cosmos like a pro!
UnCirculars – Cutting through the noise, delivering unbiased crypto news