unicorn_binance_websocket_api package

Submodules

unicorn_binance_websocket_api.api module

class unicorn_binance_websocket_api.api.BinanceWebSocketApiApi(manager=None)[source]

Bases: object

Connect to Binance API via Websocket.

This is valid for each ubwa.api.method():

If no stream_id is provided, we try to find it via a provided stream_label, if also not available we use the stream_id of the one active websocket api stream if there is one. But if there is not exactly one valid websocket api stream, this will fail! It must be clear! The stream is also valid during a stream restart, the payload is submitted as soon the stream is online again.

Read these instructions to get started:

Binance.com SPOT websocket API documentation:

Parameters:

manager (BinanceWebsocketApiManager) – Provide the initiated UNICORN Binance WebSocket API Manager instance.

cancel_open_orders(process_response=None, return_response: bool = False, symbol: str | None = None, recv_window: int | None = None, request_id: str | None = None, stream_id: str | None = None, stream_label: str | None = None) bool[source]

Cancel all open orders on a symbol, including OCO orders.

Official documentation:

Parameters:
  • process_response (function) – Provide a function/method to process the received webstream data (callback) of this specific request.

  • symbol (int) – The symbol you want to trade

  • recv_window (int) – An additional parameter, recvWindow, may be sent to specify the number of milliseconds after timestamp the request is valid for. If recvWindow is not sent, it defaults to 5000. The value cannot be greater than 60000.

  • request_id (str) – Provide a custom id for the request

  • return_response (bool) – If True the response of the API request is waited for and returned directly. However, this increases the execution time of the function by the duration until the response is received from the Binance API.

  • stream_id (str) – ID of a stream to send the request

  • stream_label (str) – Label of a stream to send the request. Only used if stream_id is not provided!

Returns:

bool

Message Sent:

{
    "id": "778f938f-9041-4b88-9914-efbf64eeacc8",
    "method": "openOrders.cancelAll"
    "params": {
        "symbol": "BTCUSDT",
        "apiKey": "vmPUZE6mv9SD5VNHk4HlWFsOr6aKE2zvsw0MuIgwCIPy6utIco14y7Ju91duEh8A",
        "signature": "773f01b6e3c2c9e0c1d217bc043ce383c1ddd6f0e25f8d6070f2b66a6ceaf3a5",
        "timestamp": 1660805557200
    }
}

Response:

{
    "id": "778f938f-9041-4b88-9914-efbf64eeacc8",
    "status": 200,
    "result": [
        {
            "symbol": "BTCUSDT",
            "origClientOrderId": "4d96324ff9d44481926157",
            "orderId": 12569099453,
            "orderListId": -1,
            "clientOrderId": "91fe37ce9e69c90d6358c0",
            "price": "23416.10000000",
            "origQty": "0.00847000",
            "executedQty": "0.00001000",
            "cummulativeQuoteQty": "0.23416100",
            "status": "CANCELED",
            "timeInForce": "GTC",
            "type": "LIMIT",
            "side": "SELL",
            "stopPrice": "0.00000000",
            "trailingDelta": 0,
            "trailingTime": -1,
            "icebergQty": "0.00000000",
            "strategyId": 37463720,
            "strategyType": 1000000,
            "selfTradePreventionMode": "NONE"
        },
        {
            "orderListId": 19431,
            "contingencyType": "OCO",
            "listStatusType": "ALL_DONE",
            "listOrderStatus": "ALL_DONE",
            "listClientOrderId": "iuVNVJYYrByz6C4yGOPPK0",
            "transactionTime": 1660803702431,
            "symbol": "BTCUSDT",
            "orders": [
                {
                "symbol": "BTCUSDT",
                "orderId": 12569099453,
                "clientOrderId": "bX5wROblo6YeDwa9iTLeyY"
                },
                {
                "symbol": "BTCUSDT",
                "orderId": 12569099454,
                "clientOrderId": "Tnu2IP0J5Y4mxw3IATBfmW"
                }
            ],
            "orderReports": [
                {
                    "symbol": "BTCUSDT",
                    "origClientOrderId": "bX5wROblo6YeDwa9iTLeyY",
                    "orderId": 12569099453,
                    "orderListId": 19431,
                    "clientOrderId": "OFFXQtxVFZ6Nbcg4PgE2DA",
                    "price": "23450.50000000",
                    "origQty": "0.00850000",
                    "executedQty": "0.00000000",
                    "cummulativeQuoteQty": "0.00000000",
                    "status": "CANCELED",
                    "timeInForce": "GTC",
                    "type": "STOP_LOSS_LIMIT",
                    "side": "BUY",
                    "stopPrice": "23430.00000000",
                    "selfTradePreventionMode": "NONE"
                },
                {
                    "symbol": "BTCUSDT",
                    "origClientOrderId": "Tnu2IP0J5Y4mxw3IATBfmW",
                    "orderId": 12569099454,
                    "orderListId": 19431,
                    "clientOrderId": "OFFXQtxVFZ6Nbcg4PgE2DA",
                    "price": "23400.00000000",
                    "origQty": "0.00850000",
                    "executedQty": "0.00000000",
                    "cummulativeQuoteQty": "0.00000000",
                    "status": "CANCELED",
                    "timeInForce": "GTC",
                    "type": "LIMIT_MAKER",
                    "side": "BUY",
                    "selfTradePreventionMode": "NONE"
                }
            ]
        }
    ],
    "rateLimits": [
        {
            "rateLimitType": "REQUEST_WEIGHT",
            "interval": "MINUTE",
            "intervalNum": 1,
            "limit": 1200,
            "count": 1
        }
    ]
}
cancel_order(cancel_restrictions: Literal['ONLY_NEW', 'ONLY_PARTIALLY_FILLED'] | None = None, new_client_order_id: str | None = None, order_id: int | None = None, orig_client_order_id: str | None = None, process_response=None, recv_window: int | None = None, request_id: str | None = None, return_response: bool = False, stream_id=None, symbol: str | None = None, stream_label: str | None = None) bool[source]

Cancel an active order.

If you cancel an order that is a part of an OCO pair, the entire OCO is canceled.

Official documentation:

Parameters:
  • cancel_restrictions (str) –

    Supported values:

    • ONLY_NEW: Cancel will succeed if the order status is NEW.

    • ONLY_PARTIALLY_FILLED: Cancel will succeed if order status is PARTIALLY_FILLED.

    If the cancelRestrictions value is not any of the supported values, the error will be: {“code”: -1145,”msg”: “Invalid cancelRestrictions”}

    If the order did not pass the conditions for cancelRestrictions, the error will be: {“code”: -2011,”msg”: “Order was not canceled due to cancel restrictions.”}

  • new_client_order_id (str) – New ID for the canceled order. Automatically generated if not sent. newClientOrderId will replace clientOrderId of the canceled order, freeing it up for new orders.

  • order_id (str) – Cancel by order_id. If both orderId and origClientOrderId parameters are specified, only orderId is used and origClientOrderId is ignored.

  • orig_client_order_id (str) – Cancel by origClientOrderId. If both orderId and origClientOrderId parameters are specified, only orderId is used and origClientOrderId is ignored.

  • process_response (function) – Provide a function/method to process the received webstream data (callback) of this specific request.

  • recv_window (int) – An additional parameter, recvWindow, may be sent to specify the number of milliseconds after timestamp the request is valid for. If recvWindow is not sent, it defaults to 5000. The value cannot be greater than 60000.

  • request_id (str) – Provide a custom id for the request

  • return_response (bool) – If True the response of the API request is waited for and returned directly. However, this increases the execution time of the function by the duration until the response is received from the Binance API.

  • stream_id (str) – ID of a stream to send the request

  • stream_label (str) – Label of a stream to send the request. Only used if stream_id is not provided!

  • symbol (str) – The symbol of the order you want to cancel

Returns:

bool

Message sent:

{
    "id": "5633b6a2-90a9-4192-83e7-925c90b6a2fd",
    "method": "order.cancel",
    "params": {
        "symbol": "BTCUSDT",
        "origClientOrderId": "4d96324ff9d44481926157",
        "apiKey": "vmPUZE6mv9SD5VNHk4HlWFsOr6aKE2zvsw0MuIgwCIPy6utIco14y7Ju91duEh8A",
        "signature": "33d5b721f278ae17a52f004a82a6f68a70c68e7dd6776ed0be77a455ab855282",
        "timestamp": 1660801715830
    }
}

Response:

{
    "id": "5633b6a2-90a9-4192-83e7-925c90b6a2fd",
    "status": 200,
    "result": {
        "symbol": "BTCUSDT",
        "origClientOrderId": "4d96324ff9d44481926157",
        "orderId": 12569099453,
        "orderListId": -1,
        "clientOrderId": "91fe37ce9e69c90d6358c0",
        "price": "23416.10000000",
        "origQty": "0.00847000",
        "executedQty": "0.00001000",
        "cummulativeQuoteQty": "0.23416100",
        "status": "CANCELED",
        "timeInForce": "GTC",
        "type": "LIMIT",
        "side": "SELL",
        "stopPrice": "0.00000000",
        "trailingDelta": 0,
        "trailingTime": -1,
        "icebergQty": "0.00000000",
        "strategyId": 37463720,
        "strategyType": 1000000,
        "selfTradePreventionMode": "NONE"
    },
    "rateLimits": [
        {
            "rateLimitType": "REQUEST_WEIGHT",
            "interval": "MINUTE",
            "intervalNum": 1,
            "limit": 1200,
            "count": 1
        }
    ]
}
create_order(iceberg_qty: float | None = None, new_client_order_id: str | None = None, new_order_resp_type: Literal['ACK', 'RESULT', 'FULL'] | None = None, order_type: Literal['LIMIT', 'LIMIT_MAKER', 'MARKET', 'STOP_LOSS', 'STOP_LOSS_LIMIT', 'TAKE_PROFIT', 'TAKE_PROFIT_LIMIT'] | None = None, price: float = 0.0, process_response=None, quantity: float = 0.0, quote_order_qty: float | None = None, recv_window: int | None = None, request_id: str | None = None, return_response: bool = False, self_trade_prevention_mode: Literal['EXPIRE_TAKER', 'EXPIRE_MAKER', 'EXPIRE_BOTH', 'NONE'] | None = None, side: Literal['BUY', 'SELL'] | None = None, stop_price: float | None = None, strategy_id: int | None = None, strategy_type: int | None = None, stream_id=None, stream_label: str | None = None, symbol: str | None = None, time_in_force: Literal['GTC', 'IOC', 'FOK'] | None = 'GTC', test: bool = False, trailing_delta: int | None = None) int | bool[source]

Create a new order.

Official documentation:

