What is a DEX Aggregator?
A decentralized exchange (DEX) aggregator is a platform that consolidates liquidity pools across multiple DEXs, so that traders can find the best available prices and pools to optimize their DeFi trades. DEX aggregators optimally match user swap orders from multiple DEXs, and help traders reach pools of deep liquidity, similar to how Google Maps finds the optimal route for drivers.
Having sufficient liquidity in a trading pool enables users to execute trades without fear of slippage. An exchange or marketplace becomes more efficient with higher liquidity. When liquidity is low, trader orders stall, sellers struggle to match buyers, and prices swing. During this time, the expected swap price diverges from the actual swap price, causing slippage. With cryptocurrencies’ inherent volatility, liquidity pools can be unpredictable. DEX aggregators therefore are used by traders to find the most liquidated pools, and swiftly execute a swap order from a single dashboard.
GeckoTerminal DEX Aggregator
GeckoTerminal is a popular DEX aggregator that tracks tokens trading on decentralized exchanges (DEXs), supplying information on price, trading volume, liquidity and more. It currently tracks cryptocurrencies across more than 200 chains and 1,400 decentralized exchanges (DEX), including Uniswap, Sushi, Pancakeswap, Curve, Balancer and more.
In today’s guide, we’ll explore how to leverage GeckoTerminal API to fetch token trade information through its RESTful JSON endpoints. With just one API call, developers and traders can fetch price, market data and historical OHLC charts. The endpoints we'll be covering in this guide are mapped on the GeckoTerminal front-end, accordingly:
Let's dive in!
How to Access Onchain Data for Tokens Traded on DEXs
Access on-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.
Should we want to find the list of available networks from which we can pull data, we can use the /networks endpoints. This retrieves a full list of supported networks and their ids. Then, in narrowing our search, we can pull pool specific data with the /networks/{network}/tokens/{token_address}/pools endpoint to get a specific pool on a network.
This endpoint would appear as:
import requests
url = 'https://api.geckoterminal.com/api/v2/networks/eth/pools/0x60594a405d53811d3bc4766596efd80fd545a270'
parameters = {'accept': 'application/json'}
response = requests.get(url, headers=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’ve 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 vary both parameters to specify other DEXs, using the vast amount of data housed by GeckoTerminal. To find other pool addresses on the Ethereum mainnet, simply go to GeckoTerminal, select a desired pool, and locate the address in the bottom left.
The output from this endpoint includes trading volume, on-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 the GeckoTerminal Public API to find the liquidity pool of a coin, searching by pool address, token address or symbol. This returns a multitude of pools including the queried data. For example, to look for pools on the Ethereum network, our query would simply be ‘ETH’ and we would 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 segregates DEXs with immense liquidity, and locates market efficiency. Pools with high liquidity experience price stability and enable seamless transactions, resulting in more investor confidence, which. perpetuates into 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 select to extract
id_list = []
type_list = []
base_token_price_usd_list = []
volume_usd_list = []
# Add more empty lists for other attributes
# 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 = attributes['volume_usd']['h24']
volume_usd = volume_usd.replace('{', '').replace('}', '').replace('h24: ', '')
volume_usd_list.append(float(volume_usd))
# Append more attributes 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 attributes
})
# Now, 'df' contains the data in separate columns!
df
This creates an easily legible DataFrame that we can manipulate as we look 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 API endpoint /networks/{network}/pools/{pool_address}/ohlcv/{timeframe}, which pulls OHLCV data for desired pools for up to 6 months.
The data granularity of this endpoint covers daily, hourly and minutely data on differing aggregations. The resulting JSON response is incredibly difficult to decipher, prompting the use of pandas dataframe, like so:
#Specifying network, desired pool, and time granularity
network = 'eth'
pool_address = '0x60594a405d53811d3bc4766596efd80fd545a270' #DAI-WETH Pool
parameters = f'{network}/pools/{pool_address}'
specificity = f'{1}'
#URL with your specifications
url = f'https://api.geckoterminal.com/api/v2/networks/{parameters}/ohlcv/day?aggregate={specificity}'
response = requests.get(url)
data = response.json()
#Turning into pandas dataframe, turning the date value into datetime format, making 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. This would look like:
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.xticks(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 API
DEX aggregators play a crucial role in crypto by offering a unified and consolidated platform for DeFi projects and traders to access liquidity pool data across decentralized exchanges. This allows users to optimize swap fees, reduce slippage, and identify fleeting or strong liquidity - and by extension, impacting investor confidence. New projects can leverage this data to influence L1 or L2 deployment decisions, forecasting how user sentiment and participation in a DEX will change overtime. DeFi Apps can utilize GeckoTerminal to access innumerable DEX data from the easily usable API.
While the GeckoTerminal API is currently in beta and subject to changes, it is currently accessible via the CoinGecko API paid plan! Web3 developers and traders who want access to paid exclusive on-chain data and avoid getting rate-limited, may consider subscribing to our Analyst API plan.
If you require a custom solution, fill in 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 or how you can do crypto backtesting easily with a quick start Github repository.
Subscribe to the CoinGecko Daily Newsletter!