Track Ethereum Transactions and Balance Using Python

·

Tracking cryptocurrency transactions has become increasingly important for developers, investors, and blockchain enthusiasts. With Ethereum being one of the most widely used blockchains, understanding how to programmatically monitor wallet activity is a valuable skill. In this guide, you'll learn how to track Ethereum transactions, retrieve wallet balances, and visualize historical data using Python and the Etherscan API.

Whether you're auditing your own wallet, building a financial dashboard, or analyzing on-chain behavior, this tutorial provides a practical foundation. While some familiarity with Python is recommended, all code examples are clearly explained for intermediate developers.


Understanding the Etherscan API

The Etherscan API is a powerful tool that allows developers to access real-time and historical Ethereum blockchain data without running a full node. It provides endpoints for retrieving account balances, transaction histories, smart contract details, and more.

To get started:

  1. Visit etherscan.io and sign up for a free API key.
  2. Navigate to the "My API Keys" section to generate your key.
  3. Store the key securely—never expose it in public repositories.

Once you have your API key, you can make HTTP requests to Etherscan’s endpoints using Python libraries like requests.

👉 Discover how blockchain analytics can enhance your development workflow


Retrieving Ethereum Wallet Balance

The first step in tracking Ethereum activity is fetching the current balance of a wallet address. Etherscan provides a simple endpoint for this:

https://api.etherscan.io/api?module=account&action=balance&address={your_address}&tag=latest&apikey={your_api_key}

Using Python, we can wrap this into a reusable function:

import requests

def get_balance(address, api_key):
    url = f"https://api.etherscan.io/api?module=account&action=balance&address={address}&tag=latest&apikey={api_key}"
    response = requests.get(url)
    data = response.json()
    if data['status'] == '1':
        # Balance is returned in wei; convert to ETH
        return float(data['result']) / 10**18
    else:
        raise Exception(f"Error: {data['message']}")

This function returns the balance in Ether (ETH) by converting from wei, Ethereum’s smallest unit.

You can now call this function with any valid Ethereum address:

address = "0xYourEthereumAddressHere"
api_key = "YourApiKeyToken"
print(f"Balance: {get_balance(address, api_key):.4f} ETH")

Fetching Ethereum Transaction History

Beyond balance checks, monitoring transaction history helps track inflows, outflows, and overall wallet activity.

Etherscan offers an endpoint to retrieve both internal and external transactions:

https://api.etherscan.io/api?module=account&action=txlist&address={your_address}&startblock=0&endblock=99999999&sort=asc&apikey={your_api_key}

Here’s how to fetch and parse transaction data:

def get_transactions(address, api_key):
    url = f"https://api.etherscan.io/api?module=account&action=txlist&address={address}&startblock=0&endblock=99999999&sort=asc&apikey={api_key}"
    response = requests.get(url)
    data = response.json()
    if data['status'] == '1':
        return data['result']
    else:
        raise Exception(f"Error: {data['message']}")

Each transaction includes fields such as:

You can enrich this data further by decoding timestamps or filtering incoming vs outgoing transactions.


Visualizing Wallet Activity Over Time

To better understand financial trends, visualizing balance changes over time adds powerful context. We’ll use Matplotlib to create a time-series graph.

First, calculate the running balance at each transaction point:

import matplotlib.pyplot as plt
from datetime import datetime

def plot_balance_history(address, api_key):
    txs = get_transactions(address, api_key)
    txs.sort(key=lambda x: int(x['timeStamp']))
    
    balance = 0
    balances = []
    times = []

    for tx in txs:
        value_eth = float(tx['value']) / 10**18
        # Assume outgoing if from our address
        if tx['from'].lower() == address.lower():
            balance -= value_eth
        # Incoming if to our address
        if tx['to'].lower() == address.lower():
            balance += value_eth

        timestamp = datetime.fromtimestamp(int(tx['timeStamp']))
        times.append(timestamp)
        balances.append(balance)

    # Plot
    plt.figure(figsize=(12, 6))
    plt.plot(times, balances, label='Balance (ETH)')
    plt.title('Ethereum Wallet Balance Over Time')
    plt.xlabel('Date')
    plt.ylabel('Balance (ETH)')
    plt.legend()
    plt.grid(True)
    plt.tight_layout()
    plt.show()

This generates a clear visual representation of how your wallet balance evolves—helpful for spotting patterns or verifying expected payments.

👉 Learn how real-time data access improves blockchain monitoring


Core Keywords and SEO Optimization

This guide targets developers interested in blockchain integration and financial transparency. Key SEO keywords naturally integrated throughout include:

These terms align with common search queries related to cryptocurrency monitoring and development tools.


Frequently Asked Questions (FAQ)

How do I get an Etherscan API key?

Visit etherscan.io, create a free account, go to "My API Keys," and generate a new key. No credit card is required for basic usage.

Can I track multiple wallets at once?

Yes! You can loop through a list of addresses using the same functions. Just ensure you stay within Etherscan’s rate limits (5 requests per second for free keys).

Is it safe to use my API key in local scripts?

Yes, as long as you keep it private. Never commit it to public GitHub repositories. Use environment variables or config files excluded from version control.

Why does the balance appear in wei instead of ETH?

Ethereum natively stores values in wei (1 ETH = 10¹⁸ wei). Always divide by 10**18 when displaying user-facing amounts.

Can I use this method for other blockchains?

Similar APIs exist for BNB Chain, Polygon, and others. Some even offer unified interfaces. However, each requires its own setup and endpoints.

What if a transaction is pending or failed?

The standard txlist endpoint only returns confirmed transactions. For pending ones, use the pending module (if supported). Failed transactions may still appear but include a txreceipt_status of 0.


Enhancing Functionality and Accuracy

For production-grade applications:

You can also integrate alerts or export data to CSV/Excel for reporting purposes.

👉 Explore advanced tools for blockchain developers


Final Thoughts

Programmatically tracking Ethereum transactions and balances using Python opens up numerous possibilities—from personal finance dashboards to enterprise-grade audit systems. By leveraging the Etherscan API, you gain instant access to rich blockchain data without infrastructure overhead.

With clear code structure, proper error handling, and visualization tools, you can build robust solutions that provide real insights into wallet behavior.

As blockchain adoption grows, mastering these skills positions you at the forefront of decentralized application development. Start small, iterate often, and expand functionality based on your needs.

Remember: always respect rate limits, secure your API keys, and validate input addresses to avoid errors. Happy coding!