Retrieve your USD/EURO wallet balance via Binance API

Get your token balances with Python and the Binance API.

Steve Dua
6 min readMar 21, 2023
Image generated on Midjourney. Prompt: a balance with gold-colored Bitcoins on one side and weights on the other — ar 3:2
Image generated on Midjourney. Prompt: a balance with gold-colored Bitcoins on one side and weights on the other — ar 3:2

Binance is a hot spot for trading cryptocurrencies, offering a ton of services like spot trading, margin trading, futures trading, and more.
If you’re like me and want to keep tabs on your portfolio and assets’ worth, using the Binance API to calculate their USD value is one way to do it

After some digging, I found out that many online Python scripts make the wrong assumption that each coin in Binance has a USDT trading pair, so make sure to check if that’s the case for each coin in your spot wallet.
In scenarios where a USDT trading pair is not available, an alternative trading pair such as BTC can be utilized.

To help you out, I’ll take you step by step through creating a Binance API key, installing the necessary Python packages, and writing the code to get your spot asset balance.

Steps:

  • Obtain a Binance API key.
  • Install the Binance package.
  • Create a function that retrieves the balance of all coins.
  • List out the coins and their USD or EURO values in descending order.
  • To see the whole picture, print out the “Grand Total”.

How to get a Binance API key

If you want to use the Binance API, you have to create an API key.
Here’s how you can create a Binance API key:

  • Log in to your Binance account.
  • Go to your account settings and click on the API Management tab.
  • Click on the Create API button.
  • Enter a label for your API key (e.g., “My Python App”).
  • Verify your identity using two-factor authentication.
  • Once verified, you will receive an API key and a secret key.

Make sure to keep your keys secure as they allow access to your Binance account.

Installing the binance package

To use the Binance API with Python, you need to install the binance package.
Open up your terminal or command prompt and type in the following command.

pip3 install binance

Setting up our Binance client

Let’s get this show on the road!
The first step is to import the “binance.client” package. This package will help us easily fetch and show our Binance account balance.

Create a file named ‘binancewallet.py’ and import the required module.

binancewallet.py file

from binance.client import Client

Retrieving Binance account balances

Here’s what this piece of code does: it creates a function called get_account_balances that fetches the balances of all the coins in the user’s Binance account and it calculates the USDT value of each of those coins.

def get_account_balances():

# Create a new client object to interact with the Binance API
client = Client("<<your_binance_api_key>>", "<<your_binance_secret_key>>")

# Retrieve the balances of all coins in the user’s Binance account
account_balances = client.get_account()[‘balances’]

# Get the current price of all tickers from the Binance API
ticker_info = client.get_all_tickers()

# Create a dictionary of tickers and their corresponding prices
ticker_prices = {ticker[‘symbol’]: float(ticker[‘price’]) for ticker in ticker_info}

# Calculate the USDT value of each coin in the user’s account
coin_values = []
for coin_balance in account_balances:
# Get the coin symbol and the free and locked balance of each coin
coin_symbol = coin_balance['asset']
unlocked_balance = float(coin_balance['free'])
locked_balance = float(coin_balance['locked'])

# If the coin is USDT and the total balance is greater than 1, add it to the list of coins with their USDT values
if coin_symbol == 'USDT' and unlocked_balance + locked_balance > 1:
coin_values.append(('USDT', (unlocked_balance + locked_balance)))
# Otherwise, check if the coin has a USDT trading pair or a BTC trading pair
elif unlocked_balance + locked_balance > 0.0:
# Check if the coin has a USDT trading pair
if (any(coin_symbol + 'USDT' in i for i in ticker_prices)):
# If it does, calculate its USDT value and add it to the list of coins with their USDT values
ticker_symbol = coin_symbol + 'USDT'
ticker_price = ticker_prices.get(ticker_symbol)
coin_usdt_value = (unlocked_balance + locked_balance) * ticker_price
if coin_usdt_value > 1:
coin_values.append((coin_symbol, coin_usdt_value))
# If the coin does not have a USDT trading pair, check if it has a BTC trading pair
elif (any(coin_symbol + 'BTC' in i for i in ticker_prices)):
# If it does, calculate its USDT value and add it to the list of coins with their USDT values
ticker_symbol = coin_symbol + 'BTC'
ticker_price = ticker_prices.get(ticker_symbol)
coin_usdt_value = (unlocked_balance + locked_balance) * ticker_price * ticker_prices.get('BTCUSDT')
if coin_usdt_value > 1:
coin_values.append((coin_symbol, coin_usdt_value))

