如何从Python调用币安API的返回值提取指定字段并按涨跌幅降序排序
你调用client.get_ticker()已经获取到了所有币种的24小时行情数据,只需要新增排序、字段提取两步即可实现需求,完整修改后的代码如下:
from binance.client import Client class BinanceConnection: def __init__(self, file): self.connect(file) """ 创建币安客户端 """ def connect(self, file): lines = [line.rstrip('\n') for line in open(file)] key = lines[0] secret = lines[1] self.client = Client(key, secret) if __name__ == '__main__': # 替换为你自己的密钥文件路径 filename = "你的密钥存储文件路径.txt" connection = BinanceConnection(filename) prices = connection.client.get_ticker() # 核心逻辑:按涨跌幅降序排序,需先将字符串格式的涨跌幅转为浮点型再比较 sorted_prices = sorted(prices, key=lambda x: float(x['priceChangePercent']), reverse=True) # 只打印你需要的两个字段 for item in sorted_prices: print(f"币种:{item['symbol']},涨跌幅:{item['priceChangePercent']}%")
如果仅需要展示涨幅前N名的币种,遍历的时候加数量限制即可,比如展示涨幅前20的币种可以写成:
for item in sorted_prices[:20]: print(f"币种:{item['symbol']},涨跌幅:{item['priceChangePercent']}%")
注:你原本提供的代码存在缩进错误,上述代码已经修正了类成员方法、主逻辑的缩进问题,替换为自己的密钥文件路径后即可直接运行。
内容的提问来源于stack exchange,提问作者Mehmet Reşat Demir
相关产品推荐
相关产品推荐

