Задать вопрос

Как обработать ошибку потери соединения?

Добрый день. У меня есть такой код:
from datetime import datetime
from pybit.unified_trading import HTTP
import pybit
import time

t_client = HTTP(api_key=API_KEY_T, api_secret=API_SECRET_M)
b_client = HTTP(api_key=API_KEY_B, api_secret=API_SECRET_B)

def GetOrdersAndWork(name, b_client, all_open_orders_bot):
    try:
        for order in all_open_orders_mt:
            symbol = order['symbol']
            side = order['side']
            size = order['size']
            takeProfit = order['takeProfit']
            stopLoss = order['stopLoss']
            leverage = order['leverage']
            create_time = int(order['updatedTime'])

            order_found = False 
            for order_bot in all_open_orders_bot:
                if order["symbol"] == order_bot["symbol"]:
                    if size != order_bot["size"] and float(size) > float(order_bot["size"]):
                        print(f"Изменилось количество контрактов в токене {order['symbol']} у {name}.")
                        add_size = str(float(size) - float(order_bot["size"]))
                        try:
                            b_client.place_order(category="linear", symbol=symbol, side=side, orderType="Market", qty=add_size, timeInForce="FOK")
                        except pybit.exceptions.InvalidRequestError as e:
                            print(f"Ошибка при размещении ордера: {e}")
            else:
                if not order_found and create_time > start_work_in_time:
                    get_leverage = b_client.get_positions(category="linear", symbol=symbol)["result"]["list"][0]["leverage"]
                    if get_leverage == leverage:
                        b_client.place_order(category="linear", symbol=symbol, side=side, orderType="Market", qty=size, timeInForce="FOK")
                    else:
                        b_client.set_leverage(category="linear", symbol=symbol, buyLeverage=leverage, sellLeverage=leverage)
                        b_client.place_order(category="linear", symbol=symbol, side=side, orderType="Market", qty=size, timeInForce="FOK")
                    print(f"{name} создал сделку по {symbol} в {side} в количестве {size}")
                    break 

        for order_close_bot in all_open_orders_bot:
            symbol_to_close = order_close_bot["symbol"]
            create_time = int(order_close_bot["updatedTime"])
            size_close = order_close_bot["size"]
            master_order_exists = False
            for order_master in all_open_orders_mt:
                if order_master["symbol"] == order_close_bot["symbol"]:
                    master_order_exists = True
                    break
            if not master_order_exists and create_time > start_work_in_time:
                if order_close_bot["side"] == "Buy":
                    b_client.place_order(category="linear", symbol=symbol_to_close, side="Sell", orderType="Market", qty=size_close, timeInForce="FOK")
                else:
                    b_client.place_order(category="linear", symbol=symbol_to_close, side="Buy", orderType="Market", qty=size_close, timeInForce="FOK")
                break
    except Exception as e:
        print(f"Произошла ошибка: {e}")

while True:
    all_open_orders_mt = t_client.get_positions(category="linear", settleCoin="USDT")["result"]["list"]
    time.sleep(0.7)
    all_open_orders_bot_3 = b_client.get_positions(category="linear", settleCoin="USDT")["result"]["list"]

    GetOrdersAndWork("b", b_client, all_open_orders_bot_3)

Всё работает хорошо, в какой-то момент, в неопределенный промежуток времени, вероятно, когда биржа лагает, вылетает ошибка:
Traceback (most recent call last):
  File "C:\Users\Computer PC\AppData\Local\Programs\Python\Python310\lib\site-packages\urllib3\connectionpool.py", line 699, in urlopen
    httplib_response = self._make_request(
  File "C:\Users\Computer PC\AppData\Local\Programs\Python\Python310\lib\site-packages\urllib3\connectionpool.py", line 445, in _make_request
    six.raise_from(e, None)
  File "<string>", line 3, in raise_from
  File "C:\Users\Computer PC\AppData\Local\Programs\Python\Python310\lib\site-packages\urllib3\connectionpool.py", line 440, in _make_request
    httplib_response = conn.getresponse()
  File "C:\Users\Computer PC\AppData\Local\Programs\Python\Python310\lib\http\client.py", line 1368, in getresponse
    response.begin()
  File "C:\Users\Computer PC\AppData\Local\Programs\Python\Python310\lib\http\client.py", line 317, in begin
    version, status, reason = self._read_status()
  File "C:\Users\Computer PC\AppData\Local\Programs\Python\Python310\lib\http\client.py", line 286, in _read_status
    raise RemoteDisconnected("Remote end closed connection without"
http.client.RemoteDisconnected: Remote end closed connection without response

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "C:\Users\Computer PC\AppData\Local\Programs\Python\Python310\lib\site-packages\requests\adapters.py", line 486, in send
    resp = conn.urlopen(
  File "C:\Users\Computer PC\AppData\Local\Programs\Python\Python310\lib\site-packages\urllib3\connectionpool.py", line 755, in urlopen
    retries = retries.increment(
  File "C:\Users\Computer PC\AppData\Local\Programs\Python\Python310\lib\site-packages\urllib3\util\retry.py", line 532, in increment
    raise six.reraise(type(error), error, _stacktrace)
  File "C:\Users\Computer PC\AppData\Local\Programs\Python\Python310\lib\site-packages\urllib3\packages\six.py", line 769, in reraise
    raise value.with_traceback(tb)
  File "C:\Users\Computer PC\AppData\Local\Programs\Python\Python310\lib\site-packages\urllib3\connectionpool.py", line 699, in urlopen
    httplib_response = self._make_request(
  File "C:\Users\Computer PC\AppData\Local\Programs\Python\Python310\lib\site-packages\urllib3\connectionpool.py", line 445, in _make_request
    six.raise_from(e, None)
  File "<string>", line 3, in raise_from
  File "C:\Users\Computer PC\AppData\Local\Programs\Python\Python310\lib\site-packages\urllib3\connectionpool.py", line 440, in _make_request
    httplib_response = conn.getresponse()
  File "C:\Users\Computer PC\AppData\Local\Programs\Python\Python310\lib\http\client.py", line 1368, in getresponse
    response.begin()
  File "C:\Users\Computer PC\AppData\Local\Programs\Python\Python310\lib\http\client.py", line 317, in begin
    version, status, reason = self._read_status()
  File "C:\Users\Computer PC\AppData\Local\Programs\Python\Python310\lib\http\client.py", line 286, in _read_status
    raise RemoteDisconnected("Remote end closed connection without"
urllib3.exceptions.ProtocolError: ('Connection aborted.', RemoteDisconnected('Remote end closed connection without response'))

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "C:\Python\T\ByBit.py", line 113, in <module>
    all_open_orders_bot_3 = b_client.get_positions(category="linear", settleCoin="USDT")["result"]["list"]
  File "C:\Users\Computer PC\AppData\Local\Programs\Python\Python310\lib\site-packages\pybit\_v5_position.py", line 22, in get_positions
    return self._submit_request(
  File "C:\Users\Computer PC\AppData\Local\Programs\Python\Python310\lib\site-packages\pybit\_http_manager.py", line 285, in _submit_request
    raise e
  File "C:\Users\Computer PC\AppData\Local\Programs\Python\Python310\lib\site-packages\pybit\_http_manager.py", line 272, in _submit_request
    s = self.client.send(r, timeout=self.timeout)
  File "C:\Users\Computer PC\AppData\Local\Programs\Python\Python310\lib\site-packages\requests\sessions.py", line 703, in send
    r = adapter.send(request, **kwargs)
  File "C:\Users\Computer PC\AppData\Local\Programs\Python\Python310\lib\site-packages\requests\adapters.py", line 501, in send
    raise ConnectionError(err, request=request)
requests.exceptions.ConnectionError: ('Connection aborted.', RemoteDisconnected('Remote end closed connection without response'))

Теряется соединение с биржей и программа останавливается. Как мне обработать данную ошибку, чтобы программа не останавливалась, а повторно пыталась бы подключиться и продолжила работу ?

Спасибо.
  • Вопрос задан
  • 234 просмотра
Подписаться 1 Простой 1 комментарий
Пригласить эксперта
Ответы на вопрос 1
2ord
@2ord
Нужно добавить обработку исключения http.client.RemoteDisconnected
Ответ написан
Комментировать
Ваш ответ на вопрос

Войдите, чтобы написать ответ

Похожие вопросы