# Sort the list of coins and their USDT values by USDT value in descending order
coin_values.sort(key=lambda x: x[1], reverse=True)

# Return the list of coins and their USDT values
return coin_values

The function get_account_balances first creates a new client object to interact with the Binance API using the Binance API key and secret key.

It then retrieves the balances of all coins in the user’s Binance account using the get_account method of the client object and stores them in the account_balances variable.

Next, it gets the current price of all tickers from the Binance API using the get_all_tickers method of the client object and creates a dictionary called ticker_prices with tickers and their corresponding prices.

The code then iterates through the account_balances list to calculate the USDT value of each coin.
For each coin, it checks if it is USDT and if its total balance is greater than 1.
If so, it adds it to the coin_values list with its USDT value.
Otherwise, it checks if the coin has a USDT trading.

Our cool trick — if there’s no USDT coin pair available, we can check if a BTC coin pair is available to calculate our balance.

So, if it has a USDT trading pair, it calculates its USDT value and adds it to the coin_values list.
If it does not have a USDT trading pair but has a BTC trading pair, it calculates its USDT value using the BTC price and adds it to the coin_values list.

The coin_values list is then sorted in descending order by USDT value and returned by the function.

— — — — — — — — — — —
Uhura: “Captain Kirk, have you heard about the latest cryptocurrency craze?”
Captain Kirk: “No, I haven’t. What is it?”
Uhura: “It’s called Altcoin-ly Logical. But I hear the market’s a bit Spocky right now.”
— — — — — — — — — — —

Print Binance account balances

The function get_accountbalances() does a few things.
It retrieves a list of coins along with their corresponding USDT values, then prints them out in descending order based on the USDT value.
Finally, it shows the total USDT value of your entire portfolio.

def main():

# Call the get_accountbalance function to get the list of coins and their USDT values
coins_usdt_value = get_account_balances()

# Print the list of coins and their USDT values in descending order of USDT value
for coin, usdt_value in coins_usdt_value:
print(f"{coin}: ${usdt_value:.2f}")

# Calculate the grand total USDT value
grand_usdt_total = sum(map(lambda coin_usdt_value: coin_usdt_value[1], coins_usdt_value))
```
# Print the grand total USDT value
print(f"\nGrand Total: ${grand_usdt_total:.2f}")

if __name__ == '__main__':
main()

The main function calls the get_account_balances function to retrieve a list of coins in a Binance account and their corresponding USDT values.

It then prints out the list of coins and their USDT values in descending order of USDT value using a for loop and formatted string.

Next, the code uses the map function to extract the USDT value from each coin in the list and sum function to calculate the total USDT value of all coins.
Finally, it prints out the grand total USDT value using a formatted string.

The if __name__ == '__main__': statement checks if the script is being run as the main program and if so, it calls the main function.

python3 binancewallet.py
output:
BTC : $500.60
LINK : $500.60
ATOM : $500.60
BNB : $500.65

Grand Total: $2002.45

Calculating EURO value

Fortunately, Binance provides a coin pair for EURO-USDT that makes it easy for us to calculate the EURO value of each USD output.

Original USD code

coin_values.append((coin_symbol, coin_usdt_value))

to EURO

coin_values.append((coin_symbol, coin_usdt_value/ticker_prices.get('EURUSDT')))

You can check out the USD and EURO implementation on GitHub.

Conclusion

To retrieve our spot asset balance we walked through everything, from creating a Binance API key to installing the necessary Python packages and writing the code.
When we couldn’t find any USDT trading pairs we found a solution by looking for BTC trading pairs instead.
We even discovered a nifty trick to convert our USD value to EURO value using Binance.
Now you’ll be able to easily track your portfolio, stay informed, and make smart trading moves …

References

Get the code on Github here:

Spot EURO Binance API:
https://github.com/stevebelgium/binance_spot_euro

Spot USD Binance API:
https://github.com/stevebelgium/binance_spot

If you enjoyed this, please follow me on Medium

--

--