How to Retrieve Any Digital Asset Wallet Balance Using Python

ยท

In the world of digital assets, monitoring your holdings is crucial. While exchanges offer APIs for balance tracking, what about assets stored in personal wallets? This guide will show you how to use Python to retrieve balances from any digital asset wallet by interacting with blockchain explorers.

Blockchain explorers are online tools that allow you to view transactions, addresses, and balances on various blockchains. Examples include btc.com for Bitcoin, etherscan.io for Ethereum, mintscan.io for ATOM, and scan.chainx.org for PCX. These explorers often provide APIs or can be scraped for data, enabling programmatic balance queries.

Understanding Blockchain Explorer APIs

Blockchain explorers can be categorized into two types: those with official APIs and those without. Well-maintained explorers like btc.com and etherscan.io offer documented APIs, while others require web scraping techniques to extract data.

Retrieving Balances from Explorers with Official APIs

Bitcoin Blockchain Explorer: btc.com

btc.com provides a comprehensive API documented at https://btc.com/api-do. To retrieve a Bitcoin balance, use the following endpoint format:

https://chain.api.btc.com/v3/address/[Your_Bitcoin_Address]

Replace [Your_Bitcoin_Address] with your actual Bitcoin wallet address. The response will include balance information that needs to be converted from satoshis to BTC (divide by 100,000,000).

Here's a practical implementation to monitor your Bitcoin balance:

import requests
import json
import datetime
import time

def send_dingding_msg1(content, robot_id='your_dingtalk_robot_id'):
    try:
        msg = {
            "msgtype": "text",
            "text": {"content": content + '\n' + datetime.datetime.now().strftime("%m-%d %H:%M:%S")}
        }
        headers = {"Content-Type": "application/json;charset=utf-8"}
        url = 'https://oapi.dingtalk.com/robot/send?access_token=' + robot_id
        body = json.dumps(msg)
        status = requests.post(url, data=body, headers=headers)
        if status.status_code == 200:
            return status.json()
        return status
    except Exception as err:
        print('DingTalk message failed to send', err)

# Monitor Bitcoin balance
while True:
    try:
        address = 'your_bitcoin_wallet_address'
        url = f'https://chain.api.btc.com/v3/address/{address}'
        response = requests.get(url)
        
        if response.text:
            BTC = float(response.json()['data']['balance']) / 100000000
            print('BTC Balance:', BTC)
            
            if BTC > 1:
                content = 'BTC wallet deposit received'
                send_msg1 = send_dingding_msg1(content)
                print(send_msg1)
                break
        time.sleep(5)
    except Exception as order_err:
        print("Query error, retrying", order_err)
        time.sleep(3)

Ethereum Blockchain Explorer: etherscan.io

Etherscan requires an API key, which you can obtain by registering at https://etherscan.io/register. The balance endpoint format is:

https://api.etherscan.io/api?module=account&action=balance&address=[Your_Address]&tag=latest&apikey=[Your_API_Key]

For ERC-20 tokens, use the token balance endpoint:

https://api.etherscan.io/api?module=account&action=tokenbalance&contractaddress=[Token_Contract_Address]&address=[Your_Address]&tag=latest&apikey=[Your_API_Key]

To find a token's contract address, search for the token on Etherscan and copy its contract address from the token page.

Implementation example for Ethereum and ERC-20 tokens:

while True:
    try:
        apikey = 'your_etherscan_api_key'
        address = 'your_ethereum_address'
        
        # ETH balance check
        url1 = f'https://api.etherscan.io/api?module=account&action=balance&address={address}&tag=latest&apikey={apikey}'
        
        # ERC-20 token balance check (using OMG as example)
        contractaddress = '0xd26114cd6EE289AccF82350c8d8487fedB8A0C07'
        url2 = f'https://api.etherscan.io/api?module=account&action=tokenbalance&contractaddress={contractaddress}&address={address}&tag=latest&apikey={apikey}'
        
        response1 = requests.get(url1)
        response2 = requests.get(url2)
        
        eth_balance = float(response1.json()['result']) / 10**18
        token_balance = float(response2.json()['result']) / 10**18
        
        print('ETH Balance:', eth_balance)
        print('OMG Balance:', token_balance)
        
        if eth_balance > 10:
            content = 'ETH wallet deposit received'
            send_msg1 = send_dingding_msg1(content)
            print(send_msg1)
            break
            
        time.sleep(5)
    except Exception as order_err:
        print("Query error, retrying", order_err)
        time.sleep(3)

Retrieving Balances from Explorers Without Official APIs

For blockchain explorers without official APIs, we need to use web scraping techniques. Let's use the ChainX PCX token as an example.

PCX Blockchain Explorer: scan.chainx.org

To extract balance information from explorers without APIs:

  1. Open the explorer in Chrome and press F12 to open Developer Tools
  2. Go to the Network tab and select XHR
  3. Refresh the page and look for balance-related requests
  4. Examine the request headers and response format

Implementation for PCX balance monitoring:

while True:
    try:
        url = "https://api.chainx.org.cn/account/your_pcx_wallet_address/balance"
        headers = {
            "Content-type": "application/json; charset=utf-8",
            'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/76.0.3809.100 Safari/537.36'
        }
        
        response = requests.get(url, headers=headers)
        balance = response.json()
        
        # Adjust the index based on where PCX appears in the response
        PCX = balance[1]['Free'] / 100000000
        print('PCX Balance:', PCX)
        
        if PCX > 30:
            content = f'PCX purchase received, balance: {str(PCX)}'
            send_msg1 = send_dingding_msg1(content)
            print(send_msg1)
            break
            
        time.sleep(3)
    except Exception as order_err:
        print("Query error, retrying", order_err)
        time.sleep(3)

This approach can be adapted to any blockchain explorer by examining the network requests and response formats.

Advanced Implementation Tips

  1. Error Handling: Implement robust error handling for network issues and API rate limits
  2. Multiple Assets: Create a configuration system to monitor multiple wallets and assets
  3. Data Persistence: Store balance history in a database for trend analysis
  4. Alert Customization: Create different alert triggers for various scenarios

๐Ÿ‘‰ Explore advanced monitoring techniques

Frequently Asked Questions

What is a blockchain explorer?
A blockchain explorer is a web application that allows users to browse information about blocks, transactions, addresses, and balances on a blockchain network. It serves as a search engine for blockchain data.

Do I need API keys for all blockchain explorers?
No, only some explorers require API keys. Public explorers like btc.com don't require authentication, while others like etherscan.io require free registration for API access.

How often should I check wallet balances?
The frequency depends on your needs. For transaction monitoring, checking every 5-30 seconds is reasonable. For general balance tracking, less frequent checks (every few hours) are sufficient.

What are the rate limits for these APIs?
Rate limits vary by service. Etherscan allows 5 requests/second for free API keys, while other explorers may have different limits. Always check the documentation for specific limits.

Can I use this method for any cryptocurrency?
Yes, this approach works for any digital asset with a blockchain explorer. The implementation may vary slightly depending on the explorer's structure and data format.

What alternatives exist to blockchain explorers for balance checking?
You can run your own blockchain node or use specialized services that aggregate multiple blockchain APIs. However, using explorers is often the most straightforward approach for individual developers.

Conclusion

Monitoring digital asset wallet balances using Python and blockchain explorers is a powerful approach for tracking your cryptocurrency holdings. Whether through official APIs or web scraping techniques, you can create automated systems to monitor balances, receive alerts, and make informed decisions about your digital assets.

Remember to always respect API rate limits, handle errors gracefully, and ensure the security of your API keys and wallet information. With these techniques, you can build comprehensive monitoring solutions for any digital asset in your portfolio.

๐Ÿ‘‰ Discover more blockchain development strategies