0%

python | websocket 对接

参考资料

简单的例子

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
import asyncio

import aiohttp


async def ws():
session = aiohttp.ClientSession()
async with session.ws_connect('wss://fstream.binance.com/ws', proxy="http://127.0.0.1:1087") as ws:
await ws.send_str('{"method": "SUBSCRIBE","params":["btcusdt@aggTrade","btcusdt@depth"],"id": 1}')
async for msg in ws:
if msg.type == aiohttp.WSMsgType.TEXT:
print(msg)

if __name__ == '__main__':
asyncio.run(ws())
print(123)

上面是一个简单的例子,但是,这个例子在 async for msg in ws 陷入了死循环。

优化

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
import asyncio

import aiohttp


async def ws():
session = aiohttp.ClientSession()
async with session.ws_connect('wss://fstream.binance.com/ws', proxy="http://127.0.0.1:1087") as ws:
await ws.send_str('{"method": "SUBSCRIBE","params":["btcusdt@aggTrade","btcusdt@depth"],"id": 1}')
async for msg in ws:
if msg.type == aiohttp.WSMsgType.TEXT:
print(msg)

if __name__ == '__main__':
loop = asyncio.get_event_loop()
loop.create_task(ws())
print(123)
loop.run_forever()

对接两个 ws

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
import asyncio

import aiohttp


async def ws_binance():
session = aiohttp.ClientSession()
async with session.ws_connect('wss://fstream.binance.com/ws', proxy="http://127.0.0.1:1087") as ws:
await ws.send_str('{"method": "SUBSCRIBE","params":["btcusdt@aggTrade","btcusdt@depth"],"id": 1}')
async for msg in ws:
if msg.type == aiohttp.WSMsgType.TEXT:
print(msg)


async def ws_mexc():
session = aiohttp.ClientSession()
async with session.ws_connect('wss://wbs.mexc.com/ws', proxy="http://127.0.0.1:1087") as ws:
await ws.send_str('{ "method":"SUBSCRIPTION", "params":["spot@public.deals.v3.api@BTCUSDT"] }')
async for msg in ws:
if msg.type == aiohttp.WSMsgType.TEXT:
print(msg)


if __name__ == '__main__':
loop = asyncio.get_event_loop()
loop.create_task(ws_binance())
loop.create_task(ws_mexc())
loop.run_forever()

ps: 2023-12-25

上面的场景运用的不是很充分,应参考

请我喝杯咖啡吧~