You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python格式化币安API余额输出 实现列对齐及终端加粗效果

币安资产查询脚本格式化输出实现方案

功能需求

  • 调用币安API遍历所有币种,仅返回余额大于0的资产
  • 控制台输出列对齐,每列最长值后固定保留2个空格
  • 支持Windows命令行下文字加粗等格式化效果,可直接通过python main.py运行

优化后完整代码

import time
time.sleep(1)
from datetime import datetime
current_time = datetime.now().strftime("%H:%M:%S")
print(f"\n [{current_time}] Using PYPY3 \n")
print(f" [{current_time}] Importing modules... ")
import os
from binance.client import Client
from forex_python.converter import CurrencyRates
current_time = datetime.now().strftime("%H:%M:%S")
print(f" [{current_time}] Imported the modules!")
# 替换为自己的币安API密钥
api_key = <api_key>
api_secret = <api_password>
client = Client(api_key, api_secret)
def get_balance():
    assets_btc = []
    assets_value = []
    assets = []
    sum_btc = 0.0
    current_btc_price_USD = client.get_symbol_ticker(symbol="BTCUSDT")["price"]
    balances = client.get_account()
    for _balance in balances["balances"]:
        asset = _balance["asset"]
        if _balance["asset"] not in Xcrypto:
            if float(_balance["free"]) != 0.0 or float(_balance["locked"]) != 0.0:
                try:
                    btc_quantity = float(_balance["free"]) + float(_balance["locked"])
                    if asset == "BTC":
                        assets.append(_balance["asset"])
                        sum_btc += btc_quantity
                        assets_value.append(btc_quantity)
                        assets_btc.append(btc_quantity * float(current_btc_price_USD))
                    else:
                        assets.append(_balance["asset"])
                        _price = client.get_symbol_ticker(symbol=asset + "BTC")
                        sum_btc += btc_quantity * float(_price["price"])
                        assets_value.append(btc_quantity)
                        assets_btc.append(btc_quantity * float(_price["price"]) * float(current_btc_price_USD))
                except Exception:
                    pass
    own_usd = sum_btc * float(current_btc_price_USD)
    return float("%.2f" % own_usd), assets, assets_value, assets_btc
if __name__ == "__main__":
    # 开启Windows控制台ANSI转义码支持,用于实现加粗等格式化效果
    os.system('')
    Xcrypto = ["EGLD"]
    current_time = datetime.now().strftime("%H:%M:%S")
    print(f"\n [{current_time}] Starting... \n")
    print(f" [{current_time}] Forbiden cryptos: {Xcrypto} \n")
    current_time = datetime.now().strftime("%H:%M:%S")
    print(f" [{current_time}] Connecting to binance API...")
    get_balance()
    current_time = datetime.now().strftime("%H:%M:%S")
    print(f" [{current_time}] Connected to the binance API! \n")
    current_time = datetime.now().strftime("%H:%M:%S")
    print(f" [{current_time}] Connecting to forex API...")
    USD_RON = float(CurrencyRates().get_rate('USD', 'RON'))
    current_time = datetime.now().strftime("%H:%M:%S")
    print(f" [{current_time}] Connected to the forex API! \n")
    print(f" [{current_time}] Conversion: USD to RON: {'%.2f' % USD_RON} \n")
    current_time = datetime.now().strftime("%H:%M:%S")
    print(f" [{current_time}] Console will be cleared, updating the price every 2 seconds!")
    while 1:
        print("\n")
        Binance_USD, assets, assets_value, assets_btc = get_balance()
        Binance_RON = float("%.2f" % (Binance_USD * USD_RON))
        current_time = datetime.now().strftime("%H:%M:%S")
        os.system('cls' if os.name == 'nt' else 'clear')
        # 计算各列最大宽度,每列末尾预留2个空格
        max_asset_len = max(len(a) for a in assets) + 2
        max_value_len = max(len(f"{v:.2f}") for v in assets_value) + 2
        max_btc_len = max(len(f"{(b * USD_RON):.2f}") for b in assets_btc) + 2
        for asset, asset_value, asset_btc in zip(assets, assets_value, assets_btc):
            # \033[1m 为加粗起始标记,\033[0m 为格式重置标记,资产名称默认加粗
            print(f" [{current_time}] \033[1m{asset:<{max_asset_len}}\033[0m Balance: {f'{asset_value:.2f}':<{max_value_len}} Value: {f'{(float(asset_btc) * USD_RON):.2f}':<{max_btc_len}} RON")
        print(f"\n [{current_time}] Total balance:", str(Binance_RON) + " RON\n")
        # 控制刷新频率避免API调用超限
        time.sleep(2)

核心修改说明

  • 新增os.system('')开启Windows控制台ANSI转义码支持,可直接识别格式化控制符
  • 每次获取资产数据后,先计算资产名、余额、价值三列的最大长度,每列末尾预留2个空格作为间隔
  • 通过f-string的左对齐语法<实现列对齐,用\033[1m和\033[0m包裹需要加粗的内容,示例中默认资产名加粗
  • 新增time.sleep(2)控制刷新频率,避免API调用触发频次限制

输出效果示例

[15:11:26] BTC  Balance: x.xx    Value: xxxx.xx  RON
 [15:11:26] USDT Balance: xxx.xx  Value: xx.xx    RON
 [15:11:26] TRX  Balance: xx.xx   Value: xx.xx    RON
 [15:11:26] XRP  Balance: xxx.xx  Value: xxx.xx   RON
 [15:11:26] XLM  Balance: x.xx    Value: x.xxx    RON

内容的提问来源于stack exchange,提问作者R0Best

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.01 07:54:02