我有一段代碼要從binance接收關于當前價格的資料:
。import asyncio
from binance import AsyncClient, BinanceSocketManager
import時間
from datetime import datetime
def analyze(res)。
kline = res['k']
if kline['x'/span>]。#candle is compleated: 蠟燭已完成。
print('{} start_sleeping {}') {}'.format(
datetime.now()。
kline['s']。
datetime.fromtimestamp(kline['t'] / 1000)。)
))
time.sleep(5)
print('{} finish_sleeping {}'/span>.format(datetime.now(), kline['s'/span>])
async def open_binance_stream(symbol)。
client = await AsyncClient.create()
bm = BinanceSocketManager(client)
ts = bm.kline_socket(symbol)
async with ts as tscm:
while True:
res = await tscm.recv()
分析(res)
await client.close_connection()
async def main() 。
t1 = asyncio.create_task(open_binance_stream('ETHBTC')
t2 = asyncio.create_task(open_binance_stream('XRPBTC'/span>)
await asyncio.gather(*[t1, t2])
if __name__ == "__main__"/span>:
asyncio.run(main())
如何使analyze函式被同時呼叫。
Binance在同一時間發送兩個資料流(ETHBTC和XRPBTC)的資訊
但只有在前一個analyze(睡眠)完成后,函式analyze才會被呼叫。
我希望函式analyze被立即獨立呼叫。
uj5u.com熱心網友回復:
你有沒有試著把analyze放在一個執行緒中。我想它會達到你想要的效果。
import asyncio
from binance import AsyncClient, BinanceSocketManager
import時間
from datetime import datetime
from threading import Thread
def analyze(res)。
kline = res['k']
if kline['x'/span>]。#candle is compleated: 蠟燭已完成。
print('{} start_sleeping {}') {}'.format(
datetime.now()。
kline['s']。
datetime.fromtimestamp(kline['t'] / 1000)。)
))
time.sleep(5)
print('{} finish_sleeping {}'/span>.format(datetime.now(), kline['s'/span>])
async def open_binance_stream(symbol)。
client = await AsyncClient.create()
bm = BinanceSocketManager(client)
ts = bm.kline_socket(symbol)
async with ts as tscm:
while True:
res = await tscm.recv()
Thread(target= analyze, args = (res)).start()
await client.close_connection()
async def main() 。
t1 = asyncio.create_task(open_binance_stream('ETHBTC')
t2 = asyncio.create_task(open_binance_stream('XRPBTC'/span>)
await asyncio.gather(*[t1, t2])
if __name__ == "__main__"/span>:
asyncio.run(main())
這應該能達到預期效果。
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/311835.html
標籤:

