继续浏览精彩内容
慕课网APP
程序员的梦工厂
打开
继续
感谢您的支持,我会继续努力的
赞赏金额会直接到老师账户
将二维码发送给自己后长按识别
微信支付
支付宝支付

教程 - 利用数字货币行情API查询加密货币的实时价格

船长610
关注TA
已关注
手记 17
粉丝 1
获赞 1
import requests

api_url = 'https://data.infoway.io/stock/batch_kline/1/10/BTC_USDT'

# Token申请:www.infoway.io
# 设置请求头
headers = {
    'User-Agent': 'Mozilla/5.0',
    'Accept': 'application/json',
    'apiKey': 'yourApikey'
}

# 发送GET请求
response = requests.get(api_url, headers=headers)

# 输出结果
print(f"HTTP code: {response.status_code}")
print(f"message: {response.text}")

使用websocket订阅BTC实时行情报价:

import asyncio
import json
import websockets

WS_URL = "wss://data.infoway.io/ws?business=crypto&apikey=yourApikey"

async def connect_and_receive():
    async with websockets.connect(WS_URL) as websocket:
        # 发送初始消息
        init_message = {
            "code": 10000,
            "trace": "01213e9d-90a0-426e-a380-ebed633cba7a",
            "data": {"codes": "BTCUSDT"}
        }
        await websocket.send(json.dumps(init_message))

        # 设置ping任务
        async def send_ping():
            while True:
                await asyncio.sleep(30)
                ping_message = {
                    "code": 10010,
                    "trace": "01213e9d-90a0-426e-a380-ebed633cba7a"
                }
                await websocket.send(json.dumps(ping_message))

        # 启动ping任务协程
        ping_task = asyncio.create_task(send_ping())
        
        try:
            # 持续接收消息
            while True:
                message = await websocket.recv()
                print(f"Message received: {message}")
        except websockets.exceptions.ConnectionClosedOK:
            print("Connection closed normally")
        finally:
            # 取消ping任务
            ping_task.cancel()

# 运行主函数
asyncio.run(connect_and_receive())
打开App,阅读手记
0人推荐
发表评论
随时随地看视频慕课网APP