"""
Binance Margin Trading REST API

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

Do not edit the class manually.
"""

from typing import List, Optional, Union
from requests import Session
from binance_common.configuration import ConfigurationRestAPI
from binance_common.errors import RequiredError
from binance_common.models import ApiResponse
from binance_common.signature import Signers
from binance_common.utils import send_request

from ..models import CreateSpecialKeyResponse


from ..models import GetForceLiquidationRecordResponse
from ..models import GetSmallLiabilityExchangeCoinListResponse
from ..models import GetSmallLiabilityExchangeHistoryResponse
from ..models import MarginAccountCancelAllOpenOrdersOnASymbolResponse
from ..models import MarginAccountCancelOcoResponse
from ..models import MarginAccountCancelOrderResponse
from ..models import MarginAccountNewOcoResponse
from ..models import MarginAccountNewOrderResponse
from ..models import MarginAccountNewOtoResponse
from ..models import MarginAccountNewOtocoResponse
from ..models import MarginManualLiquidationResponse
from ..models import QueryCurrentMarginOrderCountUsageResponse
from ..models import QueryMarginAccountsAllOcoResponse
from ..models import QueryMarginAccountsAllOrdersResponse
from ..models import QueryMarginAccountsOcoResponse
from ..models import QueryMarginAccountsOpenOcoResponse
from ..models import QueryMarginAccountsOpenOrdersResponse
from ..models import QueryMarginAccountsOrderResponse
from ..models import QueryMarginAccountsTradeListResponse
from ..models import QuerySpecialKeyResponse
from ..models import QuerySpecialKeyListResponse


from ..models import MarginAccountNewOcoSideEnum
from ..models import MarginAccountNewOcoNewOrderRespTypeEnum
from ..models import MarginAccountNewOrderSideEnum
from ..models import MarginAccountNewOrderNewOrderRespTypeEnum
from ..models import MarginAccountNewOrderTimeInForceEnum
from ..models import MarginAccountNewOtoNewOrderRespTypeEnum
from ..models import MarginAccountNewOtocoNewOrderRespTypeEnum


class TradeApi:
    """API Client for TradeApi endpoints."""

    def __init__(
        self,
        configuration: ConfigurationRestAPI = None,
        session: Session = None,
        signer: Signers = None,
    ) -> None:
        self._configuration = configuration
        self._session = session
        self._signer = signer

    def create_special_key(
        self,
        api_name: Union[str, None],
        symbol: Optional[str] = None,
        ip: Optional[str] = None,
        public_key: Optional[str] = None,
        permission_mode: Optional[str] = None,
        recv_window: Optional[int] = None,
    ) -> ApiResponse[CreateSpecialKeyResponse]:
        """
                Create Special Key(Low-Latency Trading)(TRADE)
                POST /sapi/v1/margin/apiKey
                https://developers.binance.com/docs/margin_trading/trade/Create-Special-Key-of-Low-Latency-Trading

                - Binance Margin offers low-latency trading through a [special key](https://www.binance.com/en/support/faq/frequently-asked-questions-on-margin-special-api-key-3208663e900d4d2e9fec4140e1832f4e), available exclusively to users with VIP level 4 or higher.
        - If you are VIP level 3 or below, please contact your VIP manager for eligibility criterias.**

        **Supported Products:**

        - Cross Margin
        - Isolated Margin
        - Portfolio Margin Pro
        - Cross Margin Pro (Additional agreement required and subject to meeting eligibility criteria)

        **Unsupported Products:**

        - Portfolio Margin

        We support several types of API keys:

        * Ed25519 (recommended)
        * HMAC
        * RSA

        We recommend to **use Ed25519 API keys** as it should provide the best performance and security out of all supported key types. We accept PKCS#8 (BEGIN PUBLIC KEY). For how to generate an RSA key pair to send API requests on Binance. Please refer to the document below [FAQ](https://www.binance.com/en/support/faq/how-to-generate-an-rsa-key-pair-to-send-api-requests-on-binance-2b79728f331e43079b27440d9d15c5db) .

        Weight: 1(UID)

                Args:
                    api_name (Union[str, None]):
                    symbol (Optional[str] = None): isolated margin pair
                    ip (Optional[str] = None): Can be added in batches, separated by commas. Max 30 for an API key
                    public_key (Optional[str] = None): 1. If publicKey is inputted it will create an RSA or Ed25519 key. <br />2. Need to be encoded to URL-encoded format
                    permission_mode (Optional[str] = None): This parameter is only for the Ed25519 API key, and does not effact for other encryption methods. The value can be TRADE (TRADE for all permissions) or READ (READ for USER_DATA, FIX_API_READ_ONLY). The default value is TRADE.
                    recv_window (Optional[int] = None): No more than 60000

                Returns:
                    ApiResponse[CreateSpecialKeyResponse]

                Raises:
                    RequiredError: If a required parameter is missing.

        """

        if api_name is None:
            raise RequiredError(
                field="api_name", error_message="Missing required parameter 'api_name'"
            )

        body = {}
        payload = {
            "api_name": api_name,
            "symbol": symbol,
            "ip": ip,
            "public_key": public_key,
            "permission_mode": permission_mode,
            "recv_window": recv_window,
        }

        return send_request(
            self._session,
            self._configuration,
            method="POST",
            path="/sapi/v1/margin/apiKey",
            payload=payload,
            body=body,
            time_unit=self._configuration.time_unit,
            response_model=CreateSpecialKeyResponse,
            is_signed=True,
            signer=self._signer,
        )

    def delete_special_key(
        self,
        api_name: Optional[str] = None,
        symbol: Optional[str] = None,
        recv_window: Optional[int] = None,
    ) -> ApiResponse[None]:
        """
                Delete Special Key(Low-Latency Trading)(TRADE)
                DELETE /sapi/v1/margin/apiKey
                https://developers.binance.com/docs/margin_trading/trade/Delete-Special-Key-of-Low-Latency-Trading

                This only applies to Special Key for Low Latency Trading.

        If apiKey is given, apiName will be ignored. If apiName is given with no apiKey, all apikeys with given apiName will be deleted.

        You need to enable Permits “Enable Spot & Margin Trading” option for the API Key which requests this endpoint.

        Weight: 1(UID)

                Args:
                    api_name (Optional[str] = None):
                    symbol (Optional[str] = None): isolated margin pair
                    recv_window (Optional[int] = None): No more than 60000

                Returns:
                    ApiResponse[None]

                Raises:
                    RequiredError: If a required parameter is missing.

        """

        body = {}
        payload = {"api_name": api_name, "symbol": symbol, "recv_window": recv_window}

        return send_request(
            self._session,
            self._configuration,
            method="DELETE",
            path="/sapi/v1/margin/apiKey",
            payload=payload,
            body=body,
            time_unit=self._configuration.time_unit,
            is_signed=True,
            signer=self._signer,
        )

    def edit_ip_for_special_key(
        self,
        ip: Union[str, None],
        symbol: Optional[str] = None,
        recv_window: Optional[int] = None,
    ) -> ApiResponse[None]:
        """
                Edit ip for Special Key(Low-Latency Trading)(TRADE)
                PUT /sapi/v1/margin/apiKey/ip
                https://developers.binance.com/docs/margin_trading/trade/Edit-ip-for-Special-Key-of-Low-Latency-Trading

                Edit ip restriction. This only applies to Special Key for Low Latency Trading.

        You need to enable Permits “Enable Spot & Margin Trading” option for the API Key which requests this endpoint.

        Weight: 1(UID)

                Args:
                    ip (Union[str, None]): Can be added in batches, separated by commas. Max 30 for an API key
                    symbol (Optional[str] = None): isolated margin pair
                    recv_window (Optional[int] = None): No more than 60000

                Returns:
                    ApiResponse[None]

                Raises:
                    RequiredError: If a required parameter is missing.

        """

        if ip is None:
            raise RequiredError(
                field="ip", error_message="Missing required parameter 'ip'"
            )

        body = {}
        payload = {"ip": ip, "symbol": symbol, "recv_window": recv_window}

        return send_request(
            self._session,
            self._configuration,
            method="PUT",
            path="/sapi/v1/margin/apiKey/ip",
            payload=payload,
            body=body,
            time_unit=self._configuration.time_unit,
            is_signed=True,
            signer=self._signer,
        )

    def get_force_liquidation_record(
        self,
        start_time: Optional[int] = None,
        end_time: Optional[int] = None,
        isolated_symbol: Optional[str] = None,
        current: Optional[int] = None,
        size: Optional[int] = None,
        recv_window: Optional[int] = None,
    ) -> ApiResponse[GetForceLiquidationRecordResponse]:
        """
                Get Force Liquidation Record (USER_DATA)
                GET /sapi/v1/margin/forceLiquidationRec
                https://developers.binance.com/docs/margin_trading/trade/Get-Force-Liquidation-Record

                Get Force Liquidation Record

        * Response in descending order

        Weight: 1(IP)

                Args:
                    start_time (Optional[int] = None): 只支持查询最近90天的数据
                    end_time (Optional[int] = None):
                    isolated_symbol (Optional[str] = None): isolated symbol
                    current (Optional[int] = None): Currently querying page. Start from 1. Default:1
                    size (Optional[int] = None): Default:10 Max:100
                    recv_window (Optional[int] = None): No more than 60000

                Returns:
                    ApiResponse[GetForceLiquidationRecordResponse]

                Raises:
                    RequiredError: If a required parameter is missing.

        """

        body = {}
        payload = {
            "start_time": start_time,
            "end_time": end_time,
            "isolated_symbol": isolated_symbol,
            "current": current,
            "size": size,
            "recv_window": recv_window,
        }

        return send_request(
            self._session,
            self._configuration,
            method="GET",
            path="/sapi/v1/margin/forceLiquidationRec",
            payload=payload,
            body=body,
            time_unit=self._configuration.time_unit,
            response_model=GetForceLiquidationRecordResponse,
            is_signed=True,
            signer=self._signer,
        )

    def get_small_liability_exchange_coin_list(
        self,
        recv_window: Optional[int] = None,
    ) -> ApiResponse[GetSmallLiabilityExchangeCoinListResponse]:
        """
                Get Small Liability Exchange Coin List (USER_DATA)
                GET /sapi/v1/margin/exchange-small-liability
                https://developers.binance.com/docs/margin_trading/trade/Get-Small-Liability-Exchange-Coin-List

                Query the coins which can be small liability exchange

        Weight: 100

                Args:
                    recv_window (Optional[int] = None): No more than 60000

                Returns:
                    ApiResponse[GetSmallLiabilityExchangeCoinListResponse]

                Raises:
                    RequiredError: If a required parameter is missing.

        """

        body = {}
        payload = {"recv_window": recv_window}

        return send_request(
            self._session,
            self._configuration,
            method="GET",
            path="/sapi/v1/margin/exchange-small-liability",
            payload=payload,
            body=body,
            time_unit=self._configuration.time_unit,
            response_model=GetSmallLiabilityExchangeCoinListResponse,
            is_signed=True,
            signer=self._signer,
        )

    def get_small_liability_exchange_history(
        self,
        current: Union[int, None],
        size: Union[int, None],
        start_time: Optional[int] = None,
        end_time: Optional[int] = None,
        recv_window: Optional[int] = None,
    ) -> ApiResponse[GetSmallLiabilityExchangeHistoryResponse]:
        """
                Get Small Liability Exchange History (USER_DATA)
                GET /sapi/v1/margin/exchange-small-liability-history
                https://developers.binance.com/docs/margin_trading/trade/Get-Small-Liability-Exchange-History

                Get Small liability Exchange History

        Weight: 100(UID)

                Args:
                    current (Union[int, None]): Currently querying page. Start from 1. Default:1
                    size (Union[int, None]): Default:10, Max:100
                    start_time (Optional[int] = None): 只支持查询最近90天的数据
                    end_time (Optional[int] = None):
                    recv_window (Optional[int] = None): No more than 60000

                Returns:
                    ApiResponse[GetSmallLiabilityExchangeHistoryResponse]

                Raises:
                    RequiredError: If a required parameter is missing.

        """

        if current is None:
            raise RequiredError(
                field="current", error_message="Missing required parameter 'current'"
            )
        if size is None:
            raise RequiredError(
                field="size", error_message="Missing required parameter 'size'"
            )

        body = {}
        payload = {
            "current": current,
            "size": size,
            "start_time": start_time,
            "end_time": end_time,
            "recv_window": recv_window,
        }

        return send_request(
            self._session,
            self._configuration,
            method="GET",
            path="/sapi/v1/margin/exchange-small-liability-history",
            payload=payload,
            body=body,
            time_unit=self._configuration.time_unit,
            response_model=GetSmallLiabilityExchangeHistoryResponse,
            is_signed=True,
            signer=self._signer,
        )

    def margin_account_cancel_all_open_orders_on_a_symbol(
        self,
        symbol: Union[str, None],
        is_isolated: Optional[str] = None,
        recv_window: Optional[int] = None,
    ) -> ApiResponse[MarginAccountCancelAllOpenOrdersOnASymbolResponse]:
        """
                Margin Account Cancel all Open Orders on a Symbol (TRADE)
                DELETE /sapi/v1/margin/openOrders
                https://developers.binance.com/docs/margin_trading/trade/Margin-Account-Cancel-All-Open-Orders

                Cancels all active orders on a symbol for margin account.<br></br>
        This includes OCO orders.

        Weight: 1

                Args:
                    symbol (Union[str, None]):
                    is_isolated (Optional[str] = None): for isolated margin or not, "TRUE", "FALSE"，default "FALSE"
                    recv_window (Optional[int] = None): No more than 60000

                Returns:
                    ApiResponse[MarginAccountCancelAllOpenOrdersOnASymbolResponse]

                Raises:
                    RequiredError: If a required parameter is missing.

        """

        if symbol is None:
            raise RequiredError(
                field="symbol", error_message="Missing required parameter 'symbol'"
            )

        body = {}
        payload = {
            "symbol": symbol,
            "is_isolated": is_isolated,
            "recv_window": recv_window,
        }

        return send_request(
            self._session,
            self._configuration,
            method="DELETE",
            path="/sapi/v1/margin/openOrders",
            payload=payload,
            body=body,
            time_unit=self._configuration.time_unit,
            response_model=MarginAccountCancelAllOpenOrdersOnASymbolResponse,
            is_signed=True,
            signer=self._signer,
        )

    def margin_account_cancel_oco(
        self,
        symbol: Union[str, None],
        is_isolated: Optional[str] = None,
        order_list_id: Optional[int] = None,
        list_client_order_id: Optional[str] = None,
        new_client_order_id: Optional[str] = None,
        recv_window: Optional[int] = None,
    ) -> ApiResponse[MarginAccountCancelOcoResponse]:
        """
                Margin Account Cancel OCO (TRADE)
                DELETE /sapi/v1/margin/orderList
                https://developers.binance.com/docs/margin_trading/trade/Margin-Account-Cancel-OCO

                Cancel an entire Order List for a margin account.

        * Canceling an individual leg will cancel the entire OCO

        Weight: 1(UID)

                Args:
                    symbol (Union[str, None]):
                    is_isolated (Optional[str] = None): for isolated margin or not, "TRUE", "FALSE"，default "FALSE"
                    order_list_id (Optional[int] = None): Either `orderListId` or `listClientOrderId` must be provided
                    list_client_order_id (Optional[str] = None): Either `orderListId` or `listClientOrderId` must be provided
                    new_client_order_id (Optional[str] = None): Used to uniquely identify this cancel. Automatically generated by default
                    recv_window (Optional[int] = None): No more than 60000

                Returns:
                    ApiResponse[MarginAccountCancelOcoResponse]

                Raises:
                    RequiredError: If a required parameter is missing.

        """

        if symbol is None:
            raise RequiredError(
                field="symbol", error_message="Missing required parameter 'symbol'"
            )

        body = {}
        payload = {
            "symbol": symbol,
            "is_isolated": is_isolated,
            "order_list_id": order_list_id,
            "list_client_order_id": list_client_order_id,
            "new_client_order_id": new_client_order_id,
            "recv_window": recv_window,
        }

        return send_request(
            self._session,
            self._configuration,
            method="DELETE",
            path="/sapi/v1/margin/orderList",
            payload=payload,
            body=body,
            time_unit=self._configuration.time_unit,
            response_model=MarginAccountCancelOcoResponse,
            is_signed=True,
            signer=self._signer,
        )

    def margin_account_cancel_order(
        self,
        symbol: Union[str, None],
        is_isolated: Optional[str] = None,
        order_id: Optional[int] = None,
        orig_client_order_id: Optional[str] = None,
        new_client_order_id: Optional[str] = None,
        recv_window: Optional[int] = None,
    ) -> ApiResponse[MarginAccountCancelOrderResponse]:
        """
                Margin Account Cancel Order (TRADE)
                DELETE /sapi/v1/margin/order
                https://developers.binance.com/docs/margin_trading/trade/Margin-Account-Cancel-Order

                Cancel an active order for margin account.

        * Either orderId or origClientOrderId must be sent.

        Weight: 10(IP)

                Args:
                    symbol (Union[str, None]):
                    is_isolated (Optional[str] = None): for isolated margin or not, "TRUE", "FALSE"，default "FALSE"
                    order_id (Optional[int] = None):
                    orig_client_order_id (Optional[str] = None):
                    new_client_order_id (Optional[str] = None): Used to uniquely identify this cancel. Automatically generated by default
                    recv_window (Optional[int] = None): No more than 60000

                Returns:
                    ApiResponse[MarginAccountCancelOrderResponse]

                Raises:
                    RequiredError: If a required parameter is missing.

        """

        if symbol is None:
            raise RequiredError(
                field="symbol", error_message="Missing required parameter 'symbol'"
            )

        body = {}
        payload = {
            "symbol": symbol,
            "is_isolated": is_isolated,
            "order_id": order_id,
            "orig_client_order_id": orig_client_order_id,
            "new_client_order_id": new_client_order_id,
            "recv_window": recv_window,
        }

        return send_request(
            self._session,
            self._configuration,
            method="DELETE",
            path="/sapi/v1/margin/order",
            payload=payload,
            body=body,
            time_unit=self._configuration.time_unit,
            response_model=MarginAccountCancelOrderResponse,
            is_signed=True,
            signer=self._signer,
        )

    def margin_account_new_oco(
        self,
        symbol: Union[str, None],
        side: Union[MarginAccountNewOcoSideEnum, None],
        quantity: Union[float, None],
        price: Union[float, None],
        stop_price: Union[float, None],
        is_isolated: Optional[str] = None,
        list_client_order_id: Optional[str] = None,
        limit_client_order_id: Optional[str] = None,
        limit_iceberg_qty: Optional[float] = None,
        stop_client_order_id: Optional[str] = None,
        stop_limit_price: Optional[float] = None,
        stop_iceberg_qty: Optional[float] = None,
        stop_limit_time_in_force: Optional[str] = None,
        new_order_resp_type: Optional[MarginAccountNewOcoNewOrderRespTypeEnum] = None,
        side_effect_type: Optional[str] = None,
        self_trade_prevention_mode: Optional[str] = None,
        auto_repay_at_cancel: Optional[bool] = None,
        recv_window: Optional[int] = None,
    ) -> ApiResponse[MarginAccountNewOcoResponse]:
        """
                Margin Account New OCO (TRADE)
                POST /sapi/v1/margin/order/oco
                https://developers.binance.com/docs/margin_trading/trade/Margin-Account-New-OCO

                Send in a new OCO for a margin account

        * autoRepayAtCancel is suggested to set as “FALSE” to keep liability unrepaid under high frequent new order/cancel order execution

        Weight: 6(UID)

                Args:
                    symbol (Union[str, None]):
                    side (Union[MarginAccountNewOcoSideEnum, None]):
                    quantity (Union[float, None]):
                    price (Union[float, None]):
                    stop_price (Union[float, None]):
                    is_isolated (Optional[str] = None): for isolated margin or not, "TRUE", "FALSE"，default "FALSE"
                    list_client_order_id (Optional[str] = None): Either `orderListId` or `listClientOrderId` must be provided
                    limit_client_order_id (Optional[str] = None): A unique Id for the limit order
                    limit_iceberg_qty (Optional[float] = None):
                    stop_client_order_id (Optional[str] = None): A unique Id for the stop loss/stop loss limit leg
                    stop_limit_price (Optional[float] = None): If provided, `stopLimitTimeInForce` is required.
                    stop_iceberg_qty (Optional[float] = None):
                    stop_limit_time_in_force (Optional[str] = None): Valid values are `GTC`/`FOK`/`IOC`
                    new_order_resp_type (Optional[MarginAccountNewOcoNewOrderRespTypeEnum] = None): Set the response JSON. ACK, RESULT, or FULL; MARKET and LIMIT order types default to FULL, all other orders default to ACK.
                    side_effect_type (Optional[str] = None): NO_SIDE_EFFECT, MARGIN_BUY, AUTO_REPAY,AUTO_BORROW_REPAY; default NO_SIDE_EFFECT. More info in [FAQ](https://www.binance.com/en/support/faq/how-to-use-the-sideeffecttype-parameter-with-the-margin-order-endpoints-f9fc51cda1984bf08b95e0d96c4570bc)
                    self_trade_prevention_mode (Optional[str] = None): The allowed enums is dependent on what is configured on the symbol. The possible supported values are EXPIRE_TAKER, EXPIRE_MAKER, EXPIRE_BOTH, NONE
                    auto_repay_at_cancel (Optional[bool] = None): Only when MARGIN_BUY or AUTO_BORROW_REPAY order takes effect, true means that the debt generated by the order needs to be repay after the order is cancelled. The default is true
                    recv_window (Optional[int] = None): No more than 60000

                Returns:
                    ApiResponse[MarginAccountNewOcoResponse]

                Raises:
                    RequiredError: If a required parameter is missing.

        """

        if symbol is None:
            raise RequiredError(
                field="symbol", error_message="Missing required parameter 'symbol'"
            )
        if side is None:
            raise RequiredError(
                field="side", error_message="Missing required parameter 'side'"
            )
        if quantity is None:
            raise RequiredError(
                field="quantity", error_message="Missing required parameter 'quantity'"
            )
        if price is None:
            raise RequiredError(
                field="price", error_message="Missing required parameter 'price'"
            )
        if stop_price is None:
            raise RequiredError(
                field="stop_price",
                error_message="Missing required parameter 'stop_price'",
            )

        body = {}
        payload = {
            "symbol": symbol,
            "side": side,
            "quantity": quantity,
            "price": price,
            "stop_price": stop_price,
            "is_isolated": is_isolated,
            "list_client_order_id": list_client_order_id,
            "limit_client_order_id": limit_client_order_id,
            "limit_iceberg_qty": limit_iceberg_qty,
            "stop_client_order_id": stop_client_order_id,
            "stop_limit_price": stop_limit_price,
            "stop_iceberg_qty": stop_iceberg_qty,
            "stop_limit_time_in_force": stop_limit_time_in_force,
            "new_order_resp_type": new_order_resp_type,
            "side_effect_type": side_effect_type,
            "self_trade_prevention_mode": self_trade_prevention_mode,
            "auto_repay_at_cancel": auto_repay_at_cancel,
            "recv_window": recv_window,
        }

        return send_request(
            self._session,
            self._configuration,
            method="POST",
            path="/sapi/v1/margin/order/oco",
            payload=payload,
            body=body,
            time_unit=self._configuration.time_unit,
            response_model=MarginAccountNewOcoResponse,
            is_signed=True,
            signer=self._signer,
        )

    def margin_account_new_order(
        self,
        symbol: Union[str, None],
        side: Union[MarginAccountNewOrderSideEnum, None],
        type: Union[str, None],
        is_isolated: Optional[str] = None,
        quantity: Optional[float] = None,
        quote_order_qty: Optional[float] = None,
        price: Optional[float] = None,
        stop_price: Optional[float] = None,
        new_client_order_id: Optional[str] = None,
        iceberg_qty: Optional[float] = None,
        new_order_resp_type: Optional[MarginAccountNewOrderNewOrderRespTypeEnum] = None,
        side_effect_type: Optional[str] = None,
        time_in_force: Optional[MarginAccountNewOrderTimeInForceEnum] = None,
        self_trade_prevention_mode: Optional[str] = None,
        auto_repay_at_cancel: Optional[bool] = None,
        recv_window: Optional[int] = None,
    ) -> ApiResponse[MarginAccountNewOrderResponse]:
        """
                Margin Account New Order (TRADE)
                POST /sapi/v1/margin/order
                https://developers.binance.com/docs/margin_trading/trade/Margin-Account-New-Order

                Post a new order for margin account.

        * autoRepayAtCancel is suggested to set as “FALSE” to keep liability unrepaid under high frequent new order/cancel order execution

        Weight: 6(UID)

                Args:
                    symbol (Union[str, None]):
                    side (Union[MarginAccountNewOrderSideEnum, None]):
                    type (Union[str, None]): `MARGIN`,`ISOLATED`
                    is_isolated (Optional[str] = None): for isolated margin or not, "TRUE", "FALSE"，default "FALSE"
                    quantity (Optional[float] = None):
                    quote_order_qty (Optional[float] = None):
                    price (Optional[float] = None):
                    stop_price (Optional[float] = None): Used with `STOP_LOSS`, `STOP_LOSS_LIMIT`, `TAKE_PROFIT`, and `TAKE_PROFIT_LIMIT` orders.
                    new_client_order_id (Optional[str] = None): Used to uniquely identify this cancel. Automatically generated by default
                    iceberg_qty (Optional[float] = None): Used with `LIMIT`, `STOP_LOSS_LIMIT`, and `TAKE_PROFIT_LIMIT` to create an iceberg order.
                    new_order_resp_type (Optional[MarginAccountNewOrderNewOrderRespTypeEnum] = None): Set the response JSON. ACK, RESULT, or FULL; MARKET and LIMIT order types default to FULL, all other orders default to ACK.
                    side_effect_type (Optional[str] = None): NO_SIDE_EFFECT, MARGIN_BUY, AUTO_REPAY,AUTO_BORROW_REPAY; default NO_SIDE_EFFECT. More info in [FAQ](https://www.binance.com/en/support/faq/how-to-use-the-sideeffecttype-parameter-with-the-margin-order-endpoints-f9fc51cda1984bf08b95e0d96c4570bc)
                    time_in_force (Optional[MarginAccountNewOrderTimeInForceEnum] = None): GTC,IOC,FOK
                    self_trade_prevention_mode (Optional[str] = None): The allowed enums is dependent on what is configured on the symbol. The possible supported values are EXPIRE_TAKER, EXPIRE_MAKER, EXPIRE_BOTH, NONE
                    auto_repay_at_cancel (Optional[bool] = None): Only when MARGIN_BUY or AUTO_BORROW_REPAY order takes effect, true means that the debt generated by the order needs to be repay after the order is cancelled. The default is true
                    recv_window (Optional[int] = None): No more than 60000

                Returns:
                    ApiResponse[MarginAccountNewOrderResponse]

                Raises:
                    RequiredError: If a required parameter is missing.

        """

        if symbol is None:
            raise RequiredError(
                field="symbol", error_message="Missing required parameter 'symbol'"
            )
        if side is None:
            raise RequiredError(
                field="side", error_message="Missing required parameter 'side'"
            )
        if type is None:
            raise RequiredError(
                field="type", error_message="Missing required parameter 'type'"
            )

        body = {}
        payload = {
            "symbol": symbol,
            "side": side,
            "type": type,
            "is_isolated": is_isolated,
            "quantity": quantity,
            "quote_order_qty": quote_order_qty,
            "price": price,
            "stop_price": stop_price,
            "new_client_order_id": new_client_order_id,
            "iceberg_qty": iceberg_qty,
            "new_order_resp_type": new_order_resp_type,
            "side_effect_type": side_effect_type,
            "time_in_force": time_in_force,
            "self_trade_prevention_mode": self_trade_prevention_mode,
            "auto_repay_at_cancel": auto_repay_at_cancel,
            "recv_window": recv_window,
        }

        return send_request(
            self._session,
            self._configuration,
            method="POST",
            path="/sapi/v1/margin/order",
            payload=payload,
            body=body,
            time_unit=self._configuration.time_unit,
            response_model=MarginAccountNewOrderResponse,
            is_signed=True,
