Python实现ws订阅服务

一、Python实现ws订阅服务

# 使用websocket订阅欧易公共频道中的 行情频道,以下是已知信息,写出Python代码
# 地址:"wss://wspap.okx.com:8443/ws/v5/public?brokerId=9999"
# 请求示例:
# {
#     "op": "subscribe",
#     "args": [{
#         "channel": "tickers",
#         "instId": "LTC-USD-200327"
#     }]
# }
from datetime import datetime, timedelta
import asyncio
import json
import websockets


async def subscribe_to_okx_channel():
    uri="wss://wspap.okx.com:8443/ws/v5/business?brokerId=9999"
    async with websockets.connect(uri) as websocket:
        # 订阅请求示例
        subscription_data = {
            "op": "subscribe",
            "args": [{
                "channel": "candle15m",
                "instId": "BTC-USDT"
            }]
        }

        # 向WebSocket服务器发送订阅请求
        await websocket.send(json.dumps(subscription_data))
        print(f"已向 {uri} candle15m 发送订阅请求")

        # 接收并处理服务器返回的数据
        while True:
            response = await websocket.recv()
            print(f"收到的数据: {response}")
            response = json.loads(response)
            data = response.get('data')
            if data:
                time_str = data[0][0]
                print('\033[32m' + '=============%s==============' % str(
                    datetime.fromtimestamp(int(time_str) / 1000)) + '\033[0m')


# 运行异步函数
asyncio.get_event_loop().run_until_complete(subscribe_to_okx_channel())

 

数据解析:

       订阅的URL:"wss://wspap.okx.com:8443/ws/v5/public?brokerId=9999"

       订阅参数:

 

       {
            "op": "subscribe",
            "args": [{
                "channel": "candle15m",
                "instId": "BTC-USDT"
            }]
        }

 

  

 

 

上面代码需要在访问外网的情况下才能运行  
posted @ 2024-03-14 15:09  何双新  阅读(307)  评论(0编辑  收藏  举报