同时(异步)工作 - 在自动机器人 w WebSocket 中获取消息接收和下订单/销售



>''' 我想异步工作购买订购,同时通过 websocket 接收不断获取实时价格更新。但是,当我执行下面的代码时,我发现结果如下所示,它是按顺序排列的,而不是同时进行的。 所以,想要做工作函数 - Purchase() 当"如果"被制作时,同时重新启动功能 - Main() 以获得实时价格。你能帮忙提供建议吗?

KRW-BTC 50493000.0 65190905111.72767구매할 때가 되었다구매할 때가 되었다2구매할 때가 되었다3 KRW-ETH 3728000.0 42981406234.81617KRW-ETH 3729000.0 42981416234.80089 KRW-BTC 50532000.0 65191256384.92567


구매할 때가 되었다구매할 때가 되었다2

구매할 때가 되었다

3

'''

async def main(wm):
i=int(0)
while i<1 : 
global code, close, volume
data = wm.get()
code, close, volume=data['code'], data['trade_price'], data['acc_trade_price']
#timestamp=datetime.datetime.fromtimestamp(data['trade_timestamp'] / 1000)
#open = data['opening_price']
#high=data['high_price']
#low=data['low_price']
print(code, close , volume)
if code == 'KRW-BTC' and close >50200000:
await purchase()


async def purchase():
print("구매할 때가 되었다")
await asyncio.sleep(1)
print("구매할 때가 되었다2")
await asyncio.sleep(1)
print("구매할 때가 되었다3")
await asyncio.sleep(1)  

if __name__ == "__main__":
wm = pyupbit.WebSocketManager("ticker", coinlist)
loop = asyncio.new_event_loop()
tasks = loop.create_task(main(wm))
try:
loop.run_until_complete(tasks)
loop.run_forever()        
except KeyboardInterrupt as exc:
logging.info('Quit.')
finally:
print("Closing Loop")
loop.close()

结果是按顺序排列的,因为 while 循环的下一次迭代在await purchase()返回之前无法运行,因此获得更多并发性的最简单方法是将main函数视为"worker",例如

import asyncio
import operator
import pyupbit
async def worker(wm):
while True: 
data = await asyncio.to_thread(wm.get)
code, close, volume = operator.itemgetter('code', 'trade_price', 'acc_trade_price')(data)
if code == 'KRW-BTC' and close > 50200000:
await purchase()
WORKERS = 10  # scale as desired
async def main():
wm = pyupbit.WebSocketManager("ticker", coinlist)
workers = [asyncio.create_task(worker(wm)) for _ in range(WORKERS)]
await asyncio.gather(*workers)
if __name__ == "__main__":
asyncio.run(main())

以上将允许同时等待 10 个purchase(),您可以根据需要增加它

最新更新