首页 > 解决方案 > 在 websocket 消息事件循环中返回 asyncio.create_task() 的值

问题描述

我有一个 python asyncio 问题,在连续的 websocket 异步流输出中处理异步 REST api 调用方法的输出。我在下面写了一些伪代码来解释我的问题。

我的 websocket 每 1-5 毫秒从交换中非常频繁地推出消息,但我不知道如何wallet_balance正确分配新值。

在下面的代码中启用await wallet_balance将阻止我的代码 250 毫秒,而响应需要时间才能返回。如果不使用await wallet_balancewallet_balancenow 将成为协程对象而不是浮点数。 wallet_balance一些消息将如下所示: 一旦获得 API 响应<Task pending name='Task-12' coro=<get_wallet_balances() running at....>,最终将变为。<Task finished name='Task-12' coro=<get_wallet_balances() done>

我该如何处理wallet_balance仅在获得响应时才分配/返回值的异步问题?(显然没有阻止 websocket 消息的流式传输)

相关文章: https ://sammchardy.github.io/async-binance-basics/

async def get_wallet_balance():
     wallet_balance = await async_exchange.get_balances()
     return wallet_balance


async def main():
    wallet_balance = 999.9
    async with websockets.connect(WS_URL) as ws:
         while True:
              msg = await ws.recv()
              # print(msg)
              
              ### do normal synchronous operations with msg output here ###

              ### if some conditions met, make an async API call to query wallet balance ###
              if msg == "condition met":  
                  # if a trade has executed, I want to update the value of my wallet balance  
                  wallet_balance = asyncio.create_task(get_wallet_balance())
                  # await wallet_balance
                  

if __name__ == "__main__":
    asyncio.run(main())

标签: pythonwebsocketpython-asynciotrading

解决方案


推荐阅读