比特币以太坊行情 API 接入 主流数字货币实时数据教程

比特币、以太坊作为数字货币市场的核心标的,是量化交易、行情监控、自动化工具开发的首选品种。全天候不间断的交易场景,对行情接口的实时性与连接稳定性提出了更高要求。

本文基于 PulseData 脉动行情 API,分享 BTC、ETH 的完整接入方案,涵盖 HTTP 查询与 WebSocket 实时推送,所有代码经过实测,可直接部署使用。

一、基础信息

接口统一地址:

  • 实时查询:http://39.107.99.235:1008/getQuote.php
  • 实时推送:ws://39.107.99.235/ws
  • K 线接口:http://39.107.99.235:1008/redis.php

主流币种代码:

  • 比特币:btcusdt
  • 以太坊:ethusdt

二、HTTP 快速查询行情

适合临时查询、定时轮询类业务,一次请求可同时获取多个币种的完整行情数据。

访问链接示例

plaintext

http://39.107.99.235:1008/getQuote.php?code=btcusdt,ethusdt

Python 代码实现

python

运行

import requests

api = "http://39.107.99.235:1008/getQuote.php"
head = {"Accept-Encoding": "gzip"}
param = {"code": "btcusdt,ethusdt"}

ret = requests.get(api, headers=head, params=param, timeout=10)
result = ret.json()

if result["code"] == 200:
    for item in result["data"]["body"]:
        print(f"交易品种:{item['StockCode']}")
        print(f"现价:{item['Price']} 日内最高:{item['High']} 日内最低:{item['Low']}")
        print(f"涨跌幅度:{item['DiffRate']}%")
        print("------------------------")

三、WebSocket 高频实时推送

数字货币价格波动频繁,长连接推送可以第一时间捕捉价格变化。连接建立后按规则发送心跳包与订阅指令,即可持续接收行情。

核心代码

python

运行

import websocket
import json
import time
import threading

ws_url = "ws://39.107.99.235/ws"
sub_code = "btcusdt,ethusdt"

def keep_alive(ws):
    while True:
        t = int(time.time())
        ws.send(json.dumps({"ping": t}))
        time.sleep(10)

def on_open(ws):
    print("连接成功,开始订阅数字货币行情")
    ws.send(json.dumps({"Key": sub_code}))
    threading.Thread(target=keep_alive, args=(ws,), daemon=True).start()

def on_message(ws, msg):
    data = json.loads(msg)
    if "body" in data:
        print(f"【实时更新】{data['body']['StockCode']} 价格:{data['body']['Price']}")

def on_close(ws, code, msg):
    print("连接断开,重新启动...")
    time.sleep(3)
    start_conn()

def start_conn():
    ws_app = websocket.WebSocketApp(
        ws_url,
        on_open=on_open,
        on_message=on_message,
        on_close=on_close
    )
    ws_app.run_forever()

if __name__ == "__main__":
    start_conn()

四、历史 K 线获取

做策略回测时,可调用 K 线接口获取不同周期历史数据。示例(以太坊 5 分钟 K 线):

plaintext

http://39.107.99.235:1008/redis.php?code=ethusdt&time=5m&rows=200

整套接口覆盖主流数字货币全维度数据,盘口、成交、分时 K 线一应俱全,适配币圈各类量化与行情开发场景。

0
0
0
0
评论
未登录
暂无评论