0

我想就我的菜鸟代码寻求一些帮助/建议。我想听一个带有 BTC 蜡烛的 Kucoin websocket 并相应地进行一些计算和操作。基本上是一个非常轻量级的交易机器人。但是,我是 Asyncio 的新手,我不断收到超时和长异常消息。我当前的代码是这样的:

async def main():
 global loop     

 async def calc_technicals(coin, price):
    rsi = 0
    #calculate RSI, MACD, etc. ...
 
 #callback listener that reads the BTC candles
 async def handle_evt_5min(msg):
    global last_min

    last_min = datetime.now()
    coin = msg['topic'][16:40].replace("_5min", "")
    df = pd.DataFrame([msg['data']['candles']])
    df.columns = ['Time', 'Open', 'Close', 'High', 'Low', 'Volume', 'Turnover']
    df = df.set_index('Time')
    df.index = pd.to_datetime(df.index, unit = 's')
    df = df.astype(float)
    price = df['Close'].iloc[-1]
    print(df)
    
    #do some calculations
    await calc_technicals(coin, price)

 #register to listen to websocket
 ksm_5min = await KucoinSocketManager.create(loop, client1, handle_evt_5min)

 await ksm_5min.subscribe('/market/candles:BTC-USDT_5min')
    
 while True:
    # check if websocket stopped sending
    current_time = datetime.now()
    ping = (current_time - last_min).total_seconds()
    if(ping > 60):
        await ksm_5min.unsubscribe('/market/candles:BTC-USDT_5min')       
        ksm_5min = await KucoinSocketManager.create(loop, client1, handle_evt_5min)
        await ksm_5min.subscribe('/market/candles:BTC-USDT_5min')

    #keep the loop open
    await asyncio.sleep(30)

#end of script. create loop and if it crashes, create a new one!
while True:
 try:
    loop = asyncio.new_event_loop()
    asyncio.set_event_loop(loop)
    loop.run_until_complete(main())
 except Exception as e:
    print(e)

我的第一个问题是,数据流有时会停止,我得到一个“代码 = 1000(OK),没有原因”异常。另一个问题是整个循环在那之后经常崩溃,我得到了很多异常。在这种情况下,整个数据流会在脚本启动并继续工作之前停止大约 10 分钟。

Task exception was never retrieved
ConnectionResetError: [WinError 10054] An existing connection was forcibly closed by the remote host

During handling of the above exception, another exception occurred:
urllib3.exceptions.ProtocolError: ('Connection aborted.', ConnectionResetError(10054, 'An existing connection was forcibly closed by the remote host', None, 10054, None))

During handling of the above exception, another exception occurred:
requests.exceptions.ConnectionError: ('Connection aborted.', ConnectionResetError(10054, 'An existing connection was forcibly closed by the remote host', None, 10054, None)) 
Task exception was never retrieved

如果有人可以查看并帮助我改进此代码并消除这些异常,我将不胜感激。提前致谢

4

0 回答 0