"""
Binance Derivatives Trading USDS Futures WebSocket Market Streams

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

Do not edit the class manually.
"""

from pydantic import BaseModel
from typing import Callable, Optional, TypeVar, Union

from binance_common.configuration import ConfigurationWebSocketStreams
from binance_common.websocket import (
    WebSocketStreamBase,
    WebSocketConnection,
    RequestStreamHandle,
    RequestStream,
)

from .models import UserDataStreamEventsResponse


from .streams.websocket_market_streams_api import WebsocketMarketStreamsApi


T = TypeVar("T", bound=BaseModel)


class DerivativesTradingUsdsFuturesWebSocketStreams(WebSocketStreamBase):
    def __init__(
        self,
        configuration: ConfigurationWebSocketStreams,
    ) -> None:

        super().__init__(configuration)
        self.configuration = configuration

        self._websocketMarketStreamsApi = WebsocketMarketStreamsApi(self)

    async def ping_server(self, connection: WebSocketConnection):
        """Sends a ping message to the WebSocket server to check the connection status.

        Args:
            connection (WebSocketConnection): The WebSocket connection to send the ping message to.
        """

        if self.session:
            await super().ping_ws_stream(connection=connection)
        else:
            raise ValueError("WebSocket session is not initialized.")

    async def subscribe(self, streams, response_model: Optional[T] = None):
        """Subscribes to the specified WebSocket streams.

        Args:
            streams (list): A list of WebSocket streams to subscribe to.
            response_model (Optional[T]): The Pydantic model to validate the response against.
        """

        await super().subscribe(streams, response_model=response_model)

    async def unsubscribe(self, streams):
        """Unsubscribes from the specified WebSocket streams.

        Args:
            streams (list): A list of WebSocket streams to unsubscribe from.
        """

        await super().unsubscribe(streams)

    def on(self, event: str, callback: Callable[[T], None], stream: str):
        """Registers a callback function for a specific WebSocket event.

        Args:
            event (str): The event type to listen for (e.g., 'message', 'error').
            callback (Callable[[T], None]): The callback function to be called when the event occurs.
            stream (str): The specific WebSocket stream to listen to.
        """

        super().on(event, callback, stream)

    async def list_subscribe(self) -> dict:
        """Lists all currently subscribed WebSocket streams.

        Returns:
            dict: A dictionary containing the current subscriptions.
        """

        return await super().list_subscribe()

    async def close_connection(
        self, connection: WebSocketConnection = None, close_session: bool = True
    ):
        """Closes the WebSocket connection and optionally the session.

        Args:
            connection (WebSocketConnection, optional): The WebSocket connection to close. If None, the current session's connection is used.
            close_session (bool, optional): Whether to close the session after closing the connection. Defaults to True.
        """

        await super().close_connection(connection, close_session)

    async def user_data(self, listenKey: str) -> RequestStreamHandle:
        """Subscribe to User Data Stream (USER_STREAM)

        Args:
            listenKey (str): The listen key for the user data stream.
        Returns:
            RequestStreamHandle: An instance of RequestStream that provides the on() and unsubscribe() methods.
        """

        return await RequestStream(
            self, listenKey, response_model=UserDataStreamEventsResponse
        )

    async def aggregate_trade_streams(
        self,
        symbol: Union[str, None],
        id: Optional[str] = None,
    ) -> RequestStreamHandle:
        r"""
                Aggregate Trade Streams

                The Aggregate Trade Streams push market trade information that is aggregated for fills with same price and taking side every 100 milliseconds. Only market trades will be aggregated, which means the insurance fund trades and ADL trades won't be aggregated.


        Retail Price Improvement(RPI) orders are aggregated and without special tags to be distinguished.

        Update Speed: 100ms

                Args:
                    symbol (Union[str, None]): The symbol parameter
                    id (Optional[str] = None): Unique WebSocket request ID.

                Returns:
                    RequestStreamHandle

                Raises:
                    RequiredError: If a required parameter is missing.

        """

        return await self._websocketMarketStreamsApi.aggregate_trade_streams(symbol, id)

    async def all_book_tickers_stream(
        self,
        id: Optional[str] = None,
    ) -> RequestStreamHandle:
        r"""
                All Book Tickers Stream

                Pushes any update to the best bid or ask's price or quantity in real-time for all symbols.

        Retail Price Improvement(RPI) orders are not visible and excluded in the response message.

        Update Speed: 5s

                Args:
                    id (Optional[str] = None): Unique WebSocket request ID.

                Returns:
                    RequestStreamHandle

                Raises:
                    RequiredError: If a required parameter is missing.

        """

        return await self._websocketMarketStreamsApi.all_book_tickers_stream(id)

    async def all_market_liquidation_order_streams(
        self,
        id: Optional[str] = None,
    ) -> RequestStreamHandle:
        r"""
                All Market Liquidation Order Streams

                The All Liquidation Order Snapshot Streams push force liquidation order information for all symbols in the market.
        For each symbol，only the latest one liquidation order within 1000ms will be pushed as the snapshot. If no liquidation happens in the interval of 1000ms, no stream will be pushed.

        Update Speed: 1000ms

                Args:
                    id (Optional[str] = None): Unique WebSocket request ID.

                Returns:
                    RequestStreamHandle

                Raises:
                    RequiredError: If a required parameter is missing.

        """

        return (
            await self._websocketMarketStreamsApi.all_market_liquidation_order_streams(
                id
            )
        )

    async def all_market_mini_tickers_stream(
        self,
        id: Optional[str] = None,
    ) -> RequestStreamHandle:
        r"""
                All Market Mini Tickers Stream

                24hr rolling window mini-ticker statistics for all symbols. These are NOT the statistics of the UTC day, but a 24hr rolling window from requestTime to 24hrs before. Note that only tickers that have changed will be present in the array.

        Update Speed: 1000ms

                Args:
                    id (Optional[str] = None): Unique WebSocket request ID.

                Returns:
                    RequestStreamHandle

                Raises:
                    RequiredError: If a required parameter is missing.

        """

        return await self._websocketMarketStreamsApi.all_market_mini_tickers_stream(id)

    async def all_market_tickers_streams(
        self,
        id: Optional[str] = None,
    ) -> RequestStreamHandle:
        r"""
                All Market Tickers Streams

                24hr rolling window ticker statistics for all symbols. These are NOT the statistics of the UTC day, but a 24hr rolling window from requestTime to 24hrs before. Note that only tickers that have changed will be present in the array.

        Update Speed: 1000ms

                Args:
                    id (Optional[str] = None): Unique WebSocket request ID.

                Returns:
                    RequestStreamHandle

                Raises:
                    RequiredError: If a required parameter is missing.

        """

        return await self._websocketMarketStreamsApi.all_market_tickers_streams(id)

    async def composite_index_symbol_information_streams(
        self,
        symbol: Union[str, None],
        id: Optional[str] = None,
    ) -> RequestStreamHandle:
        r"""
                Composite Index Symbol Information Streams

                Composite index information for index symbols pushed every second.

        Update Speed: 1000ms

                Args:
                    symbol (Union[str, None]): The symbol parameter
                    id (Optional[str] = None): Unique WebSocket request ID.

                Returns:
                    RequestStreamHandle

                Raises:
                    RequiredError: If a required parameter is missing.

        """

        return await self._websocketMarketStreamsApi.composite_index_symbol_information_streams(
            symbol, id
        )

    async def continuous_contract_kline_candlestick_streams(
        self,
        pair: Union[str, None],
        contract_type: Union[str, None],
        interval: Union[str, None],
        id: Optional[str] = None,
    ) -> RequestStreamHandle:
        r"""
                Continuous Contract Kline/Candlestick Streams


        Update Speed: 250ms

                Args:
                    pair (Union[str, None]): The pair parameter
                    contract_type (Union[str, None]): The contractType parameter
                    interval (Union[str, None]): The interval parameter
                    id (Optional[str] = None): Unique WebSocket request ID.

                Returns:
                    RequestStreamHandle

                Raises:
                    RequiredError: If a required parameter is missing.

        """

        return await self._websocketMarketStreamsApi.continuous_contract_kline_candlestick_streams(
            pair, contract_type, interval, id
        )

    async def contract_info_stream(
        self,
        id: Optional[str] = None,
    ) -> RequestStreamHandle:
        r"""
                Contract Info Stream

                ContractInfo stream pushes when contract info updates(listing/settlement/contract bracket update). `bks` field only shows up when bracket gets updated.

        Update Speed: Real-time

                Args:
                    id (Optional[str] = None): Unique WebSocket request ID.

                Returns:
                    RequestStreamHandle

                Raises:
                    RequiredError: If a required parameter is missing.

        """

        return await self._websocketMarketStreamsApi.contract_info_stream(id)

    async def diff_book_depth_streams(
        self,
        symbol: Union[str, None],
        id: Optional[str] = None,
        update_speed: Optional[str] = None,
    ) -> RequestStreamHandle:
        r"""
                Diff. Book Depth Streams

                Bids and asks, pushed every 250 milliseconds, 500 milliseconds, 100 milliseconds (if existing)

        Retail Price Improvement(RPI) orders are not visible and excluded in the response message.

        Update Speed: 250ms, 500ms, 100ms

                Args:
                    symbol (Union[str, None]): The symbol parameter
                    id (Optional[str] = None): Unique WebSocket request ID.
                    update_speed (Optional[str] = None): WebSocket stream update speed

                Returns:
                    RequestStreamHandle

                Raises:
                    RequiredError: If a required parameter is missing.

        """

        return await self._websocketMarketStreamsApi.diff_book_depth_streams(
            symbol, id, update_speed
        )

    async def individual_symbol_book_ticker_streams(
        self,
        symbol: Union[str, None],
        id: Optional[str] = None,
    ) -> RequestStreamHandle:
        r"""
                Individual Symbol Book Ticker Streams

                Pushes any update to the best bid or ask's price or quantity in real-time for a specified symbol.

        Retail Price Improvement(RPI) orders are not visible and excluded in the response message.

        Update Speed: Real-time

                Args:
                    symbol (Union[str, None]): The symbol parameter
                    id (Optional[str] = None): Unique WebSocket request ID.

                Returns:
                    RequestStreamHandle

                Raises:
                    RequiredError: If a required parameter is missing.

        """

        return (
            await self._websocketMarketStreamsApi.individual_symbol_book_ticker_streams(
                symbol, id
            )
        )

    async def individual_symbol_mini_ticker_stream(
        self,
        symbol: Union[str, None],
        id: Optional[str] = None,
    ) -> RequestStreamHandle:
        r"""
                Individual Symbol Mini Ticker Stream

                24hr rolling window mini-ticker statistics for a single symbol. These are NOT the statistics of the UTC day, but a 24hr rolling window from requestTime to 24hrs before.

        Update Speed: 2s

                Args:
                    symbol (Union[str, None]): The symbol parameter
                    id (Optional[str] = None): Unique WebSocket request ID.

                Returns:
                    RequestStreamHandle

                Raises:
                    RequiredError: If a required parameter is missing.

        """

        return (
            await self._websocketMarketStreamsApi.individual_symbol_mini_ticker_stream(
                symbol, id
            )
        )

    async def individual_symbol_ticker_streams(
        self,
        symbol: Union[str, None],
        id: Optional[str] = None,
    ) -> RequestStreamHandle:
        r"""
                Individual Symbol Ticker Streams

                24hr rolling window ticker statistics for a single symbol. These are NOT the statistics of the UTC day, but a 24hr rolling window from requestTime to 24hrs before.

        Update Speed: 2000ms

                Args:
                    symbol (Union[str, None]): The symbol parameter
                    id (Optional[str] = None): Unique WebSocket request ID.

                Returns:
                    RequestStreamHandle

                Raises:
                    RequiredError: If a required parameter is missing.

        """

        return await self._websocketMarketStreamsApi.individual_symbol_ticker_streams(
            symbol, id
        )

    async def kline_candlestick_streams(
        self,
        symbol: Union[str, None],
        interval: Union[str, None],
        id: Optional[str] = None,
    ) -> RequestStreamHandle:
        r"""
                Kline/Candlestick Streams

                The Kline/Candlestick Stream push updates to the current klines/candlestick every 250 milliseconds (if existing).

        Update Speed: 250ms

                Args:
                    symbol (Union[str, None]): The symbol parameter
                    interval (Union[str, None]): The interval parameter
                    id (Optional[str] = None): Unique WebSocket request ID.

                Returns:
                    RequestStreamHandle

                Raises:
                    RequiredError: If a required parameter is missing.

        """

        return await self._websocketMarketStreamsApi.kline_candlestick_streams(
            symbol, interval, id
        )

    async def liquidation_order_streams(
        self,
        symbol: Union[str, None],
        id: Optional[str] = None,
    ) -> RequestStreamHandle:
        r"""
                Liquidation Order Streams

                The Liquidation Order Snapshot Streams push force liquidation order information for specific symbol.
        For each symbol，only the latest one liquidation order within 1000ms will be pushed as the snapshot. If no liquidation happens in the interval of 1000ms, no stream will be pushed.

        Update Speed: 1000ms

                Args:
                    symbol (Union[str, None]): The symbol parameter
                    id (Optional[str] = None): Unique WebSocket request ID.

                Returns:
                    RequestStreamHandle

                Raises:
                    RequiredError: If a required parameter is missing.

        """

        return await self._websocketMarketStreamsApi.liquidation_order_streams(
            symbol, id
        )

    async def mark_price_stream(
        self,
        symbol: Union[str, None],
        id: Optional[str] = None,
        update_speed: Optional[str] = None,
    ) -> RequestStreamHandle:
        r"""
                Mark Price Stream

                Mark price and funding rate for a single symbol pushed every 3 seconds or every second.

        Update Speed: 3000ms or 1000ms

                Args:
                    symbol (Union[str, None]): The symbol parameter
                    id (Optional[str] = None): Unique WebSocket request ID.
                    update_speed (Optional[str] = None): WebSocket stream update speed

                Returns:
                    RequestStreamHandle

                Raises:
                    RequiredError: If a required parameter is missing.

        """

        return await self._websocketMarketStreamsApi.mark_price_stream(
            symbol, id, update_speed
        )

    async def mark_price_stream_for_all_market(
        self,
        id: Optional[str] = None,
        update_speed: Optional[str] = None,
    ) -> RequestStreamHandle:
        r"""
                Mark Price Stream for All market

                Mark price and funding rate for all symbols pushed every 3 seconds or every second.

        **Note**:

        This stream does not cover TradFi Perps.

        Update Speed: 3000ms or 1000ms

                Args:
                    id (Optional[str] = None): Unique WebSocket request ID.
                    update_speed (Optional[str] = None): WebSocket stream update speed

                Returns:
                    RequestStreamHandle

                Raises:
                    RequiredError: If a required parameter is missing.

        """

        return await self._websocketMarketStreamsApi.mark_price_stream_for_all_market(
            id, update_speed
        )

    async def multi_assets_mode_asset_index(
        self,
        id: Optional[str] = None,
    ) -> RequestStreamHandle:
        r"""
                Multi-Assets Mode Asset Index

                Asset index for multi-assets mode user

        Update Speed: 1s

                Args:
                    id (Optional[str] = None): Unique WebSocket request ID.

                Returns:
                    RequestStreamHandle

                Raises:
                    RequiredError: If a required parameter is missing.

        """

        return await self._websocketMarketStreamsApi.multi_assets_mode_asset_index(id)

    async def partial_book_depth_streams(
        self,
        symbol: Union[str, None],
        levels: Union[int, None],
        id: Optional[str] = None,
        update_speed: Optional[str] = None,
    ) -> RequestStreamHandle:
        r"""
                Partial Book Depth Streams

                Top **<levels\>** bids and asks, Valid **<levels\>** are 5, 10, or 20.

        Retail Price Improvement(RPI) orders are not visible and excluded in the response message.

        Update Speed: 250ms, 500ms or 100ms

                Args:
                    symbol (Union[str, None]): The symbol parameter
                    levels (Union[int, None]): The levels parameter
                    id (Optional[str] = None): Unique WebSocket request ID.
                    update_speed (Optional[str] = None): WebSocket stream update speed

                Returns:
                    RequestStreamHandle

                Raises:
                    RequiredError: If a required parameter is missing.

        """

        return await self._websocketMarketStreamsApi.partial_book_depth_streams(
            symbol, levels, id, update_speed
        )

    async def rpi_diff_book_depth_streams(
        self,
        symbol: Union[str, None],
        id: Optional[str] = None,
    ) -> RequestStreamHandle:
        r"""
                RPI Diff. Book Depth Streams

                Bids and asks including RPI orders, pushed every 500 milliseconds

        RPI(Retail Price Improvement) orders are included and aggreated in the response message. When the quantity of a price level to be updated is equal to 0, it means either all quotations for this price have been filled/canceled, or the quantity of crossed RPI orders for this price are hidden

        Update Speed: 500ms

                Args:
                    symbol (Union[str, None]): The symbol parameter
                    id (Optional[str] = None): Unique WebSocket request ID.

                Returns:
                    RequestStreamHandle

                Raises:
                    RequiredError: If a required parameter is missing.

        """

        return await self._websocketMarketStreamsApi.rpi_diff_book_depth_streams(
            symbol, id
        )

    async def trading_session_stream(
        self,
        id: Optional[str] = None,
    ) -> RequestStreamHandle:
        r"""
                Trading Session Stream

                Trading session information for the underlying assets of TradFi Perpetual contracts—covering the U.S. equity market and the commodity market—is updated every second. Trading session information for different underlying markets is pushed in separate messages. Session types for the equity market include "PRE_MARKET", "REGULAR", "AFTER_MARKET", "OVERNIGHT", and "NO_TRADING". Session types for the commodity market include "REGULAR" and "NO_TRADING".

        Update Speed: 1s

                Args:
                    id (Optional[str] = None): Unique WebSocket request ID.

                Returns:
                    RequestStreamHandle

                Raises:
                    RequiredError: If a required parameter is missing.

        """

        return await self._websocketMarketStreamsApi.trading_session_stream(id)
