کد زیر رو غیر از تابع _send_request بهینه کن و مرتب تر بنویس
و یجوری بنویس که اگر  هنگام باز کردن پوزیشن اگر داخل پارامترهای وورودی حد سود و ضرر بود که دیگ نیاز به اجرای set_multi_tp_sl نباش ولی اگر نبود این بخش اجرا بشه و همچنین درصورتی که در چیدن حد سود و ضرر و یا وورود مشکلی ایجاد شد خروجیشو بده تا بفهمم  ایراد کجا بوده


import time, requests, hashlib, hmac
from datetime import datetime


class ApiToobit:
    def __init__(self, api_key: str, secret_key: str, user: str):
        self.api_key = api_key
        self.secret_key = secret_key
        self.user = user
        self.base_url = 'https://api.toobit.com'
        self.headers = {"X-BB-APIKEY": api_key, "Content-Type": "application/x-www-form-urlencoded"}

    def _sign(self, data: str) -> str:
        return hmac.new(self.secret_key.encode(), data.encode(), hashlib.sha256).hexdigest()

    def _send_request(self, action: str, method: str, path: str, params: dict):
        try:
            params = dict(sorted(params.items()))
            data = "&".join(f"{key}={value}" for key, value in params.items())
            signature = self._sign(data)

            url = f"{self.base_url}{path}"
            response = requests.request(
                method,
                url,
                data=data,
                headers=self.headers,
                params={"signature": signature, **params} if method == 'GET' else {"signature": signature}
            )

            if response.status_code == 200:
                return response.json()
            else:
                print(f"Error in {action}: {response.text}")
                return None
        except Exception as e:
            print(f"Unexpected error in {action}: {e}")
            return None

    def create_listen_key(self):
        params = {"timestamp": int(time.time() * 1000), "recvWindow": 10000}
        return self._send_request('create_listen_key', 'POST', '/api/v1/listenKey', params)

    def keepalive_listen_key(self, listen_key: str):
        params = {"listenKey": listen_key, "timestamp": int(time.time() * 1000), "recvWindow": 10000}
        return self._send_request('keepalive_listen_key', 'PUT', '/api/v1/listenKey', params)

    def close_listen_key(self, listen_key: str):
        params = {"listenKey": listen_key, "timestamp": int(time.time() * 1000), "recvWindow": 10000}
        return self._send_request('close_listen_key', 'DELETE', '/api/v1/listenKey', params)

    def set_leverage(self, symbol: str, leverage: int):
        params = {
            "symbol": f"{symbol.upper()}-SWAP-USDT",
            "leverage": leverage,
            "timestamp": int(time.time() * 1000)
        }
        return self._send_request("set_leverage", "POST", "/api/v1/futures/leverage", params)

    def set_margin_type(self, symbol: str, margin_type: str):
        params = {
            "symbol": f"{symbol.upper()}-SWAP-USDT",
            "marginType": margin_type.upper(),
            "timestamp": int(time.time() * 1000)
        }
        return self._send_request('set_margin_type', 'POST', '/api/v1/futures/marginType', params)

    def get_last_price(self, symbol: str):
        params = {"symbol": f"{symbol.upper()}-SWAP-USDT"}
        response = self._send_request("get_last_price", "GET", "/quote/v1/markPrice", params)
        return float(response["price"]) if response else None

    def get_candle_data(self, symbol: str, interval: str = '1h', limit: int = 1000):
        params = {
            "symbol": f"{symbol.upper()}-SWAP-USDT",
            "interval": interval,
            "limit": limit,
            "timestamp": int(time.time() * 1000)
        }
        response = self._send_request("get_candle_data", "GET", "/quote/v1/klines", params)
        if not response:
            print("Error: Failed to fetch candlestick data.")
            return None

        try:
            return [{
                "timestamp": datetime.fromtimestamp(candle[0] / 1000).strftime("%Y-%m-%d %H:%M:%S"),
                "open": float(candle[1]),
                "high": float(candle[2]),
                "low": float(candle[3]),
                "close": float(candle[4]),
                "volume": float(candle[5])
            } for candle in response]
        except Exception as e:
            print(f"Error while parsing candlestick data: {e}")
            return None

    def get_user_balance(self):
        params = {"timestamp": int(time.time() * 1000)}
        response = self._send_request("get_user_balance", "GET", "/api/v1/futures/balance", params)
        return float(response[0]["availableBalance"]) if response else None

    def calculate_quantity(self, symbol: str, volume_type: str, volume: float, leverage: int, last_price:float) -> float:
        account_balance = self.get_user_balance()
        if volume_type.lower() == "percent":
            volume = (volume * leverage * account_balance / 100)
        elif volume_type.lower() == "fixed":
            volume = volume * leverage

        return round(volume / last_price, 5) if account_balance else None

    def open_position(self, symbol: str, position_side: str, order_type: str, leverage: int,volume: float, volume_type: str, 
                      price: float = None, stopPrice: float = None, tp_sl_levels: list = None, **kwargs):
        try:
            if not self.set_leverage(symbol, leverage):
                raise ValueError("Failed to set leverage")
            
            last_price = self.get_last_price(symbol)
            if last_price:
                quantity = self.calculate_quantity(symbol, volume_type, volume, leverage, last_price)
                params = {
                    "symbol": f"{symbol.upper()}-SWAP-USDT",
                    "side": "BUY_OPEN" if position_side.upper() == "LONG" else "SELL_OPEN",
                    "type": 'STOP' if order_type.lower() == 'stop' else "LIMIT",
                    "priceType": "INPUT" if order_type.lower() == "limit" else "MARKET",
                    "quantity": quantity,
                    "price": last_price if order_type.lower() == 'market' else price,
                    "newClientOrderId": f"OPEN_{position_side.upper()}/{symbol.upper()}-{self.user}-{int(time.time() * 1000)}",
                    "timestamp": int(time.time() * 1000)
                }
                if stopPrice:
                    params['stopPrice'] = stopPrice
                for key, value in kwargs.items():
                    # region ==> discription
                    #   priceType       =>  INPUT、OPPONENT、QUEUE、OVER、MARKET
                    #   stopPrice       =>  type = STOP order Mandatory need
                    #   timeInForce     =>  The time command (Time in Force) of LIMIT order, the currently supported types are GTC, FOK, IOC, LIMIT_MAKER
                    #   takeProfit      =>  Take profit price
                    #   tpTriggerBy     =>  The price type to trigger take profit: MARK_PRICE, CONTRACT_PRICE. Default CONTRACT_PRICE
                    #   tpLimitPrice    =>  The limit order price when take profit price is triggered. Only works when tpOrderType=LIMIT
                    #   tpOrderType     =>  The order type when take profit is triggered. MARKET(default), LIMIT.
                    #   stopLoss        =>  Stop loss price,
                    #   slTriggerBy     =>  The price type to trigger take profit: MARK_PRICE, CONTRACT_PRICE. Default CONTRACT_PRICE
                    #   slLimitPrice    =>  The limit order price when take profit price is triggered. Only works when slOrderType=LIMI
                    #   slOrderType     =>  The order type when take profit is triggered. MARKET(default), LIMIT.
                    # endregion
                    params[key] = value

                response = self._send_request("open_position", "POST", "/api/v1/futures/order", params)
                if not response:
                    raise ValueError("Failed to open position")

                if tp_sl_levels:
                    self.set_multi_tp_sl(symbol, position_side, tp_sl_levels)

                return response
        except Exception as e:
            print(f"Error while opening position: {e}")
            return None

    def set_multi_tp_sl(self, symbol: str, position_side: str, levels: list):
        responses = []
        for level in levels:
            params = {
                "symbol": f"{symbol.upper()}-SWAP-USDT",
                "side": "SELL_CLOSE" if position_side.upper() == "LONG" else "BUY_CLOSE",
                "type": "STOP" ,#if level["type"].upper() == "SL" else "LIMIT",
                "priceType": "MARKET", #if level["type"].upper() == "SL" else "INPUT",
                "quantity": level["quantity"],
                "price": level.get("price"),
                "stopPrice": level.get("price"), #if level["type"].upper() == "SL" else None,
                "newClientOrderId": f"{level['type'].upper()}_{int(time.time() * 1000)}",
                "timestamp": int(time.time() * 1000)
            }
            responses.append(self._send_request("set_multi_tp_sl", "POST", "/api/v1/futures/order", params))
        return responses

    def close_position(self, symbol: str, position_side: str, quantity: float):
        params = {
            "symbol": f"{symbol.upper()}-SWAP-USDT",
            "side": "SELL_CLOSE" if position_side.upper() == "LONG" else "BUY_CLOSE",
            "type": "LIMIT",
            "priceType": "MARKET",
            "quantity": quantity,
            "timestamp": int(time.time() * 1000),
            "newClientOrderId": f"CLOSE_{position_side.upper()}/{symbol.upper()}-{int(time.time() * 1000)}"
        }
        return self._send_request("close_position", "POST", "/api/v1/futures/order", params)