unicorn_binance_websocket_api package

Submodules

unicorn_binance_websocket_api.api module

unicorn_binance_websocket_api.api.futures module

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

Bases: object

Connect to Binance Futures API via Websocket.

Namespace: ubwa.api.futures.*:

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.

Todo:

Read these instructions to get started:

Binance.com Futures websocket API documentation:

Parameters:

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

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

Cancel order (TRADE)

Cancel an active order.

Either order_id or orig_client_order_id must be sent.

Weight: 1

Official documentation:

Parameters:
  • 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:

str, dict, bool

Message sent:

{
    "id": "5633b6a2-90a9-4192-83e7-925c90b6a2fd",
    "method": "order.cancel",
    "params": {
        "apiKey": "HsOehcfih8ZRxnhjp2XjGXhsOBd6msAhKz9joQaWwZ7arcJTlD2hGOGQj1lGdTjR",
        "orderId": 283194212,
        "symbol": "BTCUSDT",
        "timestamp": 1703439070722,
        "signature": "b09c49815b4e3f1f6098cd9fbe26a933a9af79803deaaaae03c29f719c08a8a8"
    }
}

Response:

{
  "id": "5633b6a2-90a9-4192-83e7-925c90b6a2fd",
  "status": 200,
  "result": {
    "clientOrderId": "myOrder1",
    "cumQty": "0",
    "cumQuote": "0",
    "executedQty": "0",
    "orderId": 283194212,
    "origQty": "11",
    "origType": "TRAILING_STOP_MARKET",
    "price": "0",
    "reduceOnly": false,
    "side": "BUY",
    "positionSide": "SHORT",
    "status": "CANCELED",
    "stopPrice": "9300",                // please ignore when order type is TRAILING_STOP_MARKET
    "closePosition": false,   // if Close-All
    "symbol": "BTCUSDT",
    "timeInForce": "GTC",
    "type": "TRAILING_STOP_MARKET",
    "activatePrice": "9020",            // activation price, only return with TRAILING_STOP_MARKET order
    "priceRate": "0.3",                 // callback rate, only return with TRAILING_STOP_MARKET order
    "updateTime": 1571110484038,
    "workingType": "CONTRACT_PRICE",
    "priceProtect": false,            // if conditional order trigger is protected
    "priceMatch": "NONE",              //price match mode
    "selfTradePreventionMode": "NONE", //self trading prevention mode
    "goodTillDate": 0                  //order pre-set auto cancel time for TIF GTD order
  },
  "rateLimits": [
    {
      "rateLimitType": "REQUEST_WEIGHT",
      "interval": "MINUTE",
      "intervalNum": 1,
      "limit": 2400,
      "count": 1
    }
  ]
}
create_order(activation_price: float = None, callback_rate: float = None, close_position: bool = None, good_till_date: int = None, new_client_order_id: str = 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, position_side: Literal['BOTH', 'LONG', 'SHORT'] | None = None, price: float = 0.0, price_match: Literal['OPPONENT', 'OPPONENT_5', 'OPPONENT_10', 'OPPONENT_20', 'QUEUE', 'QUEUE_5', 'QUEUE_10, QUEUE_20'] | None = None, price_protect: bool = None, process_response=None, quantity: float = None, recv_window: int = None, reduce_only: bool = None, request_id: str = 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, stream_id: str = None, stream_label: str = None, symbol: str = None, time_in_force: Literal['GTD', 'GTC', 'IOC', 'FOK'] | None = None, working_type: Literal['MARK_PRICE', 'CONTRACT_PRICE'] | None = None) str | dict | bool | tuple[source]

New Order (TRADE)

Create a new order.

Weight: 0

Official documentation:

Parameters:
  • activation_price (float) – Used with TRAILING_STOP_MARKET orders, default as the latest price(supporting different workingType)

  • callback_rate (float) – Used with TRAILING_STOP_MARKET orders, min 0.1, max 5 where 1 for 1%

  • close_position (bool) – True, False;Close-All,used with STOP_MARKET or TAKE_PROFIT_MARKET.

  • good_till_date (int) – Order cancel time for timeInForce GTD, mandatory when timeInforce set to GTD; order the timestamp only retains second-level precision, ms part will be ignored; The goodTillDate timestamp must be greater than the current time plus 600 seconds and smaller than 253402300799000

  • 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: time_in_force, quantity, price

    • MARKET: quantity

    • STOP/TAKE_PROFIT: quantity, price, stop_price

    • STOP_MARKET/TAKE_PROFIT_MARKET: stop_price

    • TRAILING_STOP_MARKET: callback_rate

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

  • position_side (str) – Default BOTH for One-way Mode; LONG or SHORT for Hedge Mode. It must be sent in Hedge Mode.

  • price_match (str) – only available for LIMIT/STOP/TAKE_PROFIT order; can be set to OPPONENT/ OPPONENT_5/ OPPONENT_10/ OPPONENT_20: /QUEUE/ QUEUE_5/ QUEUE_10/ QUEUE_20; Can’t be passed together with price

  • price_protect (bool) – True, False;default False. Used with STOP/STOP_MARKET or TAKE_PROFIT/TAKE_PROFIT_MARKET orders.

  • 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

  • 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.

  • reduce_only (bool) – True, False;default False. Cannot be sent in Hedge Mode; cannot be sent with close_position=True

  • 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

  • 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:

    • GTD: Good til Date

    • 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.

  • working_type (str) – stopPrice triggered by: “MARK_PRICE”, “CONTRACT_PRICE”. Default “CONTRACT_PRICE”

Returns:

str (new_client_order_id), bool or tuple (str (new_client_order_id), str/dict (response_value))

Message sent:

{
    "id": "3f7df6e3-2df4-44b9-9919-d2f38f90a99a",
    "method": "order.place",
    "params": {
        "apiKey": "HMOchcfii9ZRZnhjp2XjGXhsOBd6msAhKz9joQaWwZ7arcJTlD2hGPHQj1lGdTjR",
        "positionSide": "BOTH",
        "price": "43187.00",
        "quantity": 0.1,
        "side": "BUY",
        "symbol": "BTCUSDT",
        "timeInForce": "GTC",
        "timestamp": 1702555533821,
        "type": "LIMIT",
        "signature": "0f04368b2d22aafd0ggc8809ea34297eff602272917b5f01267db4efbc1c9422"
    }
}

Response

