Query pool liquidity on a decentralised exchange#

In this notebook, we show how to get historical (past) available liquidity on PancakeSwap pool. In this example, we use BNB-BUSD pair. We also show how to get the liquidity added and removed during the time period.

About liquidity#

Read the introduction blog post for liquidity analysis so you understand how the liquidity is presented.

Getting started#

Please read and complete the Getting started tutorial first.

First let’s import libraries and initialise our Trading Strategy dataset client.

from tradingstrategy.client import Client

client = Client.create_jupyter_client()
Started Trading Strategy in Jupyter notebook environment, configuration is stored in /Users/moo/.tradingstrategy

Fetching datasets#

Here we fetch the liquidity data for

To make this notebook run fast, we are operating on the historical weekly candles (7 days) to keep the download size of datasets smaller.


from tradingstrategy.chain import ChainId
from tradingstrategy.liquidity import GroupedLiquidityUniverse
from tradingstrategy.pair import PandasPairUniverse
from tradingstrategy.timebucket import TimeBucket

#: We use weekly liquidity candles for the calculations

# Download exchange database
exchange_universe = client.fetch_exchange_universe()

# Download trading pair database
raw_pairs = client.fetch_pair_universe().to_pandas()

# Download liquidity OHLC candles
raw_liquidity_samples = client.fetch_all_liquidity_samples(CANDLE_TIMEFRAME).to_pandas()

# Create a Python helper to manipulate trading pairs
pair_universe = PandasPairUniverse(raw_pairs)

# Create a Python helper to manipulate pair liquidity data
liquidity_universe = GroupedLiquidityUniverse(raw_liquidity_samples)

# Do some test calculations for a single pair
# Note that PancakeSwap has two different deployments:
# you most likely want v2
our_exchange = exchange_universe.get_by_chain_and_slug(ChainId.bsc, "pancakeswap-v2")
assert our_exchange, "Could not find the DEX"

# Query the pair metadata.
# Note that PancakeSwap operates on Wrapped BNB (WBNB), not native BNB token
base_token = "WBNB"
quote_token = "BUSD"

our_pair = pair_universe.get_one_pair_from_pandas_universe(

assert our_pair, "Pair not found"

print(f"Trading pair {base_token}-{quote_token} id is {our_pair.pair_id}, the pool contract address is {our_pair.address}")
Trading pair WBNB-BUSD id is 1364760, the pool contract address is 0x58f876857a02d6762e0101bb5c46a8c1ed44dc16

Querying historical liquidity data#

Here we get the historical available liquidity at 2022-01-01.

Unlike many other examples, or the underlying DEX protocol, here we operate on US Dollar amounts. Any token price is converted to US Dollar through Trading Strategy reference pricing mechanism.

See also XYLiquidity data structure documentation for available values.

import pandas as pd

# December 2021
when = pd.Timestamp("2021-12-01")

liquidity_samples = liquidity_universe.get_liquidity_samples_by_pair(our_pair.pair_id)
if liquidity_samples is None:
    raise AssertionError(f"The universe does not contain liquidity data for pair {our_pair}")

# Get all liquidity OHLC past the certain timestamp.
# Thus, we query the first available liquidity sample *after* the timestamp.
ranged_samples = liquidity_samples[when:]

if len(ranged_samples) == 0:
    raise AssertionError(f"Pair {our_pair} had no liquidity before {when}")

# Get the first sample in the series
# This presents the liquidity at the first available sampled moment
# since the timestamp.
first_sample = ranged_samples.iloc[0]

# Convert liquidity from USD to token
token_liquidity = first_sample.open * first_sample.exchange_rate

Liquidity sampled at: {first_sample.timestamp}
Liquidity sample period: {CANDLE_TIMEFRAME.value}
Liquidity at the begin: {first_sample.open:,.2f} USD
Liquidity at the end: {first_sample.close:,.2f} USD
Liquidity at the begin, expressed as the quote token: {token_liquidity:.4f} {our_pair.quote_token_symbol}
Liquidity added during the period: {first_sample.add_volume:,.2f} USD
Liquidity removed during the period: {first_sample.remove_volume:,.2f} USD

Liquidity sampled at: 2021-12-06 00:00:00
Liquidity sample period: 7d
Liquidity at the begin: 247,629,760.00 USD
Liquidity at the end: 231,012,064.00 USD
Liquidity at the begin, expressed as the quote token: 247629760.0000 BUSD
Liquidity added during the period: 75,168,344.00 USD
Liquidity removed during the period: 96,860,728.00 USD

Further info and sources of potential errors#

See also price impact example.