DEV Community

Cover image for Trading Bot in C# — Part 8 — Account Balance
Whale's Secret for Whale's Secret

Posted on • Originally published at whalessecret.com

Trading Bot in C# — Part 8 — Account Balance

In the previous blog post, we explained how to retrieve past trades and orders. This article will focus on account asset balances.

Introduction

When you sign up for an account on Binance, KuCoin, or any other exchange, you usually gain access to an asset overview page that displays your asset holdings.

The overview is valuable for tracking your holdings and their overall value.

In this series, we have emphasized that trading requires some discipline and effort. Similarly, your exchange account settings require your attention. Specifically, it's important to take account security measures seriously to avoid needless risk of losing funds. Better safe than sorry!

Account Security

Today, exchanges provide many security features, including:

  • Password strength — Exchanges tell you how strong your password is. A password manager can generate a random password of arbitrary length that you don’t have to remember. Go for it.
  • Withdrawals whitelist — With this feature on, your funds can be withdrawn from your exchange account but only to pre-selected wallet addresses which are owned by you.
  • API key permissions — An API key can be typically assigned multiple permissions like the ability to create an order, cancel an order, etc. There are two important settings. First, do not allow your API keys to withdraw funds from your exchange account unless you plan to use it. Secondly, do allow your API key to be restricted to only your IP addresses, if possible. The following screenshot shows the feature on the KuCoin exchange:

API keys IP address restrictions on KuCoin

  • Two-factor authentication (2FA) — Accessing an account used to be a combination of username and password in the old days. Today, with 2FA, you can sign in in the same way but an additional piece of information is required — a code you can obtain from your phone or hardware token. In a nutshell, your account cannot be accessed without your phone or hardware token. That’s the second factor.

Is 2FA all I need? For the most part, yes. However, no measure is bullet proof and multi-factor authentication is the same. For instance, there is the nefarious SIM swapping attack where fraudsters target wealthy individuals and convince their phone providers to port their phone numbers to their own devices in order to access bank accounts or cryptocurrency exchange accounts by receiving SMS codes required for accessing the accounts. These incidents can result in significant losses. Recently, a sentencing was issued in a case involving Michael Terpin who lost $20 million.

There's no need to worry; the intention is to encourage you to think about your account security. Exchanges have made significant advancements over the last few years, and their security measures are often comparable to those of traditional bank accounts.

This leads us to the main focus of this article: automated monitoring of your assets holdings. This approach can be viewed as an additional security measure or, more commonly, as a means to track the performance of your portfolio.

API

ScriptApiLib allows to retrieve up-to-date account asset balances using the GetLatestExchangeAccountInformation method:

ExchangeAccountInformation info = client.GetLatestExchangeAccountInformation();
Print("Assets:");

foreach ((string symbol, AccountSymbolInformation asi) in info.SymbolsInformation)
{
    Print($"* {symbol}: {asi.AvailableBalance} / {asi.TotalBalance}");
}
Enter fullscreen mode Exit fullscreen mode

The sample output of the snippet may be like this:

[2025-07-15 10:20:35] Assets (available balance / total balance):
[2025-07-15 10:20:35] * BTC: 0.01 / 0.01
[2025-07-15 10:20:35] * LTC: 0.5 / 0.5
[2025-07-15 10:20:35] * USD: 25 / 30
Enter fullscreen mode Exit fullscreen mode

You may notice that only 25 USD s available from the total of 30 USD. That's because 5 USD is, so called, frozen because an order with the value of 5 USD was placed but the order was not yet executed.

While having balance for each asset is useful, many people like to know the total value in a specific currency, such as dollars, to get similar output as KuCoin provides on their asset overview page. Public CoinGecko API can help us compute such value:

decimal totalValue = await ConvertAsync(info);
Print($"Total value is {totalValue} USD.");

/// <summary>
/// Compute value of assets in USD using CoinGecko's simple price API.
/// </summary>
/// <seealso href="https://docs.coingecko.com/v3.0.1/reference/simple-price"/>
/// <example>https://api.coingecko.com/api/v3/simple/price?symbols=btc,ltc&vs_currencies=usd</example>
static async Task<decimal> ConvertAsync(ExchangeAccountInformation info)
{
  string symbols = string.Join(',', info.SymbolsInformation.Keys);

  using HttpClient httpClient = new();
  using HttpResponseMessage response = await httpClient
    .GetAsync($"https://api.coingecko.com/api/v3/simple/price?symbols={symbols}&vs_currencies=usd");
  var data = await response.Content.ReadFromJsonAsync<Dictionary<string, Dictionary<string, decimal>>>();
  if (data is null)
  {
    Print("Failed to retrieve exchange-rate data from CoinGecko.");
    return -1;
  }

  decimal usdValue = 0;

  foreach (string coin in info.SymbolsInformation.Keys)
  {
    if (data.TryGetValue(coin.ToLowerInvariant(), out var dict) && dict.TryGetValue("usd", out decimal rate))
    {
        usdValue += rate * info.SymbolsInformation[coin].TotalBalance;
    }
    else Print($"No USD value found for '{coin}' asset.");
  }

  return usdValue;
}
Enter fullscreen mode Exit fullscreen mode

With this method, the output of our sample now contains one more line:

[2025-07-15 10:20:35] Total value is 1247 USD.
Enter fullscreen mode Exit fullscreen mode

Depending on your needs, account monitoring can be strictly time-based (check account every N hours) or more detailed, tracking every single change. GetNewerExchangeAccountInformationAsync comes to the rescue:

int i = 0;
while (true)
{
    i++;
    ExchangeAccountInformation info = await client.GetNewerExchangeAccountInformationAsync();
    Print($"Report #{i} (available balance / total balance):");

    foreach ((string symbol, AccountSymbolInformation asi) in info.SymbolsInformation)
    {
        Print($"* {symbol}: {asi.AvailableBalance} / {asi.TotalBalance}");
    }
}
Enter fullscreen mode Exit fullscreen mode

Now it's easy to demonstrate the concept of a frozen balance. You can just place an order and observe the outcome.

[2025-07-17 10:00:00] Connected to KuCoin.
[2025-07-17 10:00:00] Report #1 (available balance / total balance):
[2025-07-17 10:00:00] * BTC: 0.001 / 0.001
[2025-07-17 10:00:00] * USDT: 50 / 50

// At this point, a new order to buy 5 USDT worth of bitcoin was placed.

[2025-07-17 10:00:15] Report #2 (available balance / total balance):
[2025-07-17 10:00:15] * BTC: 0.001 / 0.001
[2025-07-17 10:00:15] * USDT: 45 / 50
Enter fullscreen mode Exit fullscreen mode

Conclusion

In this blog post, we presented API for retrieving and monitoring of account asset balances in ScriptApiLib, allowing users to understand how their portfolios change value over time. Next time, we will discuss budgeting for your trading strategies.

Disclaimer: The information provided in this blog post should not be considered financial advice. Always conduct your own research and consider your personal circumstances before acting on any financial information.

Top comments (0)