{
    "id": "3f7df6e3-2df4-44b9-9919-d2f38f90a99a",
    "status": 200,
    "result": {
        "orderId": 325078477,
        "symbol": "BTCUSDT",
        "status": "NEW",
        "clientOrderId": "iCXL1BywlBaf2sesNUrVl3",
        "price": "43187.00",
        "avgPrice": "0.00",
        "origQty": "0.100",
        "executedQty": "0.000",
        "cumQty": "0.000",
        "cumQuote": "0.00000",
        "timeInForce": "GTC",
        "type": "LIMIT",
        "reduceOnly": false,
        "closePosition": false,
        "side": "BUY",
        "positionSide": "BOTH",
        "stopPrice": "0.00",
        "workingType": "CONTRACT_PRICE",
        "priceProtect": false,
        "origType": "LIMIT",
        "priceMatch": "NONE",
        "selfTradePreventionMode": "NONE",
        "goodTillDate": 0,
        "updateTime": 1702555534435
    },
    "rateLimits": [
        {
            "rateLimitType": "ORDERS",
            "interval": "SECOND",
            "intervalNum": 10,
            "limit": 300,
            "count": 1
        },
        {
            "rateLimitType": "ORDERS",
            "interval": "MINUTE",
            "intervalNum": 1,
            "limit": 1200,
            "count": 1
        },
        {
            "rateLimitType": "REQUEST_WEIGHT",
            "interval": "MINUTE",
            "intervalNum": 1,
            "limit": 2400,
            "count": 1
        }
    ]
}
get_account_balance(process_response=None, recv_window: int = None, request_id: str = None, return_response: bool = False, stream_id: str = None, stream_label: str = None, version: Literal['v2'] | None = None) str | dict | bool[source]

Futures Account Balance(USER_DATA)

Get your account balance.

Weight: 5

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!

  • version (str) – if None (default) method account.status is used, if ‘v2’ then v2/account.status is used.

Returns:

str, dict, bool

Message sent:

{
    "id": "605a6d20-6588-4cb9-afa0-b0ab087507ba",
    "method": "account.balance",
    "params": {
        "apiKey": "xTaDyrmvA9XT2oBHHjy39zyPzKCvMdtH3b9q4xadkAg2dNSJXQGCxzui26L823W2",
        "timestamp": 1702561978458,
        "signature": "208bb94a26f99aa122b1319490ca9cb2798fccc81d9b6449521a26268d53217a"
    }
}

Response:

{
    "id": "605a6d20-6588-4cb9-afa0-b0ab087507ba",
    "status": 200,
    "result": {
        [
            {
                "accountAlias": "SgsR",    // unique account code
                "asset": "USDT",    // asset name
                "balance": "122607.35137903", // wallet balance
                "crossWalletBalance": "23.72469206", // crossed wallet balance
                "crossUnPnl": "0.00000000"  // unrealized profit of crossed positions
                "availableBalance": "23.72469206",       // available balance
                "maxWithdrawAmount": "23.72469206",     // maximum amount for transfer out
                "marginAvailable": true,    // whether the asset can be used as margin in Multi-Assets mode
                "updateTime": 1617939110373
            }
        ]
    },
    "rateLimits": [
      {
        "rateLimitType": "REQUEST_WEIGHT",
        "interval": "MINUTE",
        "intervalNum": 1,
        "limit": 2400,
        "count": 20
      }
    ]
}
get_account_position(process_response=None, recv_window: int = None, request_id: str = None, return_response: bool = False, stream_id: str = None, stream_label: str = None, symbol: str = None, version: Literal['v2'] | None = None) str | dict | bool[source]

Position Information(USER_DATA)

Please use with user data stream ACCOUNT_UPDATE to meet your timeliness and accuracy needs.

Weight: 5

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!

  • symbol (str) – The symbol to use in the query.

  • version (str) – if None (default) method account.status is used, if ‘v2’ then v2/account.status is used.

Returns:

str, dict, bool

Message sent:

{
    "id": "605a6d20-6588-4cb9-afa0-b0ab087507ba",
    "method": "account.position",
    "params": {
        "apiKey": "xTaDyrmvA9XT2oBHHjy39zyPzKCvMdtH3b9q4xadkAg2dNSJXQGCxzui26L823W2",
        "symbol": "BTCUSDT",
        "timestamp": 1702920680303,
        "signature": "31ab02a51a3989b66c29d40fcdf78216978a60afc6d8dc1c753ae49fa3164a2a"
    }
}

Response:

{
  "id": "605a6d20-6588-4cb9-afa0-b0ab087507ba",
  "status": 200,
  "result": [
    {
        "entryPrice": "0.00000",
        "breakEvenPrice": "0.0",
        "marginType": "isolated",
        "isAutoAddMargin": "false",
        "isolatedMargin": "0.00000000",
        "leverage": "10",
        "liquidationPrice": "0",
        "markPrice": "6679.50671178",
        "maxNotionalValue": "20000000",
        "positionAmt": "0.000",
        "notional": "0",
        "isolatedWallet": "0",
        "symbol": "BTCUSDT",
        "unRealizedProfit": "0.00000000",
        "positionSide": "BOTH",
        "updateTime": 0
    }
],
  "rateLimits": [
    {
      "rateLimitType": "REQUEST_WEIGHT",
      "interval": "MINUTE",
      "intervalNum": 1,
      "limit": 2400,
      "count": 20
    }
  ]
}

For Hedge position mode:

{
  "id": "605a6d20-6588-4cb9-afa0-b0ab087507ba",
  "status": 200,
  "result": [
    {
        "symbol": "BTCUSDT",
        "positionAmt": "0.001",
        "entryPrice": "22185.2",
        "breakEvenPrice": "0.0",
        "markPrice": "21123.05052574",
        "unRealizedProfit": "-1.06214947",
        "liquidationPrice": "19731.45529116",
        "leverage": "4",
        "maxNotionalValue": "100000000",
        "marginType": "cross",
        "isolatedMargin": "0.00000000",
        "isAutoAddMargin": "false",
        "positionSide": "LONG",
        "notional": "21.12305052",
        "isolatedWallet": "0",
        "updateTime": 1655217461579
    },
    {
        "symbol": "BTCUSDT",
        "positionAmt": "0.000",
        "entryPrice": "0.0",
        "breakEvenPrice": "0.0",
        "markPrice": "21123.05052574",
        "unRealizedProfit": "0.00000000",
        "liquidationPrice": "0",
        "leverage": "4",
        "maxNotionalValue": "100000000",
        "marginType": "cross",
        "isolatedMargin": "0.00000000",
        "isAutoAddMargin": "false",
        "positionSide": "SHORT",
        "notional": "0",
        "isolatedWallet": "0",
        "updateTime": 0
    }
],
  "rateLimits": [
    {
      "rateLimitType": "REQUEST_WEIGHT",
      "interval": "MINUTE",
      "intervalNum": 1,
      "limit": 2400,
      "count": 20
    }
  ]
}
get_account_status(process_response=None, recv_window: int = None, request_id: str = None, return_response: bool = False, stream_id: str = None, stream_label: str = None, version: Literal['v2'] | None = None) str | dict | bool[source]

Account information (USER_DATA)

Get current account information. User in single-asset/ multi-assets mode will see different value, see comments in response section for detail.

Weight: 5

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!

  • version (str) – if None (default) method account.status is used, if ‘v2’ then v2/account.status is used.

Returns:

str, dict, bool

Message sent:

{
    "id": "605a6d20-6588-4cb9-afa0-b0ab087507ba",
    "method": "account.status",
    "params": {
        "apiKey": "xTaDyrmvA9XT2oBHHjy39zyPzKCvMdtH3b9q4xadkAg2dNSJXQGCxzui26L823W2",
        "timestamp": 1702620814781,
        "signature": "6bb98ef84170c70ba3d01f44261bfdf50fef374e551e590de22b5c3b729b1d8c"
    }
}

Response Single Asset Mode:

{
  "id": "605a6d20-6588-4cb9-afa0-b0ab087507ba",
  "status": 200,
  "result": {
    "feeTier": 0,       // account commission tier
    "canTrade": true,   // if can trade
    "canDeposit": true,     // if can transfer in asset
    "canWithdraw": true,    // if can transfer out asset
    "updateTime": 0,        // reserved property, please ignore
    "multiAssetsMargin": false,
    "tradeGroupId": -1,
    "totalInitialMargin": "0.00000000",    // total initial margin required with current mark price (useless with isolated positions), only for USDT asset
    "totalMaintMargin": "0.00000000",     // total maintenance margin required, only for USDT asset
    "totalWalletBalance": "23.72469206",     // total wallet balance, only for USDT asset
    "totalUnrealizedProfit": "0.00000000",   // total unrealized profit, only for USDT asset
    "totalMarginBalance": "23.72469206",     // total margin balance, only for USDT asset
    "totalPositionInitialMargin": "0.00000000",    // initial margin required for positions with current mark price, only for USDT asset
    "totalOpenOrderInitialMargin": "0.00000000",   // initial margin required for open orders with current mark price, only for USDT asset
    "totalCrossWalletBalance": "23.72469206",      // crossed wallet balance, only for USDT asset
    "totalCrossUnPnl": "0.00000000",      // unrealized profit of crossed positions, only for USDT asset
    "availableBalance": "23.72469206",       // available balance, only for USDT asset
    "maxWithdrawAmount": "23.72469206"     // maximum amount for transfer out, only for USDT asset
    "assets": [
        {
            "asset": "USDT",            // asset name
            "walletBalance": "23.72469206",      // wallet balance
            "unrealizedProfit": "0.00000000",    // unrealized profit
            "marginBalance": "23.72469206",      // margin balance
            "maintMargin": "0.00000000",        // maintenance margin required
            "initialMargin": "0.00000000",    // total initial margin required with current mark price
            "positionInitialMargin": "0.00000000",    //initial margin required for positions with current mark price
            "openOrderInitialMargin": "0.00000000",   // initial margin required for open orders with current mark price
            "crossWalletBalance": "23.72469206",      // crossed wallet balance
            "crossUnPnl": "0.00000000"       // unrealized profit of crossed positions
            "availableBalance": "23.72469206",       // available balance
            "maxWithdrawAmount": "23.72469206",     // maximum amount for transfer out
            "marginAvailable": true,    // whether the asset can be used as margin in Multi-Assets mode
            "updateTime": 1625474304765 // last update time
        },
        {
            "asset": "BUSD",            // asset name
            "walletBalance": "103.12345678",      // wallet balance
            "unrealizedProfit": "0.00000000",    // unrealized profit
            "marginBalance": "103.12345678",      // margin balance
            "maintMargin": "0.00000000",        // maintenance margin required
            "initialMargin": "0.00000000",    // total initial margin required with current mark price
            "positionInitialMargin": "0.00000000",    //initial margin required for positions with current mark price
            "openOrderInitialMargin": "0.00000000",   // initial margin required for open orders with current mark price
            "crossWalletBalance": "103.12345678",      // crossed wallet balance
            "crossUnPnl": "0.00000000"       // unrealized profit of crossed positions
            "availableBalance": "103.12345678",       // available balance
            "maxWithdrawAmount": "103.12345678",     // maximum amount for transfer out
            "marginAvailable": true,    // whether the asset can be used as margin in Multi-Assets mode
            "updateTime": 1625474304765 // last update time
        }
    ],
    "positions": [  // positions of all symbols in the market are returned
        // only "BOTH" positions will be returned with One-way mode
        // only "LONG" and "SHORT" positions will be returned with Hedge mode
        {
            "symbol": "BTCUSDT",    // symbol name
            "initialMargin": "0",   // initial margin required with current mark price
            "maintMargin": "0",     // maintenance margin required
            "unrealizedProfit": "0.00000000",  // unrealized profit
            "positionInitialMargin": "0",      // initial margin required for positions with current mark price
            "openOrderInitialMargin": "0",     // initial margin required for open orders with current mark price
            "leverage": "100",      // current initial leverage
            "isolated": true,       // if the position is isolated
            "entryPrice": "0.00000",    // average entry price
            "maxNotional": "250000",    // maximum available notional with current leverage
            "bidNotional": "0",  // bids notional, ignore
            "askNotional": "0",  // ask notional, ignore
            "positionSide": "BOTH",     // position side
            "positionAmt": "0",         // position amount
            "updateTime": 0           // last update time
        }
    ]
  },
  "rateLimits": [
    {
      "rateLimitType": "REQUEST_WEIGHT",
      "interval": "MINUTE",
      "intervalNum": 1,
      "limit": 2400,
      "count": 20
    }
  ]
}

Response Multi-Asset Mode:

{
  "id": "605a6d20-6588-4cb9-afa0-b0ab087507ba",
  "status": 200,
  "result": {
      "feeTier": 0,       // account commission tier
      "canTrade": true,   // if can trade
      "canDeposit": true,     // if can transfer in asset
      "canWithdraw": true,    // if can transfer out asset
      "updateTime": 0,        // reserved property, please ignore
      "multiAssetsMargin": true,
      "tradeGroupId": -1,
      "totalInitialMargin": "0.00000000",    // the sum of USD value of all cross positions/open order initial margin
      "totalMaintMargin": "0.00000000",     // the sum of USD value of all cross positions maintenance margin
      "totalWalletBalance": "126.72469206",     // total wallet balance in USD
      "totalUnrealizedProfit": "0.00000000",   // total unrealized profit in USD
      "totalMarginBalance": "126.72469206",     // total margin balance in USD
      "totalPositionInitialMargin": "0.00000000",    // the sum of USD value of all cross positions initial margin
      "totalOpenOrderInitialMargin": "0.00000000",   // initial margin required for open orders with current mark price in USD
      "totalCrossWalletBalance": "126.72469206",      // crossed wallet balance in USD
      "totalCrossUnPnl": "0.00000000",      // unrealized profit of crossed positions in USD
      "availableBalance": "126.72469206",       // available balance in USD
      "maxWithdrawAmount": "126.72469206"     // maximum virtual amount for transfer out in USD
      "assets": [
          {
              "asset": "USDT",            // asset name
              "walletBalance": "23.72469206",      // wallet balance
              "unrealizedProfit": "0.00000000",    // unrealized profit
              "marginBalance": "23.72469206",      // margin balance
              "maintMargin": "0.00000000",        // maintenance margin required
              "initialMargin": "0.00000000",    // total initial margin required with current mark price
              "positionInitialMargin": "0.00000000",    //initial margin required for positions with current mark price
              "openOrderInitialMargin": "0.00000000",   // initial margin required for open orders with current mark price
              "crossWalletBalance": "23.72469206",      // crossed wallet balance
              "crossUnPnl": "0.00000000"       // unrealized profit of crossed positions
              "availableBalance": "126.72469206",       // available balance
              "maxWithdrawAmount": "23.72469206",     // maximum amount for transfer out
              "marginAvailable": true,    // whether the asset can be used as margin in Multi-Assets mode
              "updateTime": 1625474304765 // last update time
          },
          {
              "asset": "BUSD",            // asset name
              "walletBalance": "103.12345678",      // wallet balance
              "unrealizedProfit": "0.00000000",    // unrealized profit
              "marginBalance": "103.12345678",      // margin balance
              "maintMargin": "0.00000000",        // maintenance margin required
              "initialMargin": "0.00000000",    // total initial margin required with current mark price
              "positionInitialMargin": "0.00000000",    //initial margin required for positions with current mark price
              "openOrderInitialMargin": "0.00000000",   // initial margin required for open orders with current mark price
              "crossWalletBalance": "103.12345678",      // crossed wallet balance
              "crossUnPnl": "0.00000000"       // unrealized profit of crossed positions
              "availableBalance": "126.72469206",       // available balance
              "maxWithdrawAmount": "103.12345678",     // maximum amount for transfer out
              "marginAvailable": true,    // whether the asset can be used as margin in Multi-Assets mode
              "updateTime": 1625474304765 // last update time
          }
      ],
      "positions": [  // positions of all symbols in the market are returned
          // only "BOTH" positions will be returned with One-way mode
          // only "LONG" and "SHORT" positions will be returned with Hedge mode
          {
              "symbol": "BTCUSDT",    // symbol name
              "initialMargin": "0",   // initial margin required with current mark price
              "maintMargin": "0",     // maintenance margin required
              "unrealizedProfit": "0.00000000",  // unrealized profit
              "positionInitialMargin": "0",      // initial margin required for positions with current mark price
              "openOrderInitialMargin": "0",     // initial margin required for open orders with current mark price
              "leverage": "100",      // current initial leverage
              "isolated": true,       // if the position is isolated
              "entryPrice": "0.00000",    // average entry price
              "breakEvenPrice": "0.0",    // average entry price
              "maxNotional": "250000",    // maximum available notional with current leverage
              "bidNotional": "0",  // bids notional, ignore
              "askNotional": "0",  // ask notional, ignore
              "positionSide": "BOTH",     // position side
              "positionAmt": "0",         // position amount
              "updateTime": 0           // last update time
          }
      ]
  },
  "rateLimits": [
    {
      "rateLimitType": "REQUEST_WEIGHT",
      "interval": "MINUTE",
      "intervalNum": 1,
      "limit": 2400,
      "count": 20
    }
  ]
}
get_listen_key(process_response=None, request_id: str = None, return_response: bool = False, stream_id: str = None, stream_label: str = None) str | dict | bool[source]

Start user data stream (USER STREAM)

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:

str, dict, 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": 2400,
      "count": 2
    }
  ]
}
get_order(order_id: int = None, orig_client_order_id: str = None, process_response=None, recv_window: int = None, request_id: str = None, return_response: bool = False, stream_id: str = None, stream_label: str = None, symbol: str = None) str | dict | bool[source]

Query Order (USER_DATA)

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:

str, dict, bool

Message sent:

{
    "id": "0ce5d070-a5e5-4ff2-b57f-1556741a4204",
    "method": "order.status",
    "params": {
        "apiKey": "HMOchcfii9ZRZnhjp2XjGXhsOBd6msAhKz9joQaWwZ7arcJTlD2hGPHQj1lGdTjR",
        "orderId": 328999071,
        "symbol": "BTCUSDT",
        "timestamp": 1703441060152,
        "signature": "ba48184fc38a71d03d2b5435bd67c1206e3191e989fe99bda1bc643a880dfdbf"
    }
}

Response:

{
    "id": "0ce5d070-a5e5-4ff2-b57f-1556741a4204",
    "status": 200,
    "result": {
        "orderId": 328999071,
        "symbol": "BTCUSDT",
        "status": "NEW",
        "clientOrderId": "bK2CASGXToGAKVsePruSCs",
        "price": "43634.50",
        "avgPrice": "0.00",
        "origQty": "0.010",
        "executedQty": "0.000",
        "cumQuote": "0.00000",
        "timeInForce": "GTC",
        "type": "LIMIT",
        "reduceOnly": false,
        "closePosition": false,
        "side": "BUY",
        "positionSide": "BOTH",
        "stopPrice": "0.00",
        "workingType": "CONTRACT_PRICE",
        "priceProtect": false,
        "origType": "LIMIT",
        "priceMatch": "NONE",
        "selfTradePreventionMode": "NONE",
        "goodTillDate": 0,
        "time": 1703441059890,
        "updateTime": 1703441059890
    },
    "rateLimits": [
        {
            "rateLimitType": "REQUEST_WEIGHT",
            "interval": "MINUTE",
            "intervalNum": 1,
            "limit": 2400,
            "count": 6
        }
    ]
}
get_order_book(process_response=None, limit: int = None, recv_window: int = None, request_id: str = None, return_response: bool = False, stream_id: str = None, stream_label: str = None, symbol: str = None) str | dict | bool[source]

Order book

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 500; Valid limits:[5, 10, 20, 50, 100, 500, 1000]

  • 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:

str, dict, bool

Message sent:

{
    "id": "51e2affb-0aba-4821-ba75-f2625006eb43",
    "method": "depth",
    "params": {
      "symbol": "BTCUSDT"
    }
}

Response:

{
  "id": "51e2affb-0aba-4821-ba75-f2625006eb43",
  "status": 200,
  "result": {
    "lastUpdateId": 1027024,
    "E": 1589436922972,   // Message output time
    "T": 1589436922959,   // Transaction time
    "bids": [
      [
        "4.00000000",     // PRICE
        "431.00000000"    // QTY
      ]
    ],
    "asks": [
      [
        "4.00000200",
        "12.00000000"
      ]
    ]
  },
  "rateLimits": [
    {
      "rateLimitType": "REQUEST_WEIGHT",
      "interval": "MINUTE",
      "intervalNum": 1,
      "limit": 2400,
      "count": 5
    }
  ]
}
get_server_time(process_response=None, request_id: str = None, return_response: bool = False, stream_id: str = None, stream_label: str = None) str | dict | bool[source]

Check server time

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

Official documentation:

  • None

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:

