Coins: 14,032
Exchanges: 1,073
Market Cap: $2.485T 4.6%
24h Vol: $82.345B
Gas: 8 GWEI
Go Ad-free
API
TABLE OF CONTENTS

How to Get Decentralized Exchange Data with DEX Data API

5.0 | by Jackson Henning

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 Data API

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 100 chains and 700 decentralized exchanges (DEX), including Uniswap, Sushi, Pancakeswap, Curve, Balancer and more.

In today’s guide, we’ll explore how to leverage GeckoTerminal DEX data 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 On-Chain 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.

💡 Pro-tip: If you are unsure how to set up your IDE, refer to this Python API Guide.

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. 

Locate the pool address on GeckoTerminal - CoinGecko DEX Data API

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 GeckoTerminal’s DEX data 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:

easily legible DataFrame


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 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 DEX Data 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.

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 limited, may 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 each month.

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 and how you can backtest using historical crypto data.

CoinGecko's Content Editorial Guidelines
CoinGecko’s content aims to demystify the crypto industry. While certain posts you see may be sponsored, we strive to uphold the highest standards of editorial quality and integrity, and do not publish any content that has not been vetted by our editors.
Learn more
Tell us how much you like this article!
Vote count: 6
Jackson Henning
Jackson Henning

Jackson Henning has a background in economics and has spent 3 years in crypto, primarily ensconced in NFTs and DeFi. He is especially intrigued by the perpetual ingenuity common to crypto trading, along with the employment of technical analysis and the ability of DeFi to push the bounds of traditional finance. Follow the author on Twitter @Henninng

More Articles

coingecko
Continue in app
Track prices in real-time
Open App
Select Currency
Suggested Currencies
USD
US Dollar
IDR
Indonesian Rupiah
TWD
New Taiwan Dollar
EUR
Euro
KRW
South Korean Won
JPY
Japanese Yen
RUB
Russian Ruble
CNY
Chinese Yuan
Fiat Currencies
AED
United Arab Emirates Dirham
ARS
Argentine Peso
AUD
Australian Dollar
BDT
Bangladeshi Taka
BHD
Bahraini Dinar
BMD
Bermudian Dollar
BRL
Brazil Real
CAD
Canadian Dollar
CHF
Swiss Franc
CLP
Chilean Peso
CZK
Czech Koruna
DKK
Danish Krone
GBP
British Pound Sterling
GEL
Georgian Lari
HKD
Hong Kong Dollar
HUF
Hungarian Forint
ILS
Israeli New Shekel
INR
Indian Rupee
KWD
Kuwaiti Dinar
LKR
Sri Lankan Rupee
MMK
Burmese Kyat
MXN
Mexican Peso
MYR
Malaysian Ringgit
NGN
Nigerian Naira
NOK
Norwegian Krone
NZD
New Zealand Dollar
PHP
Philippine Peso
PKR
Pakistani Rupee
PLN
Polish Zloty
SAR
Saudi Riyal
SEK
Swedish Krona
SGD
Singapore Dollar
THB
Thai Baht
TRY
Turkish Lira
UAH
Ukrainian hryvnia
VEF
Venezuelan bolívar fuerte
VND
Vietnamese đồng
ZAR
South African Rand
XDR
IMF Special Drawing Rights
Cryptocurrencies
BTC
Bitcoin
ETH
Ether
LTC
Litecoin
BCH
Bitcoin Cash
BNB
Binance Coin
EOS
EOS
XRP
XRP
XLM
Lumens
LINK
Chainlink
DOT
Polkadot
YFI
Yearn.finance
Bitcoin Units
BITS
Bits
SATS
Satoshi
Commodities
XAG
Silver - Troy Ounce
XAU
Gold - Troy Ounce
Select Language
Popular Languages
EN
English
RU
Русский
DE
Deutsch
PL
język polski
ES
Español
VI
Tiếng việt
FR
Français
PT
Português
All Languages
AR
العربية
BG
български
CS
čeština
DA
dansk
EL
Ελληνικά
FI
suomen kieli
HE
עִבְרִית
HI
हिंदी
HR
hrvatski
HU
Magyar nyelv
ID
Bahasa Indonesia
IT
Italiano
JA
日本語
KO
한국어
LT
lietuvių kalba
NL
Nederlands
NO
norsk
RO
Limba română
SK
slovenský jazyk
SL
slovenski jezik
SV
Svenska
TH
ภาษาไทย
TR
Türkçe
UK
украї́нська мо́ва
ZH
简体中文
ZH-TW
繁體中文
Login to track your favorite coin easily 🚀
By continuing, you agree to CoinGecko Terms of Service and acknowledge you’ve read our Privacy Policy
or
Forgot your password?
Didn't receive confirmation instructions?
Resend confirmation instructions
IT'S FREE! Track your favorite coin easily with CoinGecko 🚀
By continuing, you agree to CoinGecko Terms of Service and acknowledge you’ve read our Privacy Policy
or
Password must contain at least 8 characters including 1 uppercase letter, 1 lowercase letter, 1 number, and 1 special character
Didn't receive confirmation instructions?
Resend confirmation instructions
Forgot your password?
You will receive an email with instructions on how to reset your password in a few minutes.
Resend confirmation instructions
You will receive an email with instructions for how to confirm your email address in a few minutes.
Get the CoinGecko app.
Scan this QR code to download the app now App QR Code Or check it out in the app stores