"""
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 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 GetFutureHourlyInterestRateResponse
from ..models import GetInterestHistoryResponse
from ..models import MarginAccountBorrowRepayResponse
from ..models import QueryBorrowRepayRecordsInMarginAccountResponse
from ..models import QueryMarginInterestRateHistoryResponse
from ..models import QueryMaxBorrowResponse


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

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

    def get_future_hourly_interest_rate(
        self,
        assets: Union[str, None],
        is_isolated: Union[bool, None],
    ) -> ApiResponse[GetFutureHourlyInterestRateResponse]:
        """
                Get future hourly interest rate (USER_DATA)
                GET /sapi/v1/margin/next-hourly-interest-rate
                https://developers.binance.com/docs/margin_trading/borrow-and-repay/Get-a-future-hourly-interest-rate

                Get future hourly interest rate

        Weight: 100

                Args:
                    assets (Union[str, None]): List of assets, separated by commas, up to 20
                    is_isolated (Union[bool, None]): for isolated margin or not, "TRUE", "FALSE"

                Returns:
                    ApiResponse[GetFutureHourlyInterestRateResponse]

                Raises:
                    RequiredError: If a required parameter is missing.

        """

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

        body = {}
        payload = {"assets": assets, "is_isolated": is_isolated}

        return send_request(
            self._session,
            self._configuration,
            method="GET",
            path="/sapi/v1/margin/next-hourly-interest-rate",
            payload=payload,
            body=body,
            time_unit=self._configuration.time_unit,
            response_model=GetFutureHourlyInterestRateResponse,
            is_signed=True,
            signer=self._signer,
        )

    def get_interest_history(
        self,
        asset: Optional[str] = None,
        isolated_symbol: Optional[str] = None,
        start_time: Optional[int] = None,
        end_time: Optional[int] = None,
        current: Optional[int] = None,
        size: Optional[int] = None,
        recv_window: Optional[int] = None,
    ) -> ApiResponse[GetInterestHistoryResponse]:
        """
                Get Interest History (USER_DATA)
                GET /sapi/v1/margin/interestHistory
                https://developers.binance.com/docs/margin_trading/borrow-and-repay/Get-Interest-History

                Get Interest History

        * Response in descending order
        * If isolatedSymbol is not sent, crossed margin data will be returned
        * The max interval between `startTime` and `endTime` is 30 days.  It is a MUST to ensure data correctness.
        * If `startTime`and `endTime` not sent, return records of the last 7 days by default.
        * If `startTime` is sent and `endTime` is not sent, return records of [max(`startTime`, now-30d), now].
        * If `startTime` is not sent and `endTime` is sent, return records of [`endTime`-7, `endTime`]
        * `type` in response has 4 enums:
        * `PERIODIC` interest charged per hour
        * `ON_BORROW` first interest charged on borrow
        * `PERIODIC_CONVERTED` interest charged per hour converted into BNB
        * `ON_BORROW_CONVERTED` first interest charged on borrow converted into BNB
        * `PORTFOLIO` interest charged daily on the portfolio margin negative balance

        Weight: 1(IP)

                Args:
                    asset (Optional[str] = None):
                    isolated_symbol (Optional[str] = None): isolated symbol
                    start_time (Optional[int] = None): 只支持查询最近90天的数据
                    end_time (Optional[int] = None):
                    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[GetInterestHistoryResponse]

                Raises:
                    RequiredError: If a required parameter is missing.

        """

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

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

    def margin_account_borrow_repay(
        self,
        asset: Union[str, None],
        is_isolated: Union[str, None],
        symbol: Union[str, None],
        amount: Union[str, None],
        type: Union[str, None],
        recv_window: Optional[int] = None,
    ) -> ApiResponse[MarginAccountBorrowRepayResponse]:
        """
                Margin account borrow/repay(MARGIN)
                POST /sapi/v1/margin/borrow-repay
                https://developers.binance.com/docs/margin_trading/borrow-and-repay/Margin-account-borrow-repay

                Margin account borrow/repay(MARGIN)

        Weight: 1500

                Args:
                    asset (Union[str, None]):
                    is_isolated (Union[str, None]): `TRUE` for Isolated Margin, `FALSE` for Cross Margin, Default `FALSE`
                    symbol (Union[str, None]):
                    amount (Union[str, None]):
                    type (Union[str, None]): `MARGIN`,`ISOLATED`
                    recv_window (Optional[int] = None): No more than 60000

                Returns:
                    ApiResponse[MarginAccountBorrowRepayResponse]

                Raises:
                    RequiredError: If a required parameter is missing.

        """

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

        body = {}
        payload = {
            "asset": asset,
            "is_isolated": is_isolated,
            "symbol": symbol,
            "amount": amount,
            "type": type,
            "recv_window": recv_window,
        }

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

    def query_borrow_repay_records_in_margin_account(
        self,
        type: Union[str, None],
        asset: Optional[str] = None,
        isolated_symbol: Optional[str] = None,
        tx_id: Optional[int] = None,
        start_time: Optional[int] = None,
        end_time: Optional[int] = None,
        current: Optional[int] = None,
        size: Optional[int] = None,
        recv_window: Optional[int] = None,
    ) -> ApiResponse[QueryBorrowRepayRecordsInMarginAccountResponse]:
        """
                Query borrow/repay records in Margin account(USER_DATA)
                GET /sapi/v1/margin/borrow-repay
                https://developers.binance.com/docs/margin_trading/borrow-and-repay/Query-Borrow-Repay

                Query borrow/repay records in Margin account

        * `txId` or `startTime` must be sent. `txId` takes precedence.
        * If an asset is sent, data within 30 days before `endTime`; If an asset is not sent, data within 7 days before `endTime`
        * If neither `startTime` nor `endTime` is sent, the recent 7-day data will be returned.
        * `startTime` set as `endTime` - 7days by default, `endTime` set as current time by default

        Weight: 10(IP)

                Args:
                    type (Union[str, None]): `MARGIN`,`ISOLATED`
                    asset (Optional[str] = None):
                    isolated_symbol (Optional[str] = None): isolated symbol
                    tx_id (Optional[int] = None): `tranId` in `POST /sapi/v1/margin/loan`
                    start_time (Optional[int] = None): 只支持查询最近90天的数据
                    end_time (Optional[int] = None):
                    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[QueryBorrowRepayRecordsInMarginAccountResponse]

                Raises:
                    RequiredError: If a required parameter is missing.

        """

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

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

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

    def query_margin_interest_rate_history(
        self,
        asset: Union[str, None],
        vip_level: Optional[int] = None,
        start_time: Optional[int] = None,
        end_time: Optional[int] = None,
        recv_window: Optional[int] = None,
    ) -> ApiResponse[QueryMarginInterestRateHistoryResponse]:
        """
                Query Margin Interest Rate History (USER_DATA)
                GET /sapi/v1/margin/interestRateHistory
                https://developers.binance.com/docs/margin_trading/borrow-and-repay/Query-Margin-Interest-Rate-History

                Query Margin Interest Rate History

        Weight: 1(IP)

                Args:
                    asset (Union[str, None]):
                    vip_level (Optional[int] = None): User's current specific margin data will be returned if vipLevel is omitted
                    start_time (Optional[int] = None): 只支持查询最近90天的数据
                    end_time (Optional[int] = None):
                    recv_window (Optional[int] = None): No more than 60000

                Returns:
                    ApiResponse[QueryMarginInterestRateHistoryResponse]

                Raises:
                    RequiredError: If a required parameter is missing.

        """

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

        body = {}
        payload = {
            "asset": asset,
            "vip_level": vip_level,
            "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/interestRateHistory",
            payload=payload,
            body=body,
            time_unit=self._configuration.time_unit,
            response_model=QueryMarginInterestRateHistoryResponse,
            is_signed=True,
            signer=self._signer,
        )

    def query_max_borrow(
        self,
        asset: Union[str, None],
        isolated_symbol: Optional[str] = None,
        recv_window: Optional[int] = None,
    ) -> ApiResponse[QueryMaxBorrowResponse]:
        """
                Query Max Borrow (USER_DATA)
                GET /sapi/v1/margin/maxBorrowable
                https://developers.binance.com/docs/margin_trading/borrow-and-repay/Query-Max-Borrow

                Query Max Borrow

        * If isolatedSymbol is not sent, crossed margin data will be sent.
        * `borrowLimit` is also available from [https://www.binance.com/en/margin-fee](https://www.binance.com/en/margin-fee)

        Weight: 50(IP)

                Args:
                    asset (Union[str, None]):
                    isolated_symbol (Optional[str] = None): isolated symbol
                    recv_window (Optional[int] = None): No more than 60000

                Returns:
                    ApiResponse[QueryMaxBorrowResponse]

                Raises:
                    RequiredError: If a required parameter is missing.

        """

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

        body = {}
        payload = {
            "asset": asset,
            "isolated_symbol": isolated_symbol,
            "recv_window": recv_window,
        }

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