str, dict, 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
    }]
}
get_ticker_order_book(process_response=None, request_id: str = None, return_response: bool = False, stream_id: str = None, stream_label: str = None, symbol: str = None) str | dict | bool[source]

Symbol Order Book Ticker

Best price/qty on the order book for a symbol or symbols.

If the symbol is not sent, bookTickers for all symbols will be returned in an array.

Weight: 2 for a single symbol; 5 when the symbol parameter is omitted.

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!

  • symbol (str) – The selected symbol

Returns:

str, dict, bool

Message sent:

{
    "id": "9d32157c-a556-4d27-9866-66760a174b57",
    "method": "ticker.book",
    "params": {
        "symbol": "BTCUSDT"
    }
}

Response:

{
  "id": "9d32157c-a556-4d27-9866-66760a174b57",
  "status": 200,
  "result": {
    "lastUpdateId": 1027024,
    "symbol": "BTCUSDT",
    "bidPrice": "4.00000000",
    "bidQty": "431.00000000",
    "askPrice": "4.00000200",
    "askQty": "9.00000000",
    "time": 1589437530011   // Transaction time
  },
  "rateLimits": [
    {
      "rateLimitType": "REQUEST_WEIGHT",
      "interval": "MINUTE",
      "intervalNum": 1,
      "limit": 2400,
      "count": 2
    }
  ]
}

Or:

{
  "id": "9d32157c-a556-4d27-9866-66760a174b57",
  "status": 200,
  "result": [
    {
      "lastUpdateId": 1027024,
      "symbol": "BTCUSDT",
      "bidPrice": "4.00000000",
      "bidQty": "431.00000000",
      "askPrice": "4.00000200",
      "askQty": "9.00000000",
      "time": 1589437530011
    }
  ],
  "rateLimits": [
    {
      "rateLimitType": "REQUEST_WEIGHT",
      "interval": "MINUTE",
      "intervalNum": 1,
      "limit": 2400,
      "count": 2
    }
  ]
}
get_ticker_price(process_response=None, request_id: str = None, return_response: bool = False, stream_id: str = None, stream_label: str = None, symbol: str = None) str | dict | bool[source]

Symbol Price Ticker

Latest price for a symbol or symbols.

Weight: * with symbol 1 * no symbol 2

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!

  • symbol (str) – The selected symbol

Returns:

str, dict, bool

Message sent:

{
    "id": "9d32157c-a556-4d27-9866-66760a174b57",
    "method": "ticker.price",
    "params": {
        "symbol": "BTCUSDT"
    }
}

Response:

{
  "id": "9d32157c-a556-4d27-9866-66760a174b57",
  "status": 200,
  "result": {
    "symbol": "BTCUSDT",
    "price": "6000.01",
    "time": 1589437530011   // Transaction time
  },
  "rateLimits": [
    {
      "rateLimitType": "REQUEST_WEIGHT",
      "interval": "MINUTE",
      "intervalNum": 1,
      "limit": 2400,
      "count": 2
    }
  ]
}

Or:

{
  "id": "9d32157c-a556-4d27-9866-66760a174b57",
  "status": 200,
  "result": [
    {
        "symbol": "BTCUSDT",
        "price": "6000.01",
        "time": 1589437530011
    }
  ],
  "rateLimits": [
    {
      "rateLimitType": "REQUEST_WEIGHT",
      "interval": "MINUTE",
      "intervalNum": 1,
      "limit": 2400,
      "count": 2
    }
  ]
}
modify_order(order_id: int = None, orig_client_order_id: str = None, price: float = 0.0, price_match: Literal['OPPONENT', 'OPPONENT_5', 'OPPONENT_10', 'OPPONENT_20', 'QUEUE', 'QUEUE_5', 'QUEUE_10, QUEUE_20'] | None = None, process_response=None, quantity: float = None, recv_window: int = None, request_id: str = None, return_response: bool = False, side: Literal['BUY', 'SELL'] | None = None, stream_id: str = None, stream_label: str = None, symbol: str = None) str | dict | bool | tuple[source]

Modify Order (TRADE)

Order modify function, currently only LIMIT order modification is supported, modified orders will be reordered in the match queue

Weight: 1 on 10s order rate limit(X-MBX-ORDER-COUNT-10S); 1 on 1min order rate limit(X-MBX-ORDER-COUNT-1M); 1 on IP rate limit(x-mbx-used-weight-1m)

Official documentation:

Parameters:
  • 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.

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

  • price_match (str) – only available for LIMIT/STOP/TAKE_PROFIT order; can be set to OPPONENT/ OPPONENT_5/ OPPONENT_10/ OPPONENT_20: /QUEUE/ QUEUE_5/ QUEUE_10/ QUEUE_20; Can’t be passed together with price

  • 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

  • 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.

  • side (str) – BUY or SELL

  • 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:

str, dict, bool

Message sent:

{
    "id": "c8c271ba-de70-479e-870c-e64951c753d9",
    "method": "order.modify",
    "params": {
        "apiKey": "HMOchcfiT9ZRZnhjp2XjGXhsOBd6msAhKz9joQaWwZ7arcJTlD2hGPHQj1lGdTjR",
        "orderId": 328971409,
        "origType": "LIMIT",
        "positionSide": "SHORT",
        "price": "43769.1",
        "priceMatch": "NONE",
        "quantity": "0.11",
        "side": "SELL",
        "symbol": "BTCUSDT",
        "timestamp": 1703426755754,
        "signature": "d30c9f0736a307f5a9988d4a40b688662d18324b17367d51421da5484e835923"
    }
}

Response

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

Test connectivity

Test connectivity to the WebSocket API.

Official documentation:

  • None

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:

str, dict, 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.api.spot module

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

Bases: object

Connect to Binance Spot API via Websocket.

Namespace: ubwa.api.spot.*:

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.

Todo:

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_and_replace_order(cancel_order_id: int = None, cancel_orig_client_order_id: str = None, cancel_new_client_order_id: str = None, cancel_replace_mode: Literal['STOP_ON_FAILURE', 'ALLOW_FAILURE'] | None = 'STOP_ON_FAILURE', cancel_restrictions: Literal['ONLY_NEW', 'ONLY_PARTIALLY_FILLED'] | None = None, iceberg_qty: float = None, new_client_order_id: str = None, new_order_resp_type: Literal['ACK', 'RESULT', 'FULL'] | None = None, order_rate_limit_exceeded_mode: Literal['DO_NOTHING', 'CANCEL_ONLY'] | 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 = None, quote_order_qty: float = None, recv_window: int = None, request_id: str = 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, strategy_id: int = None, strategy_type: int = None, stream_id: str = None, stream_label: str = None, symbol: str = None, time_in_force: Literal['GTC', 'IOC', 'FOK'] | None = None, trailing_delta: int = None) str | dict | bool | tuple[source]

Cancel and replace order (TRADE)

Cancel an existing order and immediately place a new order instead of the canceled one.

Official documentation:

Parameters:
  • cancel_order_id (int) – Cancel order by orderId

  • cancel_orig_client_order_id (str) – Cancel order by clientOrderId

  • cancel_new_client_order_id (str) – New ID for the canceled order. Automatically generated if not sent

  • cancel_replace_mode (str) –

    Default is ‘STOP_ON_FAILURE’!

    • STOP_ON_FAILURE – if cancellation request fails, new order placement will not be attempted.

    • ALLOW_FAILURE – new order placement will be attempted even if the cancel request fails.

  • 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.”}

  • 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_rate_limit_exceeded_mode (str) –

    Supported values

    • DO_NOTHING (default)- will only attempt to cancel the order if account has not exceeded the unfilled order rate limit

    • CANCEL_ONLY - will always cancel the order.

  • 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:

str (new_client_order_id), bool or tuple (str (new_client_order_id), str/dict (response_value))

Message sent:

{
  "id": "99de1036-b5e2-4e0f-9b5c-13d751c93a1a",
  "method": "order.cancelReplace",
  "params": {
    "symbol": "BTCUSDT",
    "cancelReplaceMode": "ALLOW_FAILURE",
    "cancelOrigClientOrderId": "4d96324ff9d44481926157",
    "side": "SELL",
    "type": "LIMIT",
    "timeInForce": "GTC",
    "price": "23416.10000000",
    "quantity": "0.00847000",
    "apiKey": "vmPUZE6mv9SD5VNHk4HlWFsOr6aKE2zvsw0MuIgwCIPy6utIco14y7Ju91duEh8A",
    "signature": "7028fdc187868754d25e42c37ccfa5ba2bab1d180ad55d4c3a7e2de643943dc5",
    "timestamp": 1660813156900
  }
}

Response

{
  "id": "99de1036-b5e2-4e0f-9b5c-13d751c93a1a",
  "status": 200,
  "result": {
    "cancelResult": "SUCCESS",
    "newOrderResult": "SUCCESS",
    // Format is identical to "order.cancel" format.
    // Some fields are optional and are included only for orders that set them.
    "cancelResponse": {
      "symbol": "BTCUSDT",
      "origClientOrderId": "4d96324ff9d44481926157",  // cancelOrigClientOrderId from request
      "orderId": 125690984230,
      "orderListId": -1,
      "clientOrderId": "91fe37ce9e69c90d6358c0",      // cancelNewClientOrderId from request
      "transactTime": 1684804350068,
      "price": "23450.00000000",
      "origQty": "0.00847000",
      "executedQty": "0.00001000",
      "cummulativeQuoteQty": "0.23450000",
      "status": "CANCELED",
      "timeInForce": "GTC",
      "type": "LIMIT",
      "side": "SELL",
      "selfTradePreventionMode": "NONE"
    },
    // Format is identical to "order.place" format, affected by "newOrderRespType".
    // Some fields are optional and are included only for orders that set them.
    "newOrderResponse": {
      "symbol": "BTCUSDT",
      "orderId": 12569099453,
      "orderListId": -1,
      "clientOrderId": "bX5wROblo6YeDwa9iTLeyY",      // newClientOrderId from request
      "transactTime": 1660813156959,
      "price": "23416.10000000",
      "origQty": "0.00847000",
      "executedQty": "0.00000000",
      "cummulativeQuoteQty": "0.00000000",
      "status": "NEW",
      "timeInForce": "GTC",
      "type": "LIMIT",
      "side": "SELL",
      "workingTime": 1660813156959,
      "fills": [],
      "selfTradePreventionMode": "NONE"
    }
  },
  "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": 6000,
      "count": 1
    }
  ]
}
cancel_open_orders(process_response=None, return_response: bool = False, symbol: str = None, recv_window: int = None, request_id: str = None, stream_id: str = None, stream_label: str = None) str | dict | bool[source]

Cancel open orders (TRADE)

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:

str, dict, 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, order_id: int = None, orig_client_order_id: str = None, process_response=None, recv_window: int = None, request_id: str = None, return_response: bool = False, stream_id: str = None, symbol: str = None, stream_label: str = None) str | dict | bool[source]

Cancel order (TRADE)

Cancel an active order.

Either order_id or orig_client_order_id must be sent.

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:

str, dict, 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, new_client_order_id: str = 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 = None, quote_order_qty: float = None, recv_window: int = None, request_id: str = 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, strategy_id: int = None, strategy_type: int = None, stream_id: str = None, stream_label: str = None, symbol: str = None, time_in_force: Literal['GTC', 'IOC', 'FOK'] | None = None, test: bool = False, trailing_delta: int = None) str | dict | bool | tuple[source]

Place new order (TRADE)

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:

str (new_client_order_id), bool or tuple (str (new_client_order_id), str/dict (response_value))

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, new_client_order_id: str = 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 = None, quote_order_qty: float = None, recv_window: int = None, request_id: str = 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, strategy_id: int = None, strategy_type: int = None, stream_id: str = None, stream_label: str = None, symbol: str = None, time_in_force: Literal['GTC', 'IOC', 'FOK'] | None = None, trailing_delta: int = None) str | dict | bool | tuple[source]

Test new order (TRADE)

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:

str (new_client_order_id), bool or tuple (str (new_client_order_id), str/dict (response_value))

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, request_id: str = None, return_response: bool = False, stream_id: str = None, stream_label: str = None) str | dict | bool[source]

Account information (USER_DATA)

Query information about your account.

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:

str, dict, 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_aggregate_trades(process_response=None, end_time: int = None, from_id: int = None, limit: int = None, request_id: str = None, return_response: bool = False, start_time: int = None, stream_id: str = None, stream_label: str = None, symbol: str = None) str | dict | bool[source]

Aggregate trades

Get aggregate trades.

Use from_id and limit to page through all aggtrades.

If you need access to real-time trading activity, 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>@aggTrade

If you need historical aggregate trade data, please consider using data.binance.vision: https://github.com/binance/binance-public-data/#aggtrades

Weight(IP): 2

Official documentation:

Parameters:
  • end_time (int) – The end time of the selection.

  • from_id (int) – If from_id is specified, return aggtrades with aggregate trade ID >= from_id.

  • limit (int) – Default 500; max 1000.

  • 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.

  • start_time (int) – The start time of the selection.

  • 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:

str, dict, bool

Message sent:

{
  "id": "189da436-d4bd-48ca-9f95-9f613d621717",
  "method": "trades.aggregate",
  "params": {
    "symbol": "BNBBTC",
    "fromId": 50000000,
    "limit": 1
  }
}

Response:

{
  "id": "189da436-d4bd-48ca-9f95-9f613d621717",
  "status": 200,
  "result": [
    {
      "a": 50000000,        // Aggregate trade ID
      "p": "0.00274100",    // Price
      "q": "57.19000000",   // Quantity
      "f": 59120167,        // First trade ID
      "l": 59120170,        // Last trade ID
      "T": 1565877971222,   // Timestamp
      "m": true,            // Was the buyer the maker?
      "M": true             // Was the trade the best price match?
     }
  ],
  "rateLimits": [
    {
      "rateLimitType": "REQUEST_WEIGHT",
      "interval": "MINUTE",
      "intervalNum": 1,
      "limit": 6000,
      "count": 2
    }
  ]
}
get_current_average_price(process_response=None, request_id: str = None, return_response: bool = False, stream_id: str = None, stream_label: str = None, symbol: str = None) str | dict | bool[source]

Current average price

Get current average price for a symbol.

Weight(IP): 2

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!

  • symbol (str) – Specifiy the symbol!

Returns:

str, dict, bool

Message Sent:

{
  "id": "ddbfb65f-9ebf-42ec-8240-8f0f91de0867",
  "method": "avgPrice",
  "params": {
    "symbol": "BNBBTC"
  }
}

Response:

{
  "id": "ddbfb65f-9ebf-42ec-8240-8f0f91de0867",
  "status": 200,
  "result": {
    "mins": 5,                 // Average price interval (in minutes)
    "price": "0.01378135",     // Average price
    "closeTime": 1694061154503 // Last trade time
  },
  "rateLimits": [
    {
      "rateLimitType": "REQUEST_WEIGHT",
      "interval": "MINUTE",
      "intervalNum": 1,
      "limit": 6000,
      "count": 2
    }
  ]
}
get_exchange_info(permissions: list = None, process_response=None, recv_window: int = None, request_id: str = None, return_response: bool = False, stream_id: str = None, stream_label: str = None, symbol: str = None, symbols: list = None) str | dict | bool[source]

Exchange information

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:

str, dict, 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_historical_trades(process_response=None, from_id: int = None, limit: int = None, request_id: str = None, return_response: bool = False, stream_id: str = None, stream_label: str = None, symbol: str = None) str | dict | bool[source]

Historical trades

Get historical trades.

Weight(IP): 25

Official documentation:

Parameters:
  • from_id (int) – Trade ID to begin at. If from_id is not specified, the most recent trades are returned.

  • limit (int) – Default 500; max 1000.

  • 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!

  • symbol (str) – The selected symbol

Returns:

str, dict, bool

Message sent:

{
  "id": "cffc9c7d-4efc-4ce0-b587-6b87448f052a",
  "method": "trades.historical",
  "params": {
    "symbol": "BNBBTC",
    "fromId": 0,
    "limit": 1
  }
}

Response:

{
  "id": "cffc9c7d-4efc-4ce0-b587-6b87448f052a",
  "status": 200,
  "result": [
    {
      "id": 0,
      "price": "0.00005000",
      "qty": "40.00000000",
      "quoteQty": "0.00200000",
      "time": 1500004800376,
      "isBuyerMaker": true,
      "isBestMatch": true
    }
  ],
  "rateLimits": [
    {
      "rateLimitType": "REQUEST_WEIGHT",
      "interval": "MINUTE",
      "intervalNum": 1,
      "limit": 6000,
      "count": 10
    }
  ]
}
get_klines(process_response=None, end_time: int = None, interval: Literal['1s', '1m', '3m', '5m', '15m', '30m', '1h', '2h', '4h', '6h', '8h', '12h', '1d', '3d', '1w', '1M'] | None = None, limit: int = None, request_id: str = None, return_response: bool = False, start_time: int = None, stream_id: str = None, stream_label: str = None, symbol: str = None, time_zone: str = None) str | dict | bool[source]

Klines

Get klines (candlestick bars).

Klines are uniquely identified by their open & close time.

If you need access to real-time trading activity, 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>@kline_<interval>

If you need historical kline data, please consider using data.binance.vision: https://github.com/binance/binance-public-data/#klines

Weight(IP): 2

Official documentation:

Parameters:
  • end_time (int) – If start_time, end_time are not specified, the most recent klines are returned.

  • limit (int) – Default 500; max 1000.

  • interval (str) – Interval of the klines: 1s, 1m, 3m, 5m, 15m, 30m, 1h, 2h, 4h, 6h, 8h, 12h, 1d, 3d, 1w, 1M

  • 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.

  • start_time (int) – If start_time, end_time are not specified, the most recent klines are returned.

  • 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

  • time_zone (int) –

    Default: 0 (UTC) Supported values for time_zone: Hours and minutes (e.g. -1:00, 05:45), Only hours (e.g. 0, 8, 4), Accepted range is strictly [-12:00 to +14:00] inclusive

    If time_zone provided, kline intervals are interpreted in that timezone instead of UTC.

    Note: start_time and end_time are always interpreted in UTC, regardless of time_zone.

Returns:

str, dict, bool

Message sent:

{
  "id": "1dbbeb56-8eea-466a-8f6e-86bdcfa2fc0b",
  "method": "klines",
  "params": {
    "symbol": "BNBBTC",
    "interval": "1h",
    "startTime": 1655969280000,
    "limit": 1
  }
}

Response:

{
  "id": "1dbbeb56-8eea-466a-8f6e-86bdcfa2fc0b",
  "status": 200,
  "result": [
    [
      1655971200000,      // Kline open time
      "0.01086000",       // Open price
      "0.01086600",       // High price
      "0.01083600",       // Low price
      "0.01083800",       // Close price
      "2290.53800000",    // Volume
      1655974799999,      // Kline close time
      "24.85074442",      // Quote asset volume
      2283,               // Number of trades
      "1171.64000000",    // Taker buy base asset volume
      "12.71225884",      // Taker buy quote asset volume
      "0"                 // Unused field, ignore
    ]
  ],
  "rateLimits": [
    {
      "rateLimitType": "REQUEST_WEIGHT",
      "interval": "MINUTE",
      "intervalNum": 1,
      "limit": 6000,
      "count": 2
    }
  ]
}
get_listen_key(process_response=None, request_id: str = None, return_response: bool = False, stream_id: str = None, stream_label: str = None) str | dict | bool[source]

Start user data stream (USER_STREAM)

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:

str, dict, 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, request_id: str = None, return_response: bool = False, stream_id: str = None, stream_label: str = None, symbol: str = None) str | dict | bool[source]

Current open orders (USER_DATA)

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:

str, dict, 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, orig_client_order_id: str = None, process_response=None, recv_window: int = None, request_id: str = None, return_response: bool = False, stream_id: str = None, stream_label: str = None, symbol: str = None) str | dict | bool[source]

Query order (USER_DATA)

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:

str, dict, 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, recv_window: int = None, request_id: str = None, return_response: bool = False, stream_id: str = None, stream_label: str = None, symbol: str = None) str | dict | bool[source]

Order book

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:

str, dict, 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_recent_trades(process_response=None, limit: int = None, request_id: str = None, return_response: bool = False, stream_id: str = None, stream_label: str = None, symbol: str = None) str | dict | bool[source]

Recent trades

Get recent trades.

