crypto_quant/test_binance.py

39 lines
1.5 KiB
Python
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

import requests
import json
from datetime import datetime
# API 端点:币安现货 K 线数据
base_url = "https://api.binance.com"
endpoint = "/api/v3/klines"
# 参数设置
symbol = "ETHUSDT" # 交易对ETH-USDT
interval = "5m" # 时间间隔5 分钟
limit = 100 # 获取最近 100 条 K 线(可根据需要调整,最大 1000
params = {
"symbol": symbol,
"interval": interval,
"limit": limit
}
# 发送 GET 请求
response = requests.get(base_url + endpoint, params=params)
# 检查响应状态
if response.status_code == 200:
data = response.json()
# 输出最近 5 条 K 线数据作为示例(每条数据格式:[开盘时间, 开盘价, 最高价, 最低价, 收盘价, 成交量, 收盘时间, 报价成交量, 成交笔数, 主动买入成交量, 主动买入报价成交量, 忽略]
print("最近 5 条 5 分钟 K 线数据 (ETH-USDT):")
print(json.dumps(data[-5:], indent=4, ensure_ascii=False))
# 可选:转换为更易读的格式
print("\n转换为易读格式(时间为 UTC")
for kline in data[-5:]:
open_time = datetime.fromtimestamp(kline[0] / 1000).strftime('%Y-%m-%d %H:%M:%S')
close_time = datetime.fromtimestamp(kline[6] / 1000).strftime('%Y-%m-%d %H:%M:%S')
print(f"时间: {open_time} - {close_time}, "
f"开: {kline[1]}, 高: {kline[2]}, 低: {kline[3]}, 收: {kline[4]}, 量: {kline[5]}")
else:
print(f"请求失败,状态码: {response.status_code}, 错误信息: {response.text}")