Parameters:
  • iceberg_qty (float) – Any LIMIT or LIMIT_MAKER order can be made into an iceberg order by specifying the icebergQty. An order with an icebergQty must have timeInForce set to GTC.

  • new_client_order_id (str) – newClientOrderId specifies clientOrderId value for the order. A new order with the same ‘clientOrderId’ is accepted only when the previous one is filled or expired.

  • new_order_resp_type (str) – Select response format: ACK, RESULT, FULL. ‘MARKET’ and ‘LIMIT’ orders use FULL by default, other order types default to ‘ACK’

  • order_type (str) –

    ‘LIMIT’, ‘LIMIT_MAKER’, ‘MARKET’, ‘STOP_LOSS’, ‘STOP_LOSS_LIMIT’, ‘TAKE_PROFIT’, ‘TAKE_PROFIT_LIMIT’

    Mandatory parameters per order_type:

    • LIMIT: ‘timeInForce’, ‘price’, ‘quantity’

    • LIMIT_MAKER: ‘price’, ‘quantity’

    • MARKET: ‘quantity’ or ‘quoteOrderQty’

    • STOP_LOSS: ‘quantity’, ‘stopPrice’ or ‘trailingDelta’

    • STOP_LOSS_LIMIT: ‘timeInForce’, ‘price’, ‘quantity’, ‘stopPrice’ or ‘trailingDelta’

    • TAKE_PROFIT: ‘quantity’, ‘stopPrice’ or ‘trailingDelta’

    • TAKE_PROFIT_LIMIT: ‘timeInForce’, ‘price’, ‘quantity’, ‘stopPrice’ or ‘trailingDelta’

  • price (float) – Price e.g. 10.223

  • process_response (function) – Provide a function/method to process the received webstream data (callback) of this specific request.

  • quantity (float) – Amount e.g. 20.5

  • quote_order_qty (float) – Amount e.g. 20.5

  • recv_window (int) – An additional parameter, recvWindow, may be sent to specify the number of milliseconds after timestamp the request is valid for. If recvWindow is not sent, it defaults to 5000. The value cannot be greater than 60000.

  • request_id (str) – Provide a custom id for the request

  • return_response (bool) – If True the response of the API request is waited for and returned directly. However, this increases the execution time of the function by the duration until the response is received from the Binance API.

  • self_trade_prevention_mode (str) – The allowed enums for selfTradePreventionMode is dependent on what is configured on the symbol. The possible supported values are EXPIRE_TAKER, EXPIRE_MAKER, EXPIRE_BOTH, NONE.

  • side (str) – BUY or SELL

  • strategy_id (int) – Arbitrary numeric value identifying the order within an order strategy.

  • strategy_type (int) – Arbitrary numeric value identifying the order strategy. Values smaller than 1000000 are reserved and cannot be used.

  • stream_id (str) – ID of a stream to send the request

  • stream_label (str) – Label of a stream to send the request. Only used if stream_id is not provided!

  • stop_price (float) –

    Trigger order price rules for STOP_LOSS/TAKE_PROFIT orders:

    • stopPrice must be above market price: STOP_LOSS BUY, TAKE_PROFIT SELL

    • stopPrice must be below market price: STOP_LOSS SELL, TAKE_PROFIT BUY

  • symbol (str) – The symbol you want to trade

  • test (bool) – Test order placement. Validates new order parameters and verifies your signature but does not send the order into the matching engine.

  • time_in_force (str) –

    Available timeInForce options, setting how long the order should be active before expiration:

    • GTC: Good ‘til Canceled – the order will remain on the book until you cancel it, or the order is completely filled.

    • IOC: Immediate or Cancel – the order will be filled for as much as possible, the unfilled quantity immediately expires.

    • FOK: Fill or Kill – the order will expire unless it cannot be immediately filled for the entire quantity.

    MARKET orders using quoteOrderQty follow LOT_SIZE filter rules. The order will execute a quantity that has notional value as close as possible to requested quoteOrderQty.

  • trailing_delta (int) – For more details on SPOT implementation on trailing stops, please refer to Trailing Stop FAQ

Returns:

False or orig_client_order_id

Message sent:

{
    "id": "56374a46-3061-486b-a311-99ee972eb648",
    "method": "order.place",
    "params": {
        "symbol": "BTCUSDT",
        "side": "SELL",
        "type": "LIMIT",
        "timeInForce": "GTC",
        "price": "23416.10000000",
        "quantity": "0.00847000",
        "apiKey": "vmPUZE6mv9SD5VNHk4HlWFsOr6aKE2zvsw0MuIgwCIPy6utIco14y7Ju91duEh8A",
        "signature": "15af09e41c36f3cc61378c2fbe2c33719a03dd5eba8d0f9206fbda44de717c88",
        "timestamp": 1660801715431
    }
}

Response

{
    "id": "56374a46-3061-486b-a311-99ee972eb648",
    "status": 200,
    "result": {
        "symbol": "BTCUSDT",
        "orderId": 12569099453,
        "orderListId": -1,
        "clientOrderId": "4d96324ff9d44481926157ec08158a40",
        "transactTime": 1660801715639
    },
    "rateLimits": [
        {
            "rateLimitType": "ORDERS",
            "interval": "SECOND",
            "intervalNum": 10,
            "limit": 50,
            "count": 1
        },
        {
            "rateLimitType": "ORDERS",
            "interval": "DAY",
            "intervalNum": 1,
            "limit": 160000,
            "count": 1
        },
        {
            "rateLimitType": "REQUEST_WEIGHT",
            "interval": "MINUTE",
            "intervalNum": 1,
            "limit": 1200,
            "count": 1
        }
    ]
}
create_test_order(iceberg_qty: float | None = None, new_client_order_id: str | None = None, new_order_resp_type: Literal['ACK', 'RESULT', 'FULL'] | None = None, order_type: Literal['LIMIT', 'LIMIT_MAKER', 'MARKET', 'STOP_LOSS', 'STOP_LOSS_LIMIT', 'TAKE_PROFIT', 'TAKE_PROFIT_LIMIT'] | None = None, price: float = 0.0, process_response=None, quantity: float = 0.0, quote_order_qty: float | None = None, recv_window: int | None = None, request_id: str | None = None, return_response: bool = False, self_trade_prevention_mode: Literal['EXPIRE_TAKER', 'EXPIRE_MAKER', 'EXPIRE_BOTH', 'NONE'] | None = None, side: Literal['BUY', 'SELL'] | None = None, stop_price: float | None = None, strategy_id: int | None = None, strategy_type: int | None = None, stream_id=None, stream_label: str | None = None, symbol: str | None = None, time_in_force: Literal['GTC', 'IOC', 'FOK'] | None = 'GTC', trailing_delta: int | None = None) int | bool[source]

Test order placement.

Validates new order parameters and verifies your signature but does not send the order into the matching engine.

Official documentation:

Parameters:
  • iceberg_qty (float) – Any LIMIT or LIMIT_MAKER order can be made into an iceberg order by specifying the icebergQty. An order with an icebergQty must have timeInForce set to GTC.

  • new_client_order_id (str) – newClientOrderId specifies clientOrderId value for the order. A new order with the same ‘clientOrderId’ is accepted only when the previous one is filled or expired.

  • new_order_resp_type (str) – Select response format: ACK, RESULT, FULL. ‘MARKET’ and ‘LIMIT’ orders use FULL by default, other order types default to ‘ACK’

  • order_type (str) –

    ‘LIMIT’, ‘LIMIT_MAKER’, ‘MARKET’, ‘STOP_LOSS’, ‘STOP_LOSS_LIMIT’, ‘TAKE_PROFIT’, ‘TAKE_PROFIT_LIMIT’

    Mandatory parameters per order_type:

    • LIMIT: ‘timeInForce’, ‘price’, ‘quantity’

    • LIMIT_MAKER: ‘price’, ‘quantity’

    • MARKET: ‘quantity’ or ‘quoteOrderQty’

    • STOP_LOSS: ‘quantity’, ‘stopPrice’ or ‘trailingDelta’

    • STOP_LOSS_LIMIT: ‘timeInForce’, ‘price’, ‘quantity’, ‘stopPrice’ or ‘trailingDelta’

    • TAKE_PROFIT: ‘quantity’, ‘stopPrice’ or ‘trailingDelta’

    • TAKE_PROFIT_LIMIT: ‘timeInForce’, ‘price’, ‘quantity’, ‘stopPrice’ or ‘trailingDelta’

  • price (float) – Price e.g. 10.223

  • process_response (function) – Provide a function/method to process the received webstream data (callback) of this specific request.

  • quantity (float) – Amount e.g. 20.5

  • quote_order_qty (float) – Amount e.g. 20.5

  • recv_window (int) – An additional parameter, recvWindow, may be sent to specify the number of milliseconds after timestamp the request is valid for. If recvWindow is not sent, it defaults to 5000. The value cannot be greater than 60000.

  • request_id (str) – Provide a custom id for the request

  • return_response (bool) – If True the response of the API request is waited for and returned directly. However, this increases the execution time of the function by the duration until the response is received from the Binance API.

  • self_trade_prevention_mode (str) – The allowed enums for selfTradePreventionMode is dependent on what is configured on the symbol. The possible supported values are EXPIRE_TAKER, EXPIRE_MAKER, EXPIRE_BOTH, NONE.

  • side (str) – BUY or SELL

  • strategy_id (int) – Arbitrary numeric value identifying the order within an order strategy.

  • strategy_type (int) – Arbitrary numeric value identifying the order strategy. Values smaller than 1000000 are reserved and cannot be used.

  • stream_id (str) – ID of a stream to send the request

  • stream_label (str) – Label of a stream to send the request. Only used if stream_id is not provided!

  • stop_price (float) –

    Trigger order price rules for STOP_LOSS/TAKE_PROFIT orders:

    • stopPrice must be above market price: STOP_LOSS BUY, TAKE_PROFIT SELL

    • stopPrice must be below market price: STOP_LOSS SELL, TAKE_PROFIT BUY

  • symbol (str) – The symbol you want to trade

  • time_in_force (str) –

    Available timeInForce options, setting how long the order should be active before expiration:

    • GTC: Good ‘til Canceled – the order will remain on the book until you cancel it, or the order is completely filled.

    • IOC: Immediate or Cancel – the order will be filled for as much as possible, the unfilled quantity immediately expires.

    • FOK: Fill or Kill – the order will expire unless it cannot be immediately filled for the entire quantity.

    MARKET orders using quoteOrderQty follow LOT_SIZE filter rules. The order will execute a quantity that has notional value as close as possible to requested quoteOrderQty.

  • trailing_delta (int) – For more details on SPOT implementation on trailing stops, please refer to Trailing Stop FAQ

Returns:

False or orig_client_order_id

Message sent:

{
    "id": "56374a46-3061-486b-a311-99ee972eb648",
    "method": "order.test",
    "params": {
        "symbol": "BTCUSDT",
        "side": "SELL",
        "type": "LIMIT",
        "timeInForce": "GTC",
        "price": "23416.10000000",
        "quantity": "0.00847000",
        "apiKey": "vmPUZE6mv9SD5VNHk4HlWFsOr6aKE2zvsw0MuIgwCIPy6utIco14y7Ju91duEh8A",
        "signature": "15af09e41c36f3cc61378c2fbe2c33719a03dd5eba8d0f9206fbda44de717c88",
        "timestamp": 1660801715431
    }
}