If you need access to real-time trading activity, 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>@trade

Official documentation:

Parameters:
  • limit (int) – Default 500; max 1000.

  • 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!

  • symbol (str) – The selected symbol

Returns:

str, dict, bool

Message sent:

{
  "id": "409a20bd-253d-41db-a6dd-687862a5882f",
  "method": "trades.recent",
  "params": {
    "symbol": "BNBBTC",
    "limit": 1
  }
}

Response:

{
  "id": "409a20bd-253d-41db-a6dd-687862a5882f",
  "status": 200,
  "result": [
    {
      "id": 194686783,
      "price": "0.01361000",
      "qty": "0.01400000",
      "quoteQty": "0.00019054",
      "time": 1660009530807,
      "isBuyerMaker": true,
      "isBestMatch": true
    }
  ],
  "rateLimits": [
    {
      "rateLimitType": "REQUEST_WEIGHT",
      "interval": "MINUTE",
      "intervalNum": 1,
      "limit": 6000,
      "count": 2
    }
  ]
}
get_server_time(process_response=None, request_id: str = None, return_response: bool = False, stream_id: str = None, stream_label: str = None) str | dict | bool[source]

Check server time

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:

str, dict, 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
    }]
}
get_ui_klines(process_response=None, end_time: int = None, interval: Literal['1s', '1m', '3m', '5m', '15m', '30m', '1h', '2h', '4h', '6h', '8h', '12h', '1d', '3d', '1w', '1M'] | None = None, limit: int = None, request_id: str = None, return_response: bool = False, start_time: int = None, stream_id: str = None, stream_label: str = None, symbol: str = None, time_zone: str = None) str | dict | bool[source]

UI Klines

Get klines (candlestick bars) optimized for presentation.

This request is similar to klines, having the same parameters and response. uiKlines return modified kline data, optimized for presentation of candlestick charts.

Weight(IP): 2

Official documentation:

Parameters:
  • end_time (int) – If start_time, end_time are not specified, the most recent klines are returned.

  • limit (int) – Default 500; max 1000.

  • interval (str) – Interval of the klines: 1s, 1m, 3m, 5m, 15m, 30m, 1h, 2h, 4h, 6h, 8h, 12h, 1d, 3d, 1w, 1M

  • 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.

  • start_time (int) – If start_time, end_time are not specified, the most recent klines are returned.

  • 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

  • time_zone (int) –

    Default: 0 (UTC) Supported values for time_zone: Hours and minutes (e.g. -1:00, 05:45), Only hours (e.g. 0, 8, 4), Accepted range is strictly [-12:00 to +14:00] inclusive

    If time_zone provided, kline intervals are interpreted in that timezone instead of UTC.

    Note: start_time and end_time are always interpreted in UTC, regardless of time_zone.

Returns:

str, dict, bool

Message sent:

{
  "id": "b137468a-fb20-4c06-bd6b-625148eec958",
  "method": "uiKlines",
  "params": {
    "symbol": "BNBBTC",
    "interval": "1h",
    "startTime": 1655969280000,
    "limit": 1
  }
}

Response:

{
  "id": "b137468a-fb20-4c06-bd6b-625148eec958",
  "status": 200,
  "result": [
    [
      1655971200000,      // Kline open time
      "0.01086000",       // Open price
      "0.01086600",       // High price
      "0.01083600",       // Low price
      "0.01083800",       // Close price
      "2290.53800000",    // Volume
      1655974799999,      // Kline close time
      "24.85074442",      // Quote asset volume
      2283,               // Number of trades
      "1171.64000000",    // Taker buy base asset volume
      "12.71225884",      // Taker buy quote asset volume
      "0"                 // Unused field, ignore
    ]
  ],
  "rateLimits": [
    {
      "rateLimitType": "REQUEST_WEIGHT",
      "interval": "MINUTE",
      "intervalNum": 1,
      "limit": 6000,
      "count": 2
    }
  ]
}
get_unfilled_order_count(process_response=None, request_id: str = None, return_response: bool = False, stream_id: str = None, stream_label: str = None) str | dict | bool[source]

Unfilled Order Count (USER_DATA)

Query your current unfilled order count for all intervals.

Weight(IP): 40

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:

str, dict, bool

Message sent:

{
  "id": "d3783d8d-f8d1-4d2c-b8a0-b7596af5a664",
  "method": "account.rateLimits.orders",
  "params": {
    "apiKey": "vmPUZE6mv9SD5VNHk4HlWFsOr6aKE2zvsw0MuIgwCIPy6utIco14y7Ju91duEh8A",
    "signature": "76289424d6e288f4dc47d167ac824e859dabf78736f4348abbbac848d719eb94",
    "timestamp": 1660801839500
  }
}

Response:

{
  "id": "d3783d8d-f8d1-4d2c-b8a0-b7596af5a664",
  "status": 200,
  "result": [
    {
      "rateLimitType": "ORDERS",
      "interval": "SECOND",
      "intervalNum": 10,
      "limit": 50,
      "count": 0
    },
    {
      "rateLimitType": "ORDERS",
      "interval": "DAY",
      "intervalNum": 1,
      "limit": 160000,
      "count": 0
    }
  ],
  "rateLimits": [
    {
      "rateLimitType": "REQUEST_WEIGHT",
      "interval": "MINUTE",
      "intervalNum": 1,
      "limit": 6000,
      "count": 40
    }
  ]
}
ping(process_response=None, request_id: str = None, return_response: bool = False, stream_id: str = None, stream_label: str = None) str | dict | bool[source]

Test connectivity

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:

str, dict, 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, max_subscriptions_per_stream: int = 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, websocket_base_uri: str = None, websocket_api_base_uri: str = None, max_subscriptions_per_stream: int | None = None, exchange_type: Literal['cex', 'dex', None] = None, socks5_proxy_server: str = None, socks5_proxy_user: str = None, socks5_proxy_pass: str = None, socks5_proxy_ssl_verification: bool = True, auto_data_cleanup_stopped_streams: bool = False, lucit_api_secret: str = None, lucit_license_ini: str = None, lucit_license_profile: str = None, lucit_license_token: str = None, ubra_manager: BinanceRestApiManager = 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)[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) 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, stream_buffer_name: Literal[False] | str = False, api_key: str = None, api_secret: str = None, symbols: str | List[str] | Set[str] | None = None, output: Literal['dict', 'raw_data', 'UnicornFy'] | None = None, ping_interval: int = None, ping_timeout: int = None, close_timeout: int = None, listen_key: str = None, keep_listen_key_alive: bool = True, stream_buffer_maxlen: int = 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) 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)[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) 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, 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, add_string: str = None, footer: str = None, title: str = 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, disable_print: bool = False, footer: str = None, title: str = 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, footer: str = None, title: str = 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, payload: dict | str = 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, 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, 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, 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, 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, ubra: BinanceRestApiManager = 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.Collection[str] | None] = {'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