Python Bitcoin Balance
Get Bitcoin Balance with Python
This section demonstrates how to retrieve your Bitcoin balance using a Python script. It leverages the Bitcoin Core RPC interface to fetch balance information.
Python Script for BTC Balance
The following Python code snippet utilizes the requests library to interact with the Bitcoin RPC daemon. Ensure you have your RPC credentials configured in a .env file for security.
import os
import requests
import json
from dotenv import load_dotenv
load_dotenv('.env')
RPC_USERNAME = os.getenv('RPC_USERNAME')
RPC_PASSWORD = os.getenv('RPC_PASSWORD')
def get_btc_balance():
headers = 'content-type: text/plain'
request_payload = {"jsonrpc": "1.0", "id":"requests", "method": "getbalance", "params": ["*", 6]}
response = requests.post('http://127.0.0.1:8332/', json=request_payload, auth=(RPC_USERNAME, RPC_PASSWORD))
return response.json()
current_balance = get_btc_balance()['result']
print('[DEBUG] current balance is: {}'.format(current_balance))
Explanation of the Code
The script defines a function get_btc_balance that constructs a JSON-RPC request to the Bitcoin daemon. It specifies the getbalance method and includes parameters for the account (* for all accounts) and the number of confirmations (6). The response, containing the current Bitcoin balance, is then printed.
Prerequisites
- Python installed on your system.
- Bitcoin Core running and accessible via RPC.
- A
.envfile withRPC_USERNAMEandRPC_PASSWORD. - The
requestsandpython-dotenvlibraries installed (pip install requests python-dotenv).