"""
Binance Derivatives Trading USDS Futures WebSocket API

OpenAPI Specification for the Binance Derivatives Trading USDS Futures WebSocket API
The version of the OpenAPI document: 1.0.0
Generated by OpenAPI Generator (https://openapi-generator.tech)

Do not edit the class manually.
"""

import pytest

from unittest.mock import AsyncMock, MagicMock

from binance_common.models import WebsocketApiResponse
from binance_common.utils import parse_ws_rate_limit_headers
from binance_common.errors import RequiredError
from binance_sdk_derivatives_trading_usds_futures.websocket_api.api import TradeApi


from binance_sdk_derivatives_trading_usds_futures.websocket_api.models import (
    ModifyOrderSideEnum,
)
from binance_sdk_derivatives_trading_usds_futures.websocket_api.models import (
    ModifyOrderPriceMatchEnum,
)
from binance_sdk_derivatives_trading_usds_futures.websocket_api.models import (
    NewAlgoOrderSideEnum,
)
from binance_sdk_derivatives_trading_usds_futures.websocket_api.models import (
    NewAlgoOrderPositionSideEnum,
)
from binance_sdk_derivatives_trading_usds_futures.websocket_api.models import (
    NewAlgoOrderTimeInForceEnum,
)
from binance_sdk_derivatives_trading_usds_futures.websocket_api.models import (
    NewAlgoOrderWorkingTypeEnum,
)
from binance_sdk_derivatives_trading_usds_futures.websocket_api.models import (
    NewAlgoOrderPriceMatchEnum,
)
from binance_sdk_derivatives_trading_usds_futures.websocket_api.models import (
    NewAlgoOrderSelfTradePreventionModeEnum,
)
from binance_sdk_derivatives_trading_usds_futures.websocket_api.models import (
    NewOrderSideEnum,
)
from binance_sdk_derivatives_trading_usds_futures.websocket_api.models import (
    NewOrderPositionSideEnum,
)
from binance_sdk_derivatives_trading_usds_futures.websocket_api.models import (
    NewOrderTimeInForceEnum,
)
from binance_sdk_derivatives_trading_usds_futures.websocket_api.models import (
    NewOrderWorkingTypeEnum,
)
from binance_sdk_derivatives_trading_usds_futures.websocket_api.models import (
    NewOrderNewOrderRespTypeEnum,
)
from binance_sdk_derivatives_trading_usds_futures.websocket_api.models import (
    NewOrderPriceMatchEnum,
)
from binance_sdk_derivatives_trading_usds_futures.websocket_api.models import (
    NewOrderSelfTradePreventionModeEnum,
)
from binance_sdk_derivatives_trading_usds_futures.websocket_api.models import (
    CancelAlgoOrderResponse,
)
from binance_sdk_derivatives_trading_usds_futures.websocket_api.models import (
    CancelOrderResponse,
)
from binance_sdk_derivatives_trading_usds_futures.websocket_api.models import (
    ModifyOrderResponse,
)
from binance_sdk_derivatives_trading_usds_futures.websocket_api.models import (
    NewAlgoOrderResponse,
)
from binance_sdk_derivatives_trading_usds_futures.websocket_api.models import (
    NewOrderResponse,
)
from binance_sdk_derivatives_trading_usds_futures.websocket_api.models import (
    PositionInformationResponse,
)
from binance_sdk_derivatives_trading_usds_futures.websocket_api.models import (
    PositionInformationV2Response,
)
from binance_sdk_derivatives_trading_usds_futures.websocket_api.models import (
    QueryOrderResponse,
)


class TestWebSocketTradeApi:
    @pytest.fixture(autouse=True)
    def setup_method(self):
        self.mock_websocket_api = MagicMock()
        self.websocket_api = TradeApi(websocket_api=self.mock_websocket_api)

    @pytest.mark.asyncio
    async def test_cancel_algo_order_success(self):
        """Test cancel_algo_order() successfully with required parameters only."""

        expected_response = {
            "id": "unique-cancel-request-id-5678",
            "status": 200,
            "result": {
                "algoId": 2000000002162519,
                "clientAlgoId": "rDMG8WSde6LkyMNtk6s825",
                "code": "200",
                "msg": "success",
            },
            "rateLimits": [
                {
                    "rateLimitType": "REQUEST_WEIGHT",
                    "interval": "MINUTE",
                    "intervalNum": 1,
                    "limit": 2400,
                    "count": 6,
                }
            ],
        }

        self.mock_websocket_api.send_signed_message = AsyncMock(
            return_value=WebsocketApiResponse(
                data_function=lambda: expected_response,
                rate_limits=(
                    parse_ws_rate_limit_headers(expected_response["rateLimits"])
                    if "rateLimits" in expected_response
                    else None
                ),
            )
        )
        result = await self.websocket_api.cancel_algo_order()

        actual_call_args = self.mock_websocket_api.send_signed_message.call_args
        request_kwargs = actual_call_args.kwargs

        assert "payload" in request_kwargs
        assert "method" in request_kwargs["payload"]
        assert request_kwargs["payload"]["method"] == "/algoOrder.cancel".replace(
            "/", "", 1
        )

        assert result is not None
        assert result.data() == expected_response
        self.mock_websocket_api.send_signed_message.assert_called_once_with(
            payload={"method": "/algoOrder.cancel".replace("/", "", 1), "params": {}},
            response_model=CancelAlgoOrderResponse,
            signer=None,
        )

    @pytest.mark.asyncio
    async def test_cancel_algo_order_success_with_optional_params(self):
        """Test cancel_algo_order() successfully with optional parameters."""

        params = {
            "id": "e9d6b4349871b40611412680b3445fac",
            "algoid": 56,
            "clientalgoid": "clientalgoid_example",
            "recv_window": 5000,
        }

        expected_response = {
            "id": "unique-cancel-request-id-5678",
            "status": 200,
            "result": {
                "algoId": 2000000002162519,
                "clientAlgoId": "rDMG8WSde6LkyMNtk6s825",
                "code": "200",
                "msg": "success",
            },
            "rateLimits": [
                {
                    "rateLimitType": "REQUEST_WEIGHT",
                    "interval": "MINUTE",
                    "intervalNum": 1,
                    "limit": 2400,
                    "count": 6,
                }
            ],
        }

        self.mock_websocket_api.send_signed_message = AsyncMock(
            return_value=WebsocketApiResponse(
                data_function=lambda: expected_response,
                rate_limits=(
                    parse_ws_rate_limit_headers(expected_response["rateLimits"])
                    if "rateLimits" in expected_response
                    else None
                ),
            )
        )

        result = await self.websocket_api.cancel_algo_order(**params)

        actual_call_args = self.mock_websocket_api.send_signed_message.call_args
        request_kwargs = actual_call_args.kwargs

        assert "payload" in request_kwargs
        assert "method" in request_kwargs["payload"]
        assert request_kwargs["payload"]["method"] == "/algoOrder.cancel".replace(
            "/", "", 1
        )
        assert "params" in request_kwargs["payload"]
        params = request_kwargs["payload"]["params"]
        assert params["id"] == "e9d6b4349871b40611412680b3445fac"
        assert params["algoid"] == 56
        assert params["clientalgoid"] == "clientalgoid_example"
        assert params["recv_window"] == 5000

        assert result is not None
        assert result.data() == expected_response
        self.mock_websocket_api.send_signed_message.assert_called_once_with(
            payload={
                "method": "/algoOrder.cancel".replace("/", "", 1),
                "params": params,
            },
            response_model=CancelAlgoOrderResponse,
            signer=None,
        )

    @pytest.mark.asyncio
    async def test_cancel_algo_order_server_error(self):
        """Test that cancel_algo_order() raises an error when the server returns an error."""

        mock_error = Exception("ResponseError")
        self.mock_websocket_api.send_signed_message.side_effect = mock_error

        with pytest.raises(Exception, match="ResponseError"):
            await self.websocket_api.cancel_algo_order()

    @pytest.mark.asyncio
    async def test_cancel_order_success(self):
        """Test cancel_order() successfully with required parameters only."""

        params = {
            "symbol": "symbol_example",
        }

        expected_response = {
            "id": "5633b6a2-90a9-4192-83e7-925c90b6a2fd",
            "status": 200,
            "result": {
                "clientOrderId": "myOrder1",
                "cumQty": "0",
                "cumQuote": "0",
                "executedQty": "0",
                "orderId": 283194212,
                "origQty": "11",
                "origType": "TRAILING_STOP_MARKET",
                "price": "0",
                "reduceOnly": False,
                "side": "BUY",
                "positionSide": "SHORT",
                "status": "CANCELED",
                "stopPrice": "9300",
                "closePosition": False,
                "symbol": "BTCUSDT",
                "timeInForce": "GTC",
                "type": "TRAILING_STOP_MARKET",
                "activatePrice": "9020",
                "priceRate": "0.3",
                "updateTime": 1571110484038,
                "workingType": "CONTRACT_PRICE",
                "priceProtect": False,
                "priceMatch": "NONE",
                "selfTradePreventionMode": "NONE",
                "goodTillDate": 0,
            },
            "rateLimits": [
                {
                    "rateLimitType": "REQUEST_WEIGHT",
                    "interval": "MINUTE",
                    "intervalNum": 1,
                    "limit": 2400,
                    "count": 1,
                }
            ],
        }

        self.mock_websocket_api.send_signed_message = AsyncMock(
            return_value=WebsocketApiResponse(
                data_function=lambda: expected_response,
                rate_limits=(
                    parse_ws_rate_limit_headers(expected_response["rateLimits"])
                    if "rateLimits" in expected_response
                    else None
                ),
            )
        )
        result = await self.websocket_api.cancel_order(**params)

        actual_call_args = self.mock_websocket_api.send_signed_message.call_args
        request_kwargs = actual_call_args.kwargs

        assert "payload" in request_kwargs
        assert "method" in request_kwargs["payload"]
        assert request_kwargs["payload"]["method"] == "/order.cancel".replace(
            "/", "", 1
        )

        assert params["symbol"] == "symbol_example"

        assert result is not None
        assert result.data() == expected_response
        self.mock_websocket_api.send_signed_message.assert_called_once_with(
            payload={"method": "/order.cancel".replace("/", "", 1), "params": params},
            response_model=CancelOrderResponse,
            signer=None,
        )

    @pytest.mark.asyncio
    async def test_cancel_order_success_with_optional_params(self):
        """Test cancel_order() successfully with optional parameters."""

        params = {
            "symbol": "symbol_example",
            "id": "e9d6b4349871b40611412680b3445fac",
            "order_id": 1,
            "orig_client_order_id": "1",
            "recv_window": 5000,
        }

        expected_response = {
            "id": "5633b6a2-90a9-4192-83e7-925c90b6a2fd",
            "status": 200,
            "result": {
                "clientOrderId": "myOrder1",
                "cumQty": "0",
                "cumQuote": "0",
                "executedQty": "0",
                "orderId": 283194212,
                "origQty": "11",
                "origType": "TRAILING_STOP_MARKET",
                "price": "0",
                "reduceOnly": False,
                "side": "BUY",
                "positionSide": "SHORT",
                "status": "CANCELED",
                "stopPrice": "9300",
                "closePosition": False,
                "symbol": "BTCUSDT",
                "timeInForce": "GTC",
                "type": "TRAILING_STOP_MARKET",
                "activatePrice": "9020",
                "priceRate": "0.3",
                "updateTime": 1571110484038,
                "workingType": "CONTRACT_PRICE",
                "priceProtect": False,
                "priceMatch": "NONE",
                "selfTradePreventionMode": "NONE",
                "goodTillDate": 0,
            },
            "rateLimits": [
                {
                    "rateLimitType": "REQUEST_WEIGHT",
                    "interval": "MINUTE",
                    "intervalNum": 1,
                    "limit": 2400,
                    "count": 1,
                }
            ],
        }

        self.mock_websocket_api.send_signed_message = AsyncMock(
            return_value=WebsocketApiResponse(
                data_function=lambda: expected_response,
                rate_limits=(
                    parse_ws_rate_limit_headers(expected_response["rateLimits"])
                    if "rateLimits" in expected_response
                    else None
                ),
            )
        )

        result = await self.websocket_api.cancel_order(**params)

        actual_call_args = self.mock_websocket_api.send_signed_message.call_args
        request_kwargs = actual_call_args.kwargs

        assert "payload" in request_kwargs
        assert "method" in request_kwargs["payload"]
        assert request_kwargs["payload"]["method"] == "/order.cancel".replace(
            "/", "", 1
        )
        assert params["symbol"] == "symbol_example"
        assert params["id"] == "e9d6b4349871b40611412680b3445fac"
        assert params["order_id"] == 1
        assert params["orig_client_order_id"] == "1"
        assert params["recv_window"] == 5000

        assert result is not None
        assert result.data() == expected_response
        self.mock_websocket_api.send_signed_message.assert_called_once_with(
            payload={"method": "/order.cancel".replace("/", "", 1), "params": params},
            response_model=CancelOrderResponse,
            signer=None,
        )

    @pytest.mark.asyncio
    async def test_cancel_order_missing_required_param_symbol(self):
        """Test that cancel_order() raises RequiredError when 'symbol' is missing."""

        params = {
            "symbol": "symbol_example",
            "id": "e9d6b4349871b40611412680b3445fac",
            "order_id": 1,
            "orig_client_order_id": "1",
            "recv_window": 5000,
        }
        params["symbol"] = None

        with pytest.raises(RequiredError, match="Missing required parameter 'symbol'"):
            await self.websocket_api.cancel_order(**params)

    @pytest.mark.asyncio
    async def test_cancel_order_server_error(self):
        """Test that cancel_order() raises an error when the server returns an error."""

        params = {
            "symbol": "symbol_example",
        }

        mock_error = Exception("ResponseError")
        self.mock_websocket_api.send_signed_message.side_effect = mock_error

        with pytest.raises(Exception, match="ResponseError"):
            await self.websocket_api.cancel_order(**params)

    @pytest.mark.asyncio
    async def test_modify_order_success(self):
        """Test modify_order() successfully with required parameters only."""

        params = {
            "symbol": "symbol_example",
            "side": ModifyOrderSideEnum["BUY"].value,
            "quantity": 1.0,
            "price": 1.0,
        }

        expected_response = {
            "id": "c8c271ba-de70-479e-870c-e64951c753d9",
            "status": 200,
            "result": {
                "orderId": 328971409,
                "symbol": "BTCUSDT",
                "status": "NEW",
                "clientOrderId": "xGHfltUMExx0TbQstQQfRX",
                "price": "43769.10",
                "avgPrice": "0.00",
                "origQty": "0.110",
                "executedQty": "0.000",
                "cumQty": "0.000",
                "cumQuote": "0.00000",
                "timeInForce": "GTC",
                "type": "LIMIT",
                "reduceOnly": False,
                "closePosition": False,
                "side": "SELL",
                "positionSide": "SHORT",
                "stopPrice": "0.00",
                "workingType": "CONTRACT_PRICE",
                "priceProtect": False,
                "origType": "LIMIT",
                "priceMatch": "NONE",
                "selfTradePreventionMode": "NONE",
                "goodTillDate": 0,
                "updateTime": 1703426756190,
            },
            "rateLimits": [
                {
                    "rateLimitType": "ORDERS",
                    "interval": "SECOND",
                    "intervalNum": 10,
                    "limit": 300,
                    "count": 1,
                },
                {
                    "rateLimitType": "ORDERS",
                    "interval": "MINUTE",
                    "intervalNum": 1,
                    "limit": 1200,
                    "count": 1,
                },
                {
                    "rateLimitType": "REQUEST_WEIGHT",
                    "interval": "MINUTE",
                    "intervalNum": 1,
                    "limit": 2400,
                    "count": 1,
                },
            ],
        }

        self.mock_websocket_api.send_signed_message = AsyncMock(
            return_value=WebsocketApiResponse(
                data_function=lambda: expected_response,
                rate_limits=(
                    parse_ws_rate_limit_headers(expected_response["rateLimits"])
                    if "rateLimits" in expected_response
                    else None
                ),
            )
        )
        result = await self.websocket_api.modify_order(**params)

        actual_call_args = self.mock_websocket_api.send_signed_message.call_args
        request_kwargs = actual_call_args.kwargs

        assert "payload" in request_kwargs
        assert "method" in request_kwargs["payload"]
        assert request_kwargs["payload"]["method"] == "/order.modify".replace(
            "/", "", 1
        )

        assert params["symbol"] == "symbol_example"

        assert params["side"] == ModifyOrderSideEnum["BUY"].value

        assert params["quantity"] == 1.0

        assert params["price"] == 1.0

        assert result is not None
        assert result.data() == expected_response
        self.mock_websocket_api.send_signed_message.assert_called_once_with(
            payload={"method": "/order.modify".replace("/", "", 1), "params": params},
            response_model=ModifyOrderResponse,
            signer=None,
        )

    @pytest.mark.asyncio
    async def test_modify_order_success_with_optional_params(self):
        """Test modify_order() successfully with optional parameters."""

        params = {
            "symbol": "symbol_example",
            "side": ModifyOrderSideEnum["BUY"].value,
            "quantity": 1.0,
            "price": 1.0,
            "id": "e9d6b4349871b40611412680b3445fac",
            "order_id": 1,
            "orig_client_order_id": "1",
            "price_match": ModifyOrderPriceMatchEnum["NONE"].value,
            "recv_window": 5000,
        }

        expected_response = {
            "id": "c8c271ba-de70-479e-870c-e64951c753d9",
            "status": 200,
            "result": {
                "orderId": 328971409,
                "symbol": "BTCUSDT",
                "status": "NEW",
                "clientOrderId": "xGHfltUMExx0TbQstQQfRX",
                "price": "43769.10",
                "avgPrice": "0.00",
                "origQty": "0.110",
                "executedQty": "0.000",
                "cumQty": "0.000",
                "cumQuote": "0.00000",
                "timeInForce": "GTC",
                "type": "LIMIT",
                "reduceOnly": False,
                "closePosition": False,
                "side": "SELL",
                "positionSide": "SHORT",
                "stopPrice": "0.00",
                "workingType": "CONTRACT_PRICE",
                "priceProtect": False,
                "origType": "LIMIT",
                "priceMatch": "NONE",
                "selfTradePreventionMode": "NONE",
                "goodTillDate": 0,
                "updateTime": 1703426756190,
            },
            "rateLimits": [
                {
                    "rateLimitType": "ORDERS",
                    "interval": "SECOND",
                    "intervalNum": 10,
                    "limit": 300,
                    "count": 1,
                },
                {
                    "rateLimitType": "ORDERS",
                    "interval": "MINUTE",
                    "intervalNum": 1,
                    "limit": 1200,
                    "count": 1,
                },
                {
                    "rateLimitType": "REQUEST_WEIGHT",
                    "interval": "MINUTE",
                    "intervalNum": 1,
                    "limit": 2400,
                    "count": 1,
                },
            ],
        }

        self.mock_websocket_api.send_signed_message = AsyncMock(
            return_value=WebsocketApiResponse(
                data_function=lambda: expected_response,
                rate_limits=(
                    parse_ws_rate_limit_headers(expected_response["rateLimits"])
                    if "rateLimits" in expected_response
                    else None
                ),
            )
        )

        result = await self.websocket_api.modify_order(**params)

        actual_call_args = self.mock_websocket_api.send_signed_message.call_args
        request_kwargs = actual_call_args.kwargs

        assert "payload" in request_kwargs
        assert "method" in request_kwargs["payload"]
        assert request_kwargs["payload"]["method"] == "/order.modify".replace(
            "/", "", 1
        )
        assert params["symbol"] == "symbol_example"
        assert params["side"] == ModifyOrderSideEnum["BUY"].value
        assert params["quantity"] == 1.0
        assert params["price"] == 1.0
        assert params["id"] == "e9d6b4349871b40611412680b3445fac"
        assert params["order_id"] == 1
        assert params["orig_client_order_id"] == "1"
        assert params["price_match"] == ModifyOrderPriceMatchEnum["NONE"].value
        assert params["recv_window"] == 5000

        assert result is not None
        assert result.data() == expected_response
        self.mock_websocket_api.send_signed_message.assert_called_once_with(
            payload={"method": "/order.modify".replace("/", "", 1), "params": params},
            response_model=ModifyOrderResponse,
            signer=None,
        )

    @pytest.mark.asyncio
    async def test_modify_order_missing_required_param_symbol(self):
        """Test that modify_order() raises RequiredError when 'symbol' is missing."""

        params = {
            "symbol": "symbol_example",
            "side": ModifyOrderSideEnum["BUY"].value,
            "quantity": 1.0,
            "price": 1.0,
            "id": "e9d6b4349871b40611412680b3445fac",
            "order_id": 1,
            "orig_client_order_id": "1",
            "price_match": ModifyOrderPriceMatchEnum["NONE"].value,
            "recv_window": 5000,
        }
        params["symbol"] = None

        with pytest.raises(RequiredError, match="Missing required parameter 'symbol'"):
            await self.websocket_api.modify_order(**params)

    @pytest.mark.asyncio
    async def test_modify_order_missing_required_param_side(self):
        """Test that modify_order() raises RequiredError when 'side' is missing."""

        params = {
            "symbol": "symbol_example",
            "side": ModifyOrderSideEnum["BUY"].value,
            "quantity": 1.0,
            "price": 1.0,
            "id": "e9d6b4349871b40611412680b3445fac",
            "order_id": 1,
            "orig_client_order_id": "1",
            "price_match": ModifyOrderPriceMatchEnum["NONE"].value,
            "recv_window": 5000,
        }
        params["side"] = None

        with pytest.raises(RequiredError, match="Missing required parameter 'side'"):
            await self.websocket_api.modify_order(**params)

    @pytest.mark.asyncio
    async def test_modify_order_missing_required_param_quantity(self):
        """Test that modify_order() raises RequiredError when 'quantity' is missing."""

        params = {
            "symbol": "symbol_example",
            "side": ModifyOrderSideEnum["BUY"].value,
            "quantity": 1.0,
            "price": 1.0,
            "id": "e9d6b4349871b40611412680b3445fac",
            "order_id": 1,
            "orig_client_order_id": "1",
            "price_match": ModifyOrderPriceMatchEnum["NONE"].value,
            "recv_window": 5000,
        }
        params["quantity"] = None

        with pytest.raises(
            RequiredError, match="Missing required parameter 'quantity'"
        ):
            await self.websocket_api.modify_order(**params)

    @pytest.mark.asyncio
    async def test_modify_order_missing_required_param_price(self):
        """Test that modify_order() raises RequiredError when 'price' is missing."""

        params = {
            "symbol": "symbol_example",
            "side": ModifyOrderSideEnum["BUY"].value,
            "quantity": 1.0,
            "price": 1.0,
            "id": "e9d6b4349871b40611412680b3445fac",
            "order_id": 1,
            "orig_client_order_id": "1",
            "price_match": ModifyOrderPriceMatchEnum["NONE"].value,
            "recv_window": 5000,
        }
        params["price"] = None

        with pytest.raises(RequiredError, match="Missing required parameter 'price'"):
            await self.websocket_api.modify_order(**params)

    @pytest.mark.asyncio
    async def test_modify_order_server_error(self):
        """Test that modify_order() raises an error when the server returns an error."""

        params = {
            "symbol": "symbol_example",
            "side": ModifyOrderSideEnum["BUY"].value,
            "quantity": 1.0,
            "price": 1.0,
        }

        mock_error = Exception("ResponseError")
        self.mock_websocket_api.send_signed_message.side_effect = mock_error

        with pytest.raises(Exception, match="ResponseError"):
            await self.websocket_api.modify_order(**params)

    @pytest.mark.asyncio
    async def test_new_algo_order_success(self):
        """Test new_algo_order() successfully with required parameters only."""

        params = {
            "algo_type": "algo_type_example",
            "symbol": "symbol_example",
            "side": NewAlgoOrderSideEnum["BUY"].value,
            "type": "type_example",
        }

        expected_response = {
            "id": "06c9dbd8-ccbf-4ecf-a29c-fe31495ac73f",
            "status": 200,
            "result": {
                "algoId": 3000000000003505,
                "clientAlgoId": "0Xkl1p621E4EryvufmYre1",
                "algoType": "CONDITIONAL",
                "orderType": "TAKE_PROFIT",
                "symbol": "BTCUSDT",
                "side": "SELL",
                "positionSide": "SHORT",
                "timeInForce": "GTC",
                "quantity": "1.000",
                "algoStatus": "NEW",
                "triggerPrice": "120000.00",
                "price": "160000.00",
                "icebergQuantity": None,
                "selfTradePreventionMode": "EXPIRE_MAKER",
                "workingType": "CONTRACT_PRICE",
                "priceMatch": "NONE",
                "closePosition": False,
                "priceProtect": False,
                "reduceOnly": False,
                "createTime": 1762507264142,
                "updateTime": 1762507264143,
                "triggerTime": 0,
                "goodTillDate": 0,
            },
            "rateLimits": [
                {
                    "rateLimitType": "REQUEST_WEIGHT",
                    "interval": "MINUTE",
                    "intervalNum": 1,
                    "limit": 2400,
                    "count": 1,
                }
            ],
        }

        self.mock_websocket_api.send_signed_message = AsyncMock(
            return_value=WebsocketApiResponse(
                data_function=lambda: expected_response,
                rate_limits=(
                    parse_ws_rate_limit_headers(expected_response["rateLimits"])
                    if "rateLimits" in expected_response
                    else None
                ),
            )
        )
        result = await self.websocket_api.new_algo_order(**params)

        actual_call_args = self.mock_websocket_api.send_signed_message.call_args
        request_kwargs = actual_call_args.kwargs

        assert "payload" in request_kwargs
        assert "method" in request_kwargs["payload"]
        assert request_kwargs["payload"]["method"] == "/algoOrder.place".replace(
            "/", "", 1
        )

        assert params["algo_type"] == "algo_type_example"

        assert params["symbol"] == "symbol_example"

        assert params["side"] == NewAlgoOrderSideEnum["BUY"].value

        assert params["type"] == "type_example"

        assert result is not None
        assert result.data() == expected_response
        self.mock_websocket_api.send_signed_message.assert_called_once_with(
            payload={
                "method": "/algoOrder.place".replace("/", "", 1),
                "params": params,
            },
            response_model=NewAlgoOrderResponse,
            signer=None,
        )

    @pytest.mark.asyncio
    async def test_new_algo_order_success_with_optional_params(self):
        """Test new_algo_order() successfully with optional parameters."""

        params = {
            "algo_type": "algo_type_example",
            "symbol": "symbol_example",
            "side": NewAlgoOrderSideEnum["BUY"].value,
            "type": "type_example",
            "id": "e9d6b4349871b40611412680b3445fac",
            "position_side": NewAlgoOrderPositionSideEnum["BOTH"].value,
            "time_in_force": NewAlgoOrderTimeInForceEnum["GTC"].value,
            "quantity": 1.0,
            "price": 1.0,
            "trigger_price": 1.0,
            "working_type": NewAlgoOrderWorkingTypeEnum["MARK_PRICE"].value,
            "price_match": NewAlgoOrderPriceMatchEnum["NONE"].value,
            "close_position": "close_position_example",
            "price_protect": "False",
            "reduce_only": "False",
            "activation_price": 1.0,
            "callback_rate": 1.0,
            "client_algo_id": "1",
            "self_trade_prevention_mode": NewAlgoOrderSelfTradePreventionModeEnum[
                "EXPIRE_TAKER"
            ].value,
            "good_till_date": 56,
            "recv_window": 5000,
        }

        expected_response = {
            "id": "06c9dbd8-ccbf-4ecf-a29c-fe31495ac73f",
            "status": 200,
            "result": {
                "algoId": 3000000000003505,
                "clientAlgoId": "0Xkl1p621E4EryvufmYre1",
                "algoType": "CONDITIONAL",
                "orderType": "TAKE_PROFIT",
                "symbol": "BTCUSDT",
                "side": "SELL",
                "positionSide": "SHORT",
                "timeInForce": "GTC",
                "quantity": "1.000",
                "algoStatus": "NEW",
                "triggerPrice": "120000.00",
                "price": "160000.00",
                "icebergQuantity": None,
                "selfTradePreventionMode": "EXPIRE_MAKER",
                "workingType": "CONTRACT_PRICE",
                "priceMatch": "NONE",
                "closePosition": False,
                "priceProtect": False,
                "reduceOnly": False,
                "createTime": 1762507264142,
                "updateTime": 1762507264143,
                "triggerTime": 0,
                "goodTillDate": 0,
            },
            "rateLimits": [
                {
                    "rateLimitType": "REQUEST_WEIGHT",
                    "interval": "MINUTE",
                    "intervalNum": 1,
                    "limit": 2400,
                    "count": 1,
                }
            ],
        }

        self.mock_websocket_api.send_signed_message = AsyncMock(
            return_value=WebsocketApiResponse(
                data_function=lambda: expected_response,
                rate_limits=(
                    parse_ws_rate_limit_headers(expected_response["rateLimits"])