Response

{
    "id": "56374a46-3061-486b-a311-99ee972eb648",
    "status": 200,
    "result": {
        "symbol": "BTCUSDT",
        "orderId": 12569099453,
        "orderListId": -1,
        "clientOrderId": "4d96324ff9d44481926157ec08158a40",
        "transactTime": 1660801715639
    },
    "rateLimits": [
        {
            "rateLimitType": "ORDERS",
            "interval": "SECOND",
            "intervalNum": 10,
            "limit": 50,
            "count": 1
        },
        {
            "rateLimitType": "ORDERS",
            "interval": "DAY",
            "intervalNum": 1,
            "limit": 160000,
            "count": 1
        },
        {
            "rateLimitType": "REQUEST_WEIGHT",
            "interval": "MINUTE",
            "intervalNum": 1,
            "limit": 1200,
            "count": 1
        }
    ]
}
get_account_status(process_response=None, recv_window: int | None = None, request_id: str | None = None, return_response: bool = False, stream_id=None, stream_label: str | None = None) bool[source]

Get the user account status.

Official documentation:

Parameters:
  • process_response (function) – Provide a function/method to process the received webstream data (callback) of this specific request.

  • recv_window (int) – An additional parameter, recvWindow, may be sent to specify the number of milliseconds after timestamp the request is valid for. If recvWindow is not sent, it defaults to 5000. The value cannot be greater than 60000.

  • request_id (str) – Provide a custom id for the request

  • return_response (bool) – If True the response of the API request is waited for and returned directly. However, this increases the execution time of the function by the duration until the response is received from the Binance API.

  • stream_id (str) – ID of a stream to send the request

  • stream_label (str) – Label of a stream to send the request. Only used if stream_id is not provided!

Returns:

bool

Message sent:

{
    "id": "605a6d20-6588-4cb9-afa0-b0ab087507ba",
    "method": "account.status",
    "params": {
        "apiKey": "vmPUZE6mv9SD5VNHk4HlWFsOr6aKE2zvsw0MuIgwCIPy6utIco14y7Ju91duEh8A",
        "signature": "83303b4a136ac1371795f465808367242685a9e3a42b22edb4d977d0696eb45c",
        "timestamp": 1660801839480
    }
}

Response:

{
    "id": "605a6d20-6588-4cb9-afa0-b0ab087507ba",
    "status": 200,
    "result": {
        "makerCommission": 15,
        "takerCommission": 15,
        "buyerCommission": 0,
        "sellerCommission": 0,
        "canTrade": true,
        "canWithdraw": true,
        "canDeposit": true,
        "commissionRates": {
            "maker": "0.00150000",
            "taker": "0.00150000",
            "buyer": "0.00000000",
            "seller":"0.00000000"
        },
        "brokered": false,
        "requireSelfTradePrevention": false,
        "updateTime": 1660801833000,
        "accountType": "SPOT",
        "balances": [
            {
                "asset": "BNB",
                "free": "0.00000000",
                "locked": "0.00000000"
            },
            {
                "asset": "BTC",
                "free": "1.3447112",
                "locked": "0.08600000"
            },
            {
                "asset": "USDT",
                "free": "1021.21000000",
                "locked": "0.00000000"
            }
        ],
        "permissions": [
            "SPOT"
        ]
    },
    "rateLimits": [
        {
            "rateLimitType": "REQUEST_WEIGHT",
            "interval": "MINUTE",
            "intervalNum": 1,
            "limit": 1200,
            "count": 10
        }
    ]
}
get_exchange_info(permissions: list | None = None, process_response=None, recv_window: int | None = None, request_id: str | None = None, return_response: bool = False, stream_id=None, stream_label: str | None = None, symbol: str | None = None, symbols: list | None = None) bool[source]

Get the Exchange Information.

Only one of symbol, symbols, permissions parameters can be specified.

Without parameters, exchangeInfo displays all symbols with [“SPOT, “MARGIN”, “LEVERAGED”] permissions. In order to list all active symbols on the exchange, you need to explicitly request all permissions

Official documentation:

Parameters:
  • permissions (list) – Filter symbols by permissions. permissions accepts either a list of permissions, or a single permission name: “SPOT”. Available Permissions

  • process_response (function) – Provide a function/method to process the received webstream data (callback) of this specific request.

  • recv_window (int) – An additional parameter, recvWindow, may be sent to specify the number of milliseconds after timestamp the request is valid for. If recvWindow is not sent, it defaults to 5000. The value cannot be greater than 60000.

  • request_id (str) – Provide a custom id for the request

  • return_response (bool) – If True the response of the API request is waited for and returned directly. However, this increases the execution time of the function by the duration until the response is received from the Binance API.

  • stream_id (str) – ID of a stream to send the request

  • stream_label (str) – Label of a stream to send the request. Only used if stream_id is not provided!

  • symbol (str) – Describe a single symbol

  • symbols (list) – Describe multiple symbols.

Returns:

bool

Message sent:

{
    "id": "5494febb-d167-46a2-996d-70533eb4d976",
    "method": "exchangeInfo",
    "params": {
        "symbols": [
            "BNBBTC"
        ]
    }
}

Response:

{
    "id": "5494febb-d167-46a2-996d-70533eb4d976",
    "status": 200,
    "result": {
    "timezone": "UTC",
    "serverTime": 1655969291181,
    "rateLimits": [{
        "rateLimitType": "REQUEST_WEIGHT",
        "interval": "MINUTE",
        "intervalNum": 1,
        "limit": 1200
    },
    {
        "rateLimitType": "ORDERS",
        "interval": "SECOND",
        "intervalNum": 10,
        "limit": 50
    },
    {
        "rateLimitType": "ORDERS",
        "interval": "DAY",
        "intervalNum": 1,
        "limit": 160000
    },
    {
        "rateLimitType": "RAW_REQUESTS",
        "interval": "MINUTE",
        "intervalNum": 5,
        "limit": 6100
    }],
    "exchangeFilters": [],
    "symbols": [{
        "symbol": "BNBBTC",
        "status": "TRADING",
        "baseAsset": "BNB",
        "baseAssetPrecision": 8,
        "quoteAsset": "BTC",
        "quotePrecision": 8,
        "quoteAssetPrecision": 8,
        "baseCommissionPrecision": 8,
        "quoteCommissionPrecision": 8,
        "orderTypes": [
            "LIMIT",
            "LIMIT_MAKER",
            "MARKET",
            "STOP_LOSS_LIMIT",
            "TAKE_PROFIT_LIMIT"
        ],
        "icebergAllowed": true,
        "ocoAllowed": true,
        "quoteOrderQtyMarketAllowed": true,
        "allowTrailingStop": true,
        "cancelReplaceAllowed": true,
        "isSpotTradingAllowed": true,
        "isMarginTradingAllowed": true,
        "filters": [{
            "filterType": "PRICE_FILTER",
            "minPrice": "0.00000100",
            "maxPrice": "100000.00000000",
            "tickSize": "0.00000100"
        },
        {
            "filterType": "LOT_SIZE",
            "minQty": "0.00100000",
            "maxQty": "100000.00000000",
            "stepSize": "0.00100000"
        }],
        "permissions": [
            "SPOT",
            "MARGIN",
            "TRD_GRP_004"
        ],
        "defaultSelfTradePreventionMode": "NONE",
        "allowedSelfTradePreventionModes": [
            "NONE"
        ]
    }]},
    "rateLimits": [{
        "rateLimitType": "REQUEST_WEIGHT",
        "interval": "MINUTE",
        "intervalNum": 1,
        "limit": 1200,
        "count": 10
    }]
}
get_listen_key(process_response=None, request_id: str | None = None, return_response: bool = False, stream_id=None, stream_label: str | None = None) bool[source]

Get a listenKey to start a UserDataStream.

Official documentation:

Parameters:
  • process_response (function) – Provide a function/method to process the received webstream data (callback) of this specific request.

  • request_id (str) – Provide a custom id for the request

  • return_response (bool) – If True the response of the API request is waited for and returned directly. However, this increases the execution time of the function by the duration until the response is received from the Binance API.

  • stream_id (str) – ID of a stream to send the request

  • stream_label (str) – Label of a stream to send the request. Only used if stream_id is not provided!

Returns:

bool

Message sent:

{
  "id": "d3df8a61-98ea-4fe0-8f4e-0fcea5d418b0",
  "method": "userDataStream.start",
  "params": {
    "apiKey": "vmPUZE6mv9SD5VNHk4HlWFsOr6aKE2zvsw0MuIgwCIPy6utIco14y7Ju91duEh8A"
  }
}

Response:

{
  "id": "d3df8a61-98ea-4fe0-8f4e-0fcea5d418b0",
  "status": 200,
  "result": {
    "listenKey": "xs0mRXdAKlIPDRFrlPcw0qI41Eh3ixNntmymGyhrhgqo7L6FuLaWArTD7RLP"
  },
  "rateLimits": [
    {
      "rateLimitType": "REQUEST_WEIGHT",
      "interval": "MINUTE",
      "intervalNum": 1,
      "limit": 6000,
      "count": 2
    }
  ]
}
get_open_orders(process_response=None, recv_window: int | None = None, request_id: str | None = None, return_response: bool = False, stream_id=None, stream_label: str | None = None, symbol: str | None = None) bool[source]

Query execution status of all open orders.

Open orders are always returned as a flat list. If all symbols are requested, use the symbol field to tell which symbol the orders belong to.

Official documentation:

If you need to continuously monitor order status updates, please consider using WebSocket Streams

  • userData

  • executionReport user data stream event

Parameters:
  • process_response (function) – Provide a function/method to process the received webstream data (callback) of this specific request.

  • recv_window (int) – An additional parameter, recvWindow, may be sent to specify the number of milliseconds after timestamp the request is valid for. If recvWindow is not sent, it defaults to 5000. The value cannot be greater than 60000.

  • request_id (str) – Provide a custom id for the request

  • return_response (bool) – If True the response of the API request is waited for and returned directly. However, this increases the execution time of the function by the duration until the response is received from the Binance API.

  • stream_id (str) – ID of a stream to send the request

  • stream_label (str) – Label of a stream to send the request. Only used if stream_id is not provided!

  • symbol (str) – If omitted, open orders for all symbols are returned.

Returns:

bool

Message Sent:

{
    "id": "55f07876-4f6f-4c47-87dc-43e5fff3f2e7",
    "method": "openOrders.status",
    "params": {
        "symbol": "BTCUSDT",
        "apiKey": "vmPUZE6mv9SD5VNHk4HlWFsOr6aKE2zvsw0MuIgwCIPy6utIco14y7Ju91duEh8A",
        "signature": "d632b3fdb8a81dd44f82c7c901833309dd714fe508772a89b0a35b0ee0c48b89",
        "timestamp": 1660813156812
    }
}

Response:

{
    "id": "55f07876-4f6f-4c47-87dc-43e5fff3f2e7",
    "status": 200,
    "result": [
        {
            "symbol": "BTCUSDT",
            "orderId": 12569099453,
            "orderListId": -1,
            "clientOrderId": "4d96324ff9d44481926157",
            "price": "23416.10000000",
            "origQty": "0.00847000",
            "executedQty": "0.00720000",
            "cummulativeQuoteQty": "172.43931000",
            "status": "PARTIALLY_FILLED",
            "timeInForce": "GTC",
            "type": "LIMIT",
            "side": "SELL",
            "stopPrice": "0.00000000",
            "icebergQty": "0.00000000",
            "time": 1660801715639,
            "updateTime": 1660801717945,
            "isWorking": true,
            "workingTime": 1660801715639,
            "origQuoteOrderQty": "0.00000000",
            "selfTradePreventionMode": "NONE"
        }
    ],
    "rateLimits": [
        {
            "rateLimitType": "REQUEST_WEIGHT",
            "interval": "MINUTE",
            "intervalNum": 1,
            "limit": 1200,
            "count": 3
        }
    ]
}
get_order(order_id: int | None = None, orig_client_order_id: str | None = None, process_response=None, recv_window: int | None = None, request_id: str | None = None, return_response: bool = False, stream_id=None, stream_label: str | None = None, symbol: str | None = None) bool[source]

Check execution status of an order.

Official documentation:

If both orderId and origClientOrderId parameters are specified, only orderId is used and origClientOrderId is ignored.

For some historical orders the cummulativeQuoteQty response field may be negative, meaning the data is not available at this time.

Parameters:
  • order_id (int) – Lookup order by orderId.

  • orig_client_order_id (str) – Lookup order by clientOrderId.

  • process_response (function) – Provide a function/method to process the received webstream data (callback) of this specific request.

  • recv_window (int) – An additional parameter, recvWindow, may be sent to specify the number of milliseconds after timestamp the request is valid for. If recvWindow is not sent, it defaults to 5000. The value cannot be greater than 60000.

  • request_id (str) – Provide a custom id for the request

  • return_response (bool) – If True the response of the API request is waited for and returned directly. However, this increases the execution time of the function by the duration until the response is received from the Binance API.

  • stream_id (str) – ID of a stream to send the request

  • stream_label (str) – Label of a stream to send the request. Only used if stream_id is not provided!

  • symbol (str) – The symbol you want to trade

Returns:

bool

Message sent:

{
    "id": "aa62318a-5a97-4f3b-bdc7-640bbe33b291",
    "method": "order.status",
    "params": {
        "symbol": "BTCUSDT",
        "orderId": 12569099453,
        "apiKey": "vmPUZE6mv9SD5VNHk4HlWFsOr6aKE2zvsw0MuIgwCIPy6utIco14y7Ju91duEh8A",
        "signature": "2c3aab5a078ee4ea465ecd95523b77289f61476c2f238ec10c55ea6cb11a6f35",
        "timestamp": 1660801720951
    }
}

Response:

{
    "id": "aa62318a-5a97-4f3b-bdc7-640bbe33b291",
    "status": 200,
    "result": {
        "symbol": "BTCUSDT",
        "orderId": 12569099453,
        "orderListId": -1,
        "clientOrderId": "4d96324ff9d44481926157",
        "price": "23416.10000000",
        "origQty": "0.00847000",
        "executedQty": "0.00847000",
        "cummulativeQuoteQty": "198.33521500",
        "status": "FILLED",
        "timeInForce": "GTC",
        "type": "LIMIT",
        "side": "SELL",
        "stopPrice": "0.00000000",
        "trailingDelta": 10,
        "trailingTime": -1,
        "icebergQty": "0.00000000",
        "time": 1660801715639,
        "updateTime": 1660801717945,
        "isWorking": true,
        "workingTime": 1660801715639,
        "origQuoteOrderQty": "0.00000000",
        "strategyId": 37463720,
        "strategyType": 1000000,
        "selfTradePreventionMode": "NONE",
        "preventedMatchId": 0,
        "preventedQuantity": "1.200000"
    },
    "rateLimits": [
        {
            "rateLimitType": "REQUEST_WEIGHT",
            "interval": "MINUTE",
            "intervalNum": 1,
            "limit": 1200,
            "count": 2
        }
    ]
}
get_order_book(process_response=None, limit: int | None = None, recv_window: int | None = None, request_id: str | None = None, return_response: bool = False, stream_id=None, stream_label: str | None = None, symbol: str | None = None) bool[source]

Get current order book.

Note that this request returns limited market depth.

If you need to continuously monitor order book updates, please consider using ‘WebSocket Streams <https://unicorn-binance-websocket-api.docs.lucit.tech/unicorn_binance_websocket_api.html#unicorn_binance_websocket_api.manager.BinanceWebSocketApiManager.create_stream>’_

  • <symbol>@depth<levels>

  • <symbol>@depth

Official documentation:

Parameters:
  • limit (int) – Default 100; max 5000.

  • process_response (function) – Provide a function/method to process the received webstream data (callback) of this specific request.

  • recv_window (int) – An additional parameter, recvWindow, may be sent to specify the number of milliseconds after timestamp the request is valid for. If recvWindow is not sent, it defaults to 5000. The value cannot be greater than 60000.

  • request_id (str) – Provide a custom id for the request

  • return_response (bool) – If True the response of the API request is waited for and returned directly. However, this increases the execution time of the function by the duration until the response is received from the Binance API.

  • stream_id (str) – ID of a stream to send the request

  • stream_label (str) – Label of a stream to send the request. Only used if stream_id is not provided!

  • symbol (str) – The selected symbol

Returns:

bool

Message sent:

{
    "id": "5494febb-d167-46a2-996d-70533eb4d976",
    "method": "depth",
    "params": {
        "symbol": "BNBBTC",
        "limit": 5
    }
}

Response:

{
    "id": "5494febb-d167-46a2-996d-70533eb4d976",
    "status": 200,
    "result": {
        "lastUpdateId": 2731179239,
        "bids": [
            [
                "0.01379900",
                "3.43200000"
            ],
            [
                "0.01379800",
                "3.24300000"
            ],
            [
                "0.01379700",
                "10.45500000"
            ],
            [
                "0.01379600",
                "3.82100000"
            ],
            [
                "0.01379500",
                "10.26200000"
            ]
        ],
        "asks": [
            [
                "0.01380000",
                "5.91700000"
            ],
            [
                "0.01380100",
                "6.01400000"
            ],
            [
                "0.01380200",
                "0.26800000"
            ],
            [
                "0.01380300",
                "0.33800000"
            ],
            [
                "0.01380400",
                "0.26800000"
            ]
        ]
    },
    "rateLimits": [
        {
            "rateLimitType": "REQUEST_WEIGHT",
            "interval": "MINUTE",
            "intervalNum": 1,
            "limit": 1200,
            "count": 1
        }
    ]
}
get_server_time(process_response=None, request_id: str | None = None, return_response: bool = False, stream_id=None, stream_label: str | None = None) bool[source]

Test connectivity to the WebSocket API and get the current server time.

Official documentation:

Parameters:
  • process_response (function) – Provide a function/method to process the received webstream data (callback) of this specific request.

  • request_id (str) – Provide a custom id for the request

  • return_response (bool) – If True the response of the API request is waited for and returned directly. However, this increases the execution time of the function by the duration until the response is received from the Binance API.

  • stream_id (str) – ID of a stream to send the request

  • stream_label (str) – Label of a stream to send the request. Only used if stream_id is not provided!

Returns:

bool

Message sent:

{
    "id": "187d3cb2-942d-484c-8271-4e2141bbadb1",
    "method": "time"
}

Response:

{
    "id": "187d3cb2-942d-484c-8271-4e2141bbadb1",
    "status": 200,
    "result": {
        "serverTime": 1656400526260
    },
    "rateLimits": [{
        "rateLimitType": "REQUEST_WEIGHT",
        "interval": "MINUTE",
        "intervalNum": 1,
        "limit": 1200,
        "count": 1
    }]
}
ping(process_response=None, request_id: str | None = None, return_response: bool = False, stream_id=None, stream_label: str | None = None) bool[source]

Test connectivity to the WebSocket API.

Official documentation:

Parameters:
  • process_response (function) – Provide a function/method to process the received webstream data (callback) of this specific request.

  • request_id (str) – Provide a custom id for the request

  • return_response (bool) – If True the response of the API request is waited for and returned directly. However, this increases the execution time of the function by the duration until the response is received from the Binance API.

  • stream_id (str) – ID of a stream to send the request

  • stream_label (str) – Label of a stream to send the request. Only used if stream_id is not provided!

Returns:

bool

Message sent:

{
    "id": "4e72973031d8-bff9-8481-c95b-c42414df",
    "method": "ping"
}

Response:

{
    "id": "4e72973031d8-bff9-8481-c95b-c42414df",
    "status": 200,
    "result": {},
    "rateLimits": [{
        "rateLimitType": "REQUEST_WEIGHT",
        "interval": "MINUTE",
        "intervalNum": 1,
        "limit": 1200,
        "count": 1
    }]
}

unicorn_binance_websocket_api.connection module

class unicorn_binance_websocket_api.connection.BinanceWebSocketApiConnection(manager, stream_id, channels, markets, symbols)[source]

Bases: object

async close()[source]
raise_exceptions()[source]
async receive()[source]
async send(data)[source]

unicorn_binance_websocket_api.exceptions module

exception unicorn_binance_websocket_api.exceptions.MaximumSubscriptionsExceeded(exchange: str | None = None, max_subscriptions_per_stream: int | None = None)[source]

Bases: Exception

Exception if the maximum number of subscriptions per stream has been exceeded!

exception unicorn_binance_websocket_api.exceptions.Socks5ProxyConnectionError[source]

Bases: Exception

Exception if the manager class is not able to establish a connection to the socks5 proxy.

exception unicorn_binance_websocket_api.exceptions.StreamIsCrashing(stream_id=None, reason=None)[source]

Bases: Exception

Exception if the stream is crashing.

exception unicorn_binance_websocket_api.exceptions.StreamIsRestarting(stream_id=None, reason=None)[source]

Bases: Exception

Exception if the stream is restarting.

exception unicorn_binance_websocket_api.exceptions.StreamIsStopping(stream_id=None, reason=None)[source]

Bases: Exception

Exception if the stream is stopping.

exception unicorn_binance_websocket_api.exceptions.UnknownExchange(error_msg=None)[source]

Bases: Exception

Exception if the manager class is started with an unknown exchange.

unicorn_binance_websocket_api.manager module

class unicorn_binance_websocket_api.manager.BinanceWebSocketApiManager(process_stream_data: Callable | None = None, process_stream_data_async: Callable | None = None, process_asyncio_queue: Callable | None = None, exchange: str = 'binance.com', warn_on_update: bool = True, restart_timeout: int = 6, show_secrets_in_logs: bool = False, output_default: Literal['dict', 'raw_data', 'UnicornFy'] | None = 'raw_data', enable_stream_signal_buffer: bool = False, disable_colorama: bool = False, stream_buffer_maxlen: int | None = None, process_stream_signals=None, close_timeout_default: int = 1, ping_interval_default: int = 5, ping_timeout_default: int = 10, high_performance: bool = False, debug: bool = False, restful_base_uri: str | None = None, websocket_base_uri: str | None = None, websocket_api_base_uri: str | None = None, max_subscriptions_per_stream: int | None = None, exchange_type: Literal['cex', 'dex', None] | None = None, socks5_proxy_server: str | None = None, socks5_proxy_user: str | None = None, socks5_proxy_pass: str | None = None, socks5_proxy_ssl_verification: bool = True, auto_data_cleanup_stopped_streams: bool = False, lucit_api_secret: str | None = None, lucit_license_ini: str | None = None, lucit_license_profile: str | None = None, lucit_license_token: str | None = None, ubra_manager: BinanceRestApiManager | None = None)[source]

Bases: Thread

A Python SDK by LUCIT to use the Binance Websocket API`s (com+testnet, com-margin+testnet, com-isolated_margin+testnet, com-futures+testnet, com-coin_futures, us, “tr”, dex/chain+testnet) in a simple, fast, flexible, robust and fully-featured way.

This library supports two different kind of websocket endpoints:

  • CEX (Centralized exchange): “binance.com”, “binance.vision”, “binance.je”, “binance.us”, “trbinance.com”

  • DEX (Decentralized exchange): “binance.org”

Binance.com websocket API documentation:

Binance.vision (Testnet) websocket API documentation:

Binance.us websocket API documentation:

TRBinance.com websocket API documentation:

Binance.org websocket API documentation:

Parameters:
  • process_asyncio_queue (Optional[Callable]) – Insert your Asyncio function into the same AsyncIO loop in which the websocket data is received. This method guarantees the fastest possible asynchronous processing of the data in the correct receiving sequence. https://unicorn-binance-websocket-api.docs.lucit.tech/readme.html#or-await-the-webstream-data-in-an-asyncio-coroutine

  • process_stream_data (Optional[Callable]) – Provide a function/method to process the received webstream data (callback). The function will be called instead of add_to_stream_buffer() like process_stream_data(stream_data, stream_buffer_name) where stream_data contains the raw_stream_data. If not provided, the raw stream_data will get stored in the stream_buffer or provided to a specific callback function of create_stream()! How to read from stream_buffer!

  • process_stream_data_async (Optional[Callable]) – Provide an asyncio function/method to process the received webstream data (callback). The function will be called instead of add_to_stream_buffer() like process_stream_data(stream_data, stream_buffer_name) where stream_data contains the raw_stream_data. If not provided, the raw stream_data will get stored in the stream_buffer or provided to a specific callback function of create_stream()! How to read from stream_buffer!

  • exchange (str) – Select binance.com, binance.com-testnet, binance.com-margin, binance.com-margin-testnet, binance.com-isolated_margin, binance.com-isolated_margin-testnet, binance.com-futures, binance.com-futures-testnet, binance.com-coin_futures, binance.us, trbinance.com, binance.org, binance.org-testnet (default: binance.com)

  • warn_on_update (bool) – set to False to disable the update warning of UBWA and also in UBRA used as submodule.

  • restart_timeout (int) – A stream restart must be successful within this time, otherwise a new restart will be initialized. Default is 6 seconds.

  • show_secrets_in_logs (bool) – set to True to show secrets like listen_key, api_key or api_secret in log file (default=False)

  • output_default (str) – set to “dict” to convert the received raw data to a python dict, set to “UnicornFy” to convert with UnicornFy - otherwise with the default setting “raw_data” the output remains unchanged and gets delivered as received from the endpoints. Change this for a specific stream with the output parameter of create_stream() and replace_stream()

  • enable_stream_signal_buffer (bool) – set to True to enable the stream_signal_buffer and receive information about disconnects and reconnects to manage a restore of the lost data during the interruption or to recognize your bot got blind.

  • disable_colorama (bool) – set to True to disable the use of colorama

  • stream_buffer_maxlen (int or None) – Set a max len for the generic stream_buffer. This parameter can also be used within create_stream() for a specific stream_buffer.

  • process_stream_signals (function) – Provide a function/method to process the received stream signals. The function is running inside an asyncio loop and will be called instead of add_to_stream_signal_buffer() like process_stream_data(signal_type=False, stream_id=False, data_record=False).

  • auto_data_cleanup_stopped_streams (bool) – The parameter “auto_data_cleanup_stopped_streams=True” can be used to inform the UBWA instance that all remaining data of a stopped stream should be automatically and completely deleted.

  • close_timeout_default (int) – The close_timeout parameter defines a maximum wait time in seconds for completing the closing handshake and terminating the TCP connection. This parameter is passed through to the websockets.client.connect()

  • ping_interval_default (int) – Once the connection is open, a Ping frame is sent every ping_interval seconds. This serves as a keepalive. It helps keeping the connection open, especially in the presence of proxies with short timeouts on inactive connections. Set ping_interval to None to disable this behavior. This parameter is passed through to the websockets.client.connect()

  • ping_timeout_default (int) – If the corresponding Pong frame isn’t received within ping_timeout seconds, the connection is considered unusable and is closed with code 1011. This ensures that the remote endpoint remains responsive. Set ping_timeout to None to disable this behavior. This parameter is passed through to the websockets.client.connect()

  • high_performance (bool) – Set to True makes create_stream() a non-blocking function

  • debug (bool) – If True the lib adds additional information to logging outputs

  • restful_base_uri (str) – Override restful_base_uri. Example: https://127.0.0.1

  • websocket_base_uri (str) – Override websocket_base_uri. Example: ws://127.0.0.1:8765/

  • websocket_api_base_uri (str) – Override websocket_api_base_uri. Example: ws://127.0.0.1:8765/

  • max_subscriptions_per_stream (int) – Override the max_subscriptions_per_stream value. Example: 1024

  • exchange_type (str) – Override the exchange type. Valid options are: ‘cex’, ‘dex’

  • socks5_proxy_server (str) – Set this to activate the usage of a socks5 proxy. Example: ‘127.0.0.1:9050’

  • socks5_proxy_user (str) – Set this to activate the usage of a socks5 proxy user. Example: ‘alice’

  • socks5_proxy_pass (str) – Set this to activate the usage of a socks5 proxy password.

  • socks5_proxy_ssl_verification (bool) – Set to False to disable SSL server verification. Default is True.

  • lucit_api_secret (str) – The api_secret of your UNICORN Binance Suite license from https://shop.lucit.services/software/unicorn-binance-suite

  • lucit_license_ini (str) – Specify the path including filename to the config file (ex: ~/license_a.ini). If not provided lucitlicmgr tries to load a lucit_license.ini from /home/oliver/.lucit/.

  • lucit_license_profile (str) – The license profile to use. Default is ‘LUCIT’.

  • lucit_license_token (str) – The license_token of your UNICORN Binance Suite license from https://shop.lucit.services/software/unicorn-binance-suite

  • ubra_manager (BinanceRestApiManager) – Provide a shared unicorn_binance_rest_api.manager instance

add_payload_to_stream(stream_id=None, payload: dict | None = None)[source]

Add a payload to a stream by stream_id.

Parameters:
  • stream_id (str) – id of a stream

  • payload (dict) – The payload in JSON to add.

Returns:

bool

add_to_ringbuffer_error(error)[source]

Add received error messages from websocket endpoints to the error ringbuffer

Parameters:

error (string) – The data to add.

Returns:

bool

add_to_ringbuffer_result(result)[source]

Add received result messages from websocket endpoints to the result ringbuffer

Parameters:

result (string) – The data to add.

Returns:

bool

add_to_stream_buffer(stream_data, stream_buffer_name: Literal[False] | str = False)[source]

Kick back data to the stream_buffer

If it is not possible to process received stream data (for example, the database is restarting, so it’s not possible to save the data), you can return the data back into the stream_buffer. After a few seconds you stopped writing data back to the stream_buffer, the BinanceWebSocketApiManager starts flushing back the data to normal processing.

Parameters:
  • stream_data (raw stream_data or unicorn_fied stream data) – the data you want to write back to the buffer

  • stream_buffer_name (False or str) – If False the data is going to get written to the default stream_buffer, set to True to read the data via pop_stream_data_from_stream_buffer(stream_id) or provide a string to create and use a shared stream_buffer and read it via pop_stream_data_from_stream_buffer(‘string’).

Returns:

bool

add_to_stream_signal_buffer(signal_type=None, stream_id=None, data_record=None, error_msg=None)[source]

Add signals about a stream to the stream_signal_buffer

Parameters:
  • signal_type (str) – “CONNECT”, “DISCONNECT”, “FIRST_RECEIVED_DATA” or “STREAM_UNREPAIRABLE”

  • stream_id (str) – id of a stream

  • data_record (str or dict) – The last or first received data record

  • error_msg (str or dict) – The message of the error.

Returns:

bool

add_total_received_bytes(size)[source]

Add received bytes to the total received bytes statistic

Parameters:

size (int) – int value of added bytes

asyncio_queue_task_done(stream_id=None) bool[source]

If get_stream_data_from_asyncio_queue() was used, asyncio_queue_task_done() must be executed at the end of the loop.

Parameters:

stream_id (str) – provide a stream_id - only needed for userData Streams (acquiring a listenKey)

Returns:

bool

Example:

. code-block:: python

while True:

data = await ubwa.get_stream_data_from_asyncio_queue(stream_id) print(data) ubwa.asyncio_queue_task_done(stream_id)

clear_asyncio_queue(stream_id: str | None = None) bool[source]

Clear the asyncio queue of a specific stream.

Parameters:

stream_id (str) – provide a stream_id

Returns:

bool

clear_stream_buffer(stream_buffer_name: Literal[False] | str = False)[source]

Clear the stream_buffer

Parameters:

stream_buffer_name (False or str) – False to read from generic stream_buffer, the stream_id if you used True in create_stream() or the string name of a shared stream_buffer.

Returns:

bool

create_payload(stream_id, method, channels=None, markets=None)[source]

Create the payload for subscriptions

Parameters:
  • stream_id (str) – provide a stream_id

  • method (str) – SUBSCRIBE or UNSUBSCRIBE

  • channels (str, list, set) – provide the channels to create the URI

  • markets (str, list, set) – provide the markets to create the URI

Returns:

payload (list) or False

create_stream(channels: str | List[str] | Set[str] | None = None, markets: str | List[str] | Set[str] | None = None, stream_label: str | None = None, stream_buffer_name: Literal[False] | str = False, api_key: str | None = None, api_secret: str | None = None, symbols: str | List[str] | Set[str] | None = None, output: Literal['dict', 'raw_data', 'UnicornFy'] | None = None, ping_interval: int | None = None, ping_timeout: int | None = None, close_timeout: int | None = None, listen_key: str | None = None, keep_listen_key_alive: bool = True, stream_buffer_maxlen: int | None = None, api: bool = False, process_stream_data: Callable | None = None, process_stream_data_async: Callable | None = None, process_asyncio_queue: Callable | None = None)[source]

Create a websocket stream

If you provide 2 markets and 2 channels, then you are going to create 4 subscriptions (markets * channels).

Example:

channels = [‘trade’, ‘kline_1’]

markets = [‘bnbbtc’, ‘ethbtc’]

Finally: bnbbtc@trade, ethbtc@trade, bnbbtc@kline_1, ethbtc@kline_1

There is a subscriptions limit per stream!

Create !userData streams as single streams, because it’s using a different endpoint and can not get combined with other streams in a multiplexed stream!

Example CEX:

binance_websocket_api_manager.create_stream(["arr"], ["!userData"], api_key="aaa", api_secret="bbb")

Isolated Margin:

binance_websocket_api_manager.create_stream(["arr"], ["!userData"], api_key="aaa", api_secret="bbb", symbols="ankrbtc")

Example DEX:

binance_websocket_api_manager.create_stream(['orders', 'transfers', 'accounts'], binance_dex_user_address)

To create a multiplexed stream which includes also !miniTicker@arr, !ticker@arr, !forceOrder@arr or !bookTicker@arr you just need to add !bookTicker to the channels list - don’t add arr (cex) or $all (dex) to the markets list.

Example:

binance_websocket_api_manager.create_stream(['kline_5m', 'marketDepth', '!miniTicker'], ['bnbbtc'])

But you have to add arr or $all if you want to start it as a single stream!

Example:

binance_websocket_api_manager.create_stream(["arr"], ["!miniTicker"])

Parameters:
  • channels (str, list, set) – provide the channels you wish to stream

  • markets (str, list, set) – provide the markets you wish to stream

  • stream_label (str) – provide a stream_label to identify the stream

  • stream_buffer_name (bool or str) – If False the data is going to get written to the default stream_buffer, set to True to read the data via pop_stream_data_from_stream_buffer(stream_id) or provide a string to create and use a shared stream_buffer and read it via pop_stream_data_from_stream_buffer(‘string’).

  • api_key (str) – provide a valid Binance API key

  • api_secret (str) – provide a valid Binance API secret

  • symbols (str, list, set) – provide the symbols for isolated_margin user_data streams

  • output (str) – the default setting raw_data can be globally overwritten with the parameter output_default of BinanceWebSocketApiManager`. To overrule the output_default value for this specific stream, set output to “dict” to convert the received raw data to a python dict, set to “UnicornFy” to convert with UnicornFy - otherwise with the default setting “raw_data” the output remains unchanged and gets delivered as received from the endpoints

  • ping_interval (int or None) – Once the connection is open, a Ping frame is sent every ping_interval seconds. This serves as a keepalive. It helps keeping the connection open, especially in the presence of proxies with short timeouts on inactive connections. Set ping_interval to None to disable this behavior. (default: 20) This parameter is passed through to the websockets.client.connect()

  • ping_timeout (int or None) – If the corresponding Pong frame isn’t received within ping_timeout seconds, the connection is considered unusable and is closed with code 1011. This ensures that the remote endpoint remains responsive. Set ping_timeout to None to disable this behavior. (default: 20) This parameter is passed through to the websockets.client.connect()

  • close_timeout (int or None) – The close_timeout parameter defines a maximum wait time in seconds for completing the closing handshake and terminating the TCP connection. (default: 10) This parameter is passed through to the websockets.client.connect()

  • keep_listen_key_alive (str) – True (default) or False.

  • listen_key (str) – Provide the Binance listenKey for the userData stream.

  • stream_buffer_maxlen (int or None) – Set a max len for the stream_buffer. Only used in combination with a non-generic stream_buffer. The generic stream_buffer uses always the value of BinanceWebSocketApiManager().

  • api (bool) – Setting this to True activates the creation of a Websocket API stream to send API requests via Websocket. Needs api_key and api_secret in combination. This type of stream can not be combined with a UserData stream or another public endpoint. (Default is False)

  • process_stream_data (function) – Provide a function/method to process the received webstream data (callback). The function will be called instead of add_to_stream_buffer() like process_stream_data(stream_data) where stream_data contains the raw_stream_data. If not provided, the raw stream_data will get stored in the stream_buffer or provided to the global callback function provided during object instantiation! How to read from stream_buffer!

  • process_stream_data_async (function) – Provide an asynchronous function/method to process the received webstream data (callback). The function will be called instead of add_to_stream_buffer() like process_stream_data(stream_data) where stream_data contains the raw_stream_data. If not provided, the raw stream_data will get stored in the stream_buffer or provided to the global callback function provided during object instantiation! How to read from stream_buffer!

  • process_asyncio_queue (Optional[Callable]) – Insert your Asyncio function into the same AsyncIO loop in which the websocket data is received. This method guarantees the fastest possible asynchronous processing of the data in the correct receiving sequence. https://unicorn-binance-websocket-api.docs.lucit.tech/readme.html#or-await-the-webstream-data-in-an-asyncio-coroutine

Returns:

stream_id or ‘None’

create_websocket_uri(channels, markets, stream_id=None, symbols=None, api=False)[source]

Create a websocket URI

Parameters:
  • channels (str, list, set) – provide the channels to create the URI

  • markets (str, list, set) – provide the markets to create the URI

  • stream_id (str) – provide a stream_id - only needed for userData Streams (acquiring a listenKey)

  • symbols (str) – provide the symbols for isolated_margin user_data streams

  • api (bool) – Setting this to True activates the creation of a Websocket API stream to send API requests via Websocket. Needs api_key and api_secret in combination. This type of stream can not be combined with a UserData stream or another public endpoint. (Default is False)

Returns:

str or False

delete_listen_key_by_stream_id(stream_id) bool[source]

Delete a binance listen_key from a specific !userData stream

Parameters:

stream_id (str) – id of a !userData stream

Returns:

bool

delete_stream_from_stream_list(stream_id, timeout: float = 10.0) bool[source]

Delete a stream from the stream_list

Even if a stream crashes or get stopped, its data remains in the BinanceWebSocketApiManager till you stop the BinanceWebSocketApiManager itself. If you want to tidy up the stream_list you can use this method.

Parameters:
  • stream_id (str) – id of a stream

  • timeout (float) – The timeout for how long to wait for the stream to stop. The function aborts if the waiting time is exceeded and returns False.

Returns:

bool

static fill_up_space_centered(demand_of_chars, string, filling=' ')[source]

Add whitespaces to string to a length of demand_of_chars

Parameters:
  • demand_of_chars (int) – how much chars does the string have to have?

  • string (str) – the string that has to get filled up with spaces

  • filling (str) – filling char (default: blank space)

Returns:

the filled up string

static fill_up_space_left(demand_of_chars, string, filling=' ')[source]

Add whitespaces to string to a length of demand_of_chars on the left side

Parameters:
  • demand_of_chars (int) – how much chars does the string have to have?

  • string (str) – the string that has to get filled up with spaces

  • filling (str) – filling char (default: blank space)

Returns:

the filled up string

static fill_up_space_right(demand_of_chars, string, filling=' ')[source]

Add whitespaces to string to a length of demand_of_chars on the right side

Parameters:
  • demand_of_chars (int) – how much chars does the string have to have?

  • string (str) – the string that has to get filled up with spaces

  • filling (str) – filling char (default: blank space)

Returns:

the filled up string

generate_signature(api_secret=None, data=None)[source]

Signe the request.

Parameters:
  • api_secret

  • data

Returns:

get_active_stream_list()[source]

Get a list of all active streams

Returns:

set or False

get_all_receives_last_second()[source]

Get the number of all receives of the last second

Returns:

int

get_binance_api_status()[source]

get_binance_api_status() is obsolete and will be removed in future releases, please use get_used_weight() instead!

Returns:

dict

get_current_receiving_speed(stream_id)[source]

Get the receiving speed of the last second in Bytes

Returns:

int

get_current_receiving_speed_global()[source]

Get the receiving speed of the last second in Bytes from all streams!

Returns:

int

static get_date_of_timestamp(timestamp)[source]

Convert a timestamp into a readable date/time format for humans

Parameters:

timestamp (timestamp) – provide the timestamp you want to convert into a date

Returns:

str

get_debug_log()[source]

Get the debug log string.

Returns:

str

get_errors_from_endpoints()[source]

Get all the stored error messages from the ringbuffer sent by the endpoints.

Returns:

list

get_event_loop_by_stream_id(stream_id: str | bool | None = False) AbstractEventLoop | None[source]

Get the asyncio event loop used by a specific stream.

Returns:

asyncio.AbstractEventLoop or None

get_exchange()[source]

Get the name of the used exchange like “binance.com” or “binance.org-testnet”

Returns:

str

static get_human_bytesize(amount_bytes, suffix='')[source]

Convert the bytes to something readable

Parameters:
  • amount_bytes (int) – amount of bytes

  • suffix (str) – add a string after

Returns:

static get_human_uptime(uptime)[source]

Convert a timespan of seconds into hours, days, …

Parameters:

uptime (int) – Uptime in seconds

Returns:

get_keep_max_received_last_second_entries()[source]

Get the number of how much received_last_second entries are stored till they get deleted

Returns:

int

static get_latest_release_info()[source]

Get infos about the latest available release

Returns:

dict or None

static get_latest_release_info_check_command()[source]

Get infos about the latest available check_lucit_collector release

Returns:

dict or None

get_latest_version() str | None[source]

Get the version of the latest available release (cache time 1 hour)

Returns:

str or None

get_latest_version_check_command() str | None[source]

Get the version of the latest available check_lucit_collector.py release (cache time 1 hour)

Returns:

str or None

get_limit_of_subscriptions_per_stream()[source]

Get the number of allowed active subscriptions per stream (limit of binance API)

Returns:

int

get_listen_key_from_restclient(stream_id)[source]

Get a new or cached (<30m) listen_key

Parameters:

stream_id (str) – provide a stream_id

get_monitoring_status_icinga(check_command_version=False, warn_on_update=True)[source]

Get status and perfdata to monitor and collect metrics with ICINGA/Nagios

status: OK, WARNING, CRITICAL - WARNING: on restarts, available updates - CRITICAL: crashed streams

perfdata: - average receives per second since last status check - average speed per second since last status check - total received bytes since start - total received length since start - stream_buffer size - stream_buffer length - reconnects - uptime

Parameters:
  • check_command_version (str) – is the version of the calling check_command

  • warn_on_update (bool) – set to False to disable the update warning

Returns:

dict (text, time, return_code)

get_monitoring_status_plain(check_command_version=False, warn_on_update=True)[source]

Get plain monitoring status data: active_streams, crashed_streams, restarting_streams, stopped_streams, return_code, status_text, timestamp, update_msg, average_receives_per_second, average_speed_per_second, total_received_mb, stream_buffer_items, stream_buffer_mb, reconnects, uptime

Parameters:
  • check_command_version (False or str) – is the version of the calling check_command

  • warn_on_update (bool) – set to False to disable the update warning

Returns:

dict

get_most_receives_per_second()[source]

Get the highest total receives per second value

Returns:

int

static get_new_uuid_id() str[source]

Get a new unique uuid in string format. This is used as ‘stream_id’ or ‘socket_id’.

Returns:

uuid (str)

get_number_of_all_subscriptions()[source]

Get the amount of all stream subscriptions

Returns:

int

get_number_of_free_subscription_slots(stream_id)[source]

Get the number of free subscription slots (max allowed subscriptions - subscriptions) of a specific stream

Returns:

int

get_number_of_streams_in_stream_list()[source]

Get the number of streams that are stored in the stream_list

Returns:

int

get_number_of_subscriptions(stream_id)[source]

Get the number of subscriptions of a specific stream

Returns:

int

static get_process_usage_cpu()[source]

Get the used cpu power of this process

Returns:

int

get_process_usage_memory()[source]

Get the used memory of this process

Returns:

str

static get_process_usage_threads()[source]

Get the amount of threads that this process is using

Returns:

int

get_reconnects()[source]

Get the number of total reconnects

Returns:

int

get_request_id()[source]

Get a unique request_id

Returns:

int

get_result_by_request_id(request_id=None, timeout=10)[source]

Get the result related to the provided request_id

Parameters:
  • request_id (stream_id (uuid)) – if you run get_stream_subscriptions() it returns a unique request_id - provide it to this method to receive the result.

  • timeout (int) – seconds to wait to receive the result. If not there it returns ‘False’

Returns:

result or None

get_results_from_endpoints()[source]

Get all the stored result messages from the ringbuffer sent by the endpoints.

Returns:

list

get_ringbuffer_error_max_size()[source]

How many entries should be stored in the ringbuffer?

Returns:

int

get_ringbuffer_result_max_size()[source]

How many entries should be stored in the ringbuffer?

Returns:

int

get_start_time()[source]

Get the start_time of the BinanceWebSocketApiManager instance

Returns:

timestamp

get_stream_buffer_byte_size()[source]

Get the current byte size estimation of the stream_buffer

Returns:

int

get_stream_buffer_length(stream_buffer_name: Literal[False] | str = False)[source]

Get the current number of items in all stream_buffer or of a specific stream_buffer

Parameters:

stream_buffer_name (str or stream_id) – Name of the stream_buffer

Returns:

int

get_stream_buffer_maxlen(stream_buffer_name: Literal[False] | str = False)[source]

Get the maxlen value of the stream_buffer

If maxlen is not specified or is None, stream_buffer may grow to an arbitrary length. Otherwise, the stream_buffer is bounded to the specified maximum length. Once a bounded length stream_buffer is full, when new items are added, a corresponding number of items are discarded from the opposite end.

Parameters:

stream_buffer_name (False or str) – False to read from generic stream_buffer, the stream_id if you used True in create_stream() or the string name of a shared stream_buffer.

Returns:

int or False

async get_stream_data_from_asyncio_queue(stream_id=None)[source]

Retrieves the oldest entry from the FIFO stack.

Parameters:

stream_id (str) – provide a stream_id - only needed for userData Streams (acquiring a listenKey)

Returns:

stream_data - str, dict or None

get_stream_id_by_label(stream_label: str | None = None) str | None[source]

Get the stream_id of a specific stream by stream label

Parameters:

stream_label (str) – stream_label of the stream you search

Returns:

stream_id or None

get_stream_info(stream_id)[source]

Get all infos about a specific stream

Parameters:

stream_id (str) – id of a stream

Returns:

set

get_stream_label(stream_id=None)[source]

Get the stream_label of a specific stream

Parameters:

stream_id (str) – id of a stream

Returns:

str or None

get_stream_list()[source]

Get a list of all streams

Returns:

set

get_stream_receives_last_second(stream_id)[source]

Get the number of receives of specific stream from the last seconds

Parameters:

stream_id (str) – id of a stream

Returns:

int

get_stream_statistic(stream_id)[source]

Get the statistic of a specific stream

Parameters:

stream_id (str) – id of a stream

Returns:

set

get_stream_subscriptions(stream_id, request_id=None)[source]

Get a list of subscriptions of a specific stream from Binance endpoints - the result can be received via the stream_buffer and is also added to the results ringbuffer - get_results_from_endpoints() to get all results or use get_result_by_request_id(request_id) to get a specific one!

This function is supported by CEX endpoints only!

Info: https://github.com/binance-exchange/binance-official-api-docs/blob/master/web-socket-streams.md#listing-subscriptions

Parameters:
  • stream_id (str) – id of a stream

  • request_id (int) – id to use for the request - use get_request_id() to create a unique id. If not provided or False, then this method is using get_request_id() automatically.

Returns:

request_id (int)

get_the_one_active_websocket_api() str | None[source]

This function is needed to simplify the access to the websocket API, if only one API stream exists it is clear that only this stream can be used for the requests and therefore will be used.

Returns:

stream_id or None (str)

static get_timestamp() int[source]

Get a Binance conform Timestamp.

Returns:

int

static get_timestamp_unix() float[source]

Get a Binance conform Timestamp.

Returns:

float

get_total_received_bytes()[source]

Get number of total received bytes

Returns:

int

get_total_receives()[source]

Get the number of total receives

Returns:

int

get_used_weight()[source]

Get used_weight, last status_code and the timestamp of the last status update

Returns:

dict

get_user_agent()[source]

Get the user_agent string “lib name + lib version + python version”

Returns:

get_version()[source]

Get the package/module version

Returns:

str

static get_version_unicorn_fy()[source]

Get the package/module version of UnicornFy

Returns:

str

static help()[source]

Help in iPython

increase_processed_receives_statistic(stream_id)[source]

Add the number of processed receives

Parameters:

stream_id (str) – id of a stream

increase_received_bytes_per_second(stream_id, size)[source]

Add the amount of received bytes per second

Parameters:
  • stream_id (str) – id of a stream

  • size (int) – amount of bytes to add

increase_reconnect_counter(stream_id=None)[source]

Increase reconnect counter

Parameters:

stream_id (str) – id of a stream

increase_transmitted_counter(stream_id)[source]

Increase the counter of transmitted payloads :param stream_id: id of a stream :type stream_id: str

is_crash_request(stream_id) bool[source]

Has a specific stream a crash_request?

Parameters:

stream_id (str) – id of a stream

Returns:

bool

is_exchange_type(exchange_type: str | None = None)[source]

Check the exchange type!

Parameters:

exchange_type (str) – Valid types are dex and cex!

Returns:

bool

is_manager_stopping()[source]

Returns True if the manager has a stop request, ‘False’ if not.

Returns:

bool

is_socket_ready(stream_id: str | None = None) bool[source]

Set socket_is_ready for a specific stream to False.

Parameters:

stream_id (str) – id of the stream

is_stop_request(stream_id) bool[source]

Has a specific stream a stop_request?

Parameters:

stream_id (str) – id of a stream

Returns:

bool

is_stream_signal_buffer_enabled()[source]

Is the stream_signal_buffer enabled?

Returns:

bool

is_update_available()[source]

Is a new release of this package available?

Returns:

bool

is_update_available_check_command(check_command_version=None)[source]

Is a new release of check_lucit_collector.py available?

Returns:

bool

static is_update_available_unicorn_fy()[source]

Is a new release of UnicornFy available?

Returns:

bool

static order_params(data)[source]

Convert params to list with signature as last element

Parameters:

data

Returns:

pop_stream_data_from_stream_buffer(stream_buffer_name: Literal[False] | str | None = None, mode='FIFO')[source]

Get oldest or latest entry from stream_buffer and remove from FIFO/LIFO stack.

Parameters:
  • stream_buffer_name (False or str) – False to read from generic stream_buffer, the stream_id if you used True in create_stream() or the string name of a shared stream_buffer.

  • mode (str) – How to read from the stream_buffer - “FIFO” (default) or “LIFO”.

Returns:

stream_data - str, dict or None

pop_stream_signal_from_stream_signal_buffer()[source]

Get the oldest entry from stream_signal_buffer and remove from stack/pipe (FIFO stack)

Returns:

stream_signal - dict or False

print_stream_info(stream_id: str | None = None, add_string: str | None = None, footer: str | None = None, title: str | None = None)[source]

Print all infos about a specific stream, helps debugging :)

Parameters:
  • stream_id (str) – id of a stream

  • add_string (str) – text to add to the output

  • footer (str) – set a footer (last row) for print_summary output

  • title (str) – set to True to use curses instead of print()

print_summary(add_string: str | None = None, disable_print: bool = False, footer: str | None = None, title: str | None = None)[source]

Print an overview of all streams

Parameters:
  • add_string (str) – text to add to the output

  • disable_print (bool) – set to True to use curses instead of print()

  • footer (str) – set a footer (last row) for print_summary output

  • title (str) – set a title (first row) for print_summary output

print_summary_to_png(print_summary_export_path, height_per_row=12.5, add_string: str | None = None, footer: str | None = None, title: str | None = None)[source]

Create a PNG image file with the console output of print_summary()

LINUX ONLY It should not be hard to make it OS independent: https://github.com/LUCIT-Systems-and-Development/unicorn-binance-websocket-api/issues/61

Parameters:
  • print_summary_export_path (str) – If you want to export the output of print_summary() to an image, please provide a path like “/var/www/html/”. View the Wiki!

  • height_per_row (float) – set the height per row for the image height calculation

  • add_string (str) – text to add to the output

  • footer (str) – set a footer (last row) for print_summary output

  • title (str) – set a title (first row) for print_summary output

Returns:

bool

remove_all_data_of_stream_id(stream_id, timeout: float = 10.0) bool[source]

Delete all remaining data within the UBWA instance of a stopped stream.

Even if a stream crashes or get stopped, its data remains in the BinanceWebSocketApiManager till you stop the BinanceWebSocketApiManager itself. If you want to tidy up the entire UBWA instance you can use this method.

UnicornBinanceWebSocketApiManager accepts the parameter auto_data_cleanup_stopped_streams. If this is set to True (auto_data_cleanup_stopped_streams=True), the UBWA instance performs the cleanup with this function remove_all_data_of_stream_id() automatically and regularly.

Parameters:
  • stream_id (str) – id of a stream

  • timeout (float) – The timeout for how long to wait for the stream to stop. The function aborts if the waiting time is exceeded and returns False.

Returns:

bool

static remove_ansi_escape_codes(text)[source]

Remove ansi escape codes from the text string!

Parameters:

text (str) – The text :)

Returns:

str

replace_stream(stream_id, new_channels, new_markets, new_stream_label=None, new_stream_buffer_name: Literal[False] | str = False, new_api_key=None, new_api_secret=None, new_symbols=None, new_output: Literal['dict', 'raw_data', 'UnicornFy'] | None = None, new_ping_interval=20, new_ping_timeout=20, new_close_timeout=10, new_stream_buffer_maxlen=None)[source]

Replace a stream

If you want to start a stream with a new config, its recommended, to first start a new stream with the new settings and close the old stream not before the new stream received its first data. So your data will stay consistent.

Parameters:
  • stream_id (str) – id of the old stream

  • new_channels (str, tuple, list, set) – the new channel list for the stream

  • new_markets (str, tuple, list, set) – the new markets list for the stream

  • new_stream_label (str) – provide a stream_label to identify the stream

  • new_stream_buffer_name (False or str) – If False the data is going to get written to the default stream_buffer, set to True to read the data via pop_stream_data_from_stream_buffer(stream_id) or provide a string to create and use a shared stream_buffer and read it via pop_stream_data_from_stream_buffer(‘string’).

  • new_api_key (str) – provide a valid Binance API key

  • new_api_secret (str) – provide a valid Binance API secret

  • new_symbols (str) – provide the symbols for isolated_margin user_data streams

  • new_output (str) – set to “dict” to convert the received raw data to a python dict, set to “UnicornFy” to convert with UnicornFy - otherwise the output remains unchanged and gets delivered as received from the endpoints

  • new_ping_interval (int or None) – Once the connection is open, a Ping frame is sent every ping_interval seconds. This serves as a keepalive. It helps keeping the connection open, especially in the presence of proxies with short timeouts on inactive connections. Set ping_interval to None to disable this behavior. (default: 20) This parameter is passed through to the websockets.client.connect()

  • new_ping_timeout (int or None) – If the corresponding Pong frame isn’t received within ping_timeout seconds, the connection is considered unusable and is closed with code 1011. This ensures that the remote endpoint remains responsive. Set ping_timeout to None to disable this behavior. (default: 20) This parameter is passed through to the websockets.client.connect()

  • new_close_timeout (int or None) – The close_timeout parameter defines a maximum wait time in seconds for completing the closing handshake and terminating the TCP connection. (default: 10) This parameter is passed through to the websockets.client.connect()

  • new_stream_buffer_maxlen (int or None) – Set a max len for the stream_buffer. Only used in combination with a non-generic stream_buffer. The generic stream_buffer uses always the value of BinanceWebSocketApiManager().

Returns:

new stream_id

Returns:

stream_id or ‘None’

run()[source]

This method overloads threading.run() and starts management functions

send_stream_signal(signal_type=None, stream_id=None, data_record=None, error_msg=None) bool[source]

Send a stream signal

send_with_stream(stream_id: str | None = None, payload: dict | str | None = None, timeout: float = 5.0) bool[source]

Send a payload with a specific stream.

Parameters:
  • stream_id (str) – id of the stream to be used for sending.

  • payload (dict or str(JSON)) – The payload to add.

  • timeout (float or int) – Timeout to wait for a ready stream.

Returns:

bool

set_heartbeat(stream_id) None[source]

Set heartbeat for a specific thread (should only be done by the stream itself)

Returns:

None

set_keep_max_received_last_second_entries(number_of_max_entries)[source]

Set how much received_last_second entries are stored till they get deleted!

Parameters:

number_of_max_entries (int) – number of entries to keep in list

set_private_dex_config(binance_dex_user_address)[source]

Set binance_dex_user_address

Is going to be the default user_address, once the websocket is created with this default value, it’s not possible to change it. If you plan to use different user_address It’s recommended to not use this method! Just provide the user_address with create_stream() in the market parameter.

Parameters:

binance_dex_user_address (str) – Binance DEX user address

set_ringbuffer_error_max_size(max_size)[source]

How many error messages should be kept in the ringbuffer?

Parameters:

max_size (int) – Max entries of error messages in the ringbuffer.

Returns:

bool

set_ringbuffer_result_max_size(max_size)[source]

How many result messages should be kept in the ringbuffer?

Parameters:

max_size (int) – Max entries of result messages in the ringbuffer.

Returns:

bool

set_socket_is_not_ready(stream_id: str) bool[source]

Set socket_is_ready for a specific stream to False.

Parameters:

stream_id (str) – id of the stream

Returns:

bool

set_socket_is_ready(stream_id: str) bool[source]

Set socket_is_ready for a specific stream to True.

Parameters:

stream_id (str) – id of the stream

Returns:

bool

set_stop_request(stream_id=None)[source]

Set a stop request for a specific stream.

Returns:

None

set_stream_label(stream_id, stream_label=None) bool[source]

Set a stream_label by stream_id

Parameters:
  • stream_id (str) – id of the stream

  • stream_label (str) – stream_label to set

Returns:

bool

split_payload(params, method, max_items_per_request=350)[source]

Sending more than 8000 chars via websocket.send() leads to a connection loss, 350 list elements is a good limit to keep the payload length under 8000 chars and avoid reconnects

Parameters:
  • params (list) – params of subscribe payload

  • method (str) – SUBSCRIBE or UNSUBSCRIBE

  • max_items_per_request – max size for params, if more it gets split

Returns:

list or False

start_monitoring_api(host='127.0.0.1', port=64201, warn_on_update=True)[source]

Start the monitoring API server

Take a look into the Wiki to see how this works!

Parameters:
  • host (str) – listening ip address, use 0.0.0.0 or a specific address (default: 127.0.0.1)

  • port (int) – listening port number (default: 64201)

  • warn_on_update (bool) – set to False to disable the update warning

stop_manager(close_api_session: bool = True)[source]

Stop the BinanceWebSocketApiManager with all streams, monitoring and management threads

stop_manager_with_all_streams(close_api_session: bool = True)[source]

Stop the BinanceWebSocketApiManager with all streams, monitoring and management threads

Alias of ‘stop_manager()’

stop_monitoring_api() bool[source]

Stop the monitoring API service

Returns:

bool

stop_stream(stream_id, delete_listen_key: bool = True)[source]

Stop a specific stream

Parameters:
  • stream_id (str) – id of a stream

  • delete_listen_key (str) – If set to True (default), the listen_key gets deleted. Set to False if you run more than one userData stream with this listen_key!

Returns:

bool

subscribe_to_stream(stream_id: str | None = None, channels=None, markets=None) bool[source]

Subscribe channels and/or markets to an existing stream

If you provide one channel and one market, then every subscribed market is going to get added to the new channel and all subscribed channels are going to get added to the new market!

How are the parameter `channels and markets used with subscriptions

Parameters:
  • stream_id (str) – id of a stream

  • channels (str, list, set) – provide the channels you wish to subscribe

  • markets (str, list, set) – provide the markets you wish to subscribe

Returns:

bool

unsubscribe_from_stream(stream_id: str | None = None, channels=None, markets=None) bool[source]

Unsubscribe channels and/or markets to an existing stream

If you provide one channel and one market, then all subscribed markets from the specific channel and all subscribed channels from the specific markets are going to be removed!

How are the parameter `channels and markets used with subscriptions

Parameters:
  • stream_id (str) – id of a stream

  • channels (str, list, set) – provide the channels you wish to unsubscribe

  • markets (str, list, set) – provide the markets you wish to unsubscribe

Returns:

bool

wait_till_stream_has_started(stream_id, timeout: float = 0.0) bool[source]

Returns True as soon a specific stream has started and received its first stream data

Parameters:
  • stream_id (str) – id of a stream

  • timeout (float) – The timeout for how long to wait for the stream to stop. The function aborts if the waiting time is exceeded and returns False.

Returns:

bool

wait_till_stream_has_stopped(stream_id: str | None = None, timeout: float = 0.0) bool[source]

Returns True as soon a specific stream has stopped itself

Parameters:
  • stream_id (str) – id of a stream

  • timeout (float) – The timeout for how long to wait for the stream to stop. The function aborts if the waiting time is exceeded and returns False.

Returns:

bool

unicorn_binance_websocket_api.restclient module

class unicorn_binance_websocket_api.restclient.BinanceWebSocketApiRestclient(debug: bool | None = False, disable_colorama: bool | None = False, exchange: str | None = 'binance.com', lucit_api_secret: str | None = None, lucit_license_ini: str | None = None, lucit_license_profile: str | None = None, lucit_license_token: str | None = None, restful_base_uri: str | None = None, show_secrets_in_logs: bool | None = False, socks5_proxy_server: str | None = None, socks5_proxy_user: str | None = None, socks5_proxy_pass: str | None = None, socks5_proxy_ssl_verification: bool | None = True, stream_list: dict | None = None, ubra: BinanceRestApiManager | None = None, warn_on_update: bool | None = True)[source]

Bases: object

delete_listen_key(stream_id=None) Tuple[str | None, dict | None][source]

Delete a specific listen key

Parameters:

stream_id (str) – provide a stream_id

Returns:

listen_key, binance_api_status

Return type:

Tuple[Union[str, None], Union[dict, None]]

get_binance_api_status() dict[source]

Get the used weight of the last api request, with a current timestamp.

Returns:

binance_api_status

Return type:

dict

get_listen_key(stream_id=None) Tuple[dict | None, dict | None][source]

Request a valid listen_key from binance

Parameters:

stream_id (str) – provide a stream_id

Returns:

response, binance_api_status

Return type:

Tuple[Union[dict, None], Union[dict, None]]

keepalive_listen_key(stream_id=None) Tuple[str | None, dict | None][source]

Ping a listenkey to keep it alive

Parameters:

stream_id (str) – provide a stream_id

Returns:

listen_key, binance_api_status

Return type:

Tuple[Union[str, None], Union[dict, None]]

stop() bool[source]

Stop this instance!r

Return type:

bool

unicorn_binance_websocket_api.restserver module

class unicorn_binance_websocket_api.restserver.BinanceWebSocketApiRestServer(handler_binance_websocket_api_manager, warn_on_update=True)[source]

Bases: Resource

Provide a REST API server

Description: https://github.com/LUCIT-Systems-and-Development/unicorn-binance-websocket-api/wiki/UNICORN-Monitoring-API-Service

Parameters:
  • handler_binance_websocket_api_manager (function) – Provide the handler of the binance_websocket_api_manager

  • warn_on_update (bool) – set to ‘False’ to avoid a warning on available updates

get(statusformat, checkcommandversion=False)[source]

Get the status of the ‘UNICORN Binance WebSocket API Manager’

Parameters:
  • statusformat (str) – Choose the format for the export (e.g. ‘icinga’)

  • checkcommandversion (bool) – Control if there is a new version of the check_command available!

Returns:

status message of ‘UNICORN Binance WebSocket API Manager’

Return type:

list (status string, http status code)

methods: t.ClassVar[t.Optional[t.Collection[str]]] = {'GET'}

The methods this view is registered for. Uses the same default (["GET", "HEAD", "OPTIONS"]) as route and add_url_rule by default.

unicorn_binance_websocket_api.sockets module

class unicorn_binance_websocket_api.sockets.BinanceWebSocketApiSocket(manager, stream_id, channels, markets)[source]

Bases: object

raise_exceptions()[source]
async start_socket()[source]

Module contents