Binance API

client module

class binance.client.Client(api_key, api_secret, requests_params=None)[source]

Bases: object

AGG_BEST_MATCH = 'M'
AGG_BUYER_MAKES = 'm'
AGG_FIRST_TRADE_ID = 'f'
AGG_ID = 'a'
AGG_LAST_TRADE_ID = 'l'
AGG_PRICE = 'p'
AGG_QUANTITY = 'q'
AGG_TIME = 'T'
API_URL = 'https://api.binance.com/api'
KLINE_INTERVAL_12HOUR = '12h'
KLINE_INTERVAL_15MINUTE = '15m'
KLINE_INTERVAL_1DAY = '1d'
KLINE_INTERVAL_1HOUR = '1h'
KLINE_INTERVAL_1MINUTE = '1m'
KLINE_INTERVAL_1MONTH = '1M'
KLINE_INTERVAL_1WEEK = '1w'
KLINE_INTERVAL_2HOUR = '2h'
KLINE_INTERVAL_30MINUTE = '30m'
KLINE_INTERVAL_3DAY = '3d'
KLINE_INTERVAL_3MINUTE = '3m'
KLINE_INTERVAL_4HOUR = '4h'
KLINE_INTERVAL_5MINUTE = '5m'
KLINE_INTERVAL_6HOUR = '6h'
KLINE_INTERVAL_8HOUR = '8h'
ORDER_RESP_TYPE_ACK = 'ACK'
ORDER_RESP_TYPE_FULL = 'FULL'
ORDER_RESP_TYPE_RESULT = 'RESULT'
ORDER_STATUS_CANCELED = 'CANCELED'
ORDER_STATUS_EXPIRED = 'EXPIRED'
ORDER_STATUS_FILLED = 'FILLED'
ORDER_STATUS_NEW = 'NEW'
ORDER_STATUS_PARTIALLY_FILLED = 'PARTIALLY_FILLED'
ORDER_STATUS_PENDING_CANCEL = 'PENDING_CANCEL'
ORDER_STATUS_REJECTED = 'REJECTED'
ORDER_TYPE_LIMIT = 'LIMIT'
ORDER_TYPE_LIMIT_MAKER = 'LIMIT_MAKER'
ORDER_TYPE_MARKET = 'MARKET'
ORDER_TYPE_STOP_LOSS = 'STOP_LOSS'
ORDER_TYPE_STOP_LOSS_LIMIT = 'STOP_LOSS_LIMIT'
ORDER_TYPE_TAKE_PROFIT = 'TAKE_PROFIT'
ORDER_TYPE_TAKE_PROFIT_LIMIT = 'TAKE_PROFIT_LIMIT'
PRIVATE_API_VERSION = 'v3'
PUBLIC_API_VERSION = 'v1'
SIDE_BUY = 'BUY'
SIDE_SELL = 'SELL'
SYMBOL_TYPE_SPOT = 'SPOT'
TIME_IN_FORCE_FOK = 'FOK'
TIME_IN_FORCE_GTC = 'GTC'
TIME_IN_FORCE_IOC = 'IOC'
WEBSITE_URL = 'https://www.binance.com'
WITHDRAW_API_URL = 'https://api.binance.com/wapi'
WITHDRAW_API_VERSION = 'v3'
__init__(api_key, api_secret, requests_params=None)[source]

Binance API Client constructor

Parameters:
  • api_key (str.) – Api Key
  • api_secret (str.) – Api Secret
  • requests_params (dict.) – optional - Dictionary of requests params to use for all calls
aggregate_trade_iter(symbol, start_str=None, last_id=None)[source]

Iterate over aggregate trade data from (start_time or last_id) to the end of the history so far.

If start_time is specified, start with the first trade after start_time. Meant to initialise a local cache of trade data.

If last_id is specified, start with the trade after it. This is meant for updating a pre-existing local trade data cache.

Only allows start_str or last_id—not both. Not guaranteed to work right if you’re running more than one of these simultaneously. You will probably hit your rate limit.

See dateparser docs for valid start and end string formats http://dateparser.readthedocs.io/en/latest/

If using offset strings for dates add “UTC” to date string e.g. “now UTC”, “11 hours ago UTC”

Parameters:
  • symbol (str) – Symbol string e.g. ETHBTC
  • start_str – Start date string in UTC format or timestamp in milliseconds. The iterator will

return the first trade occurring later than this time. :type start_str: str|int :param last_id: aggregate trade ID of the last known aggregate trade. Not a regular trade ID. See https://github.com/binance-exchange/binance-official-api-docs/blob/master/rest-api.md#compressedaggregate-trades-list.

Returns:an iterator of JSON objects, one per trade. The format of

each object is identical to Client.aggregate_trades().

cancel_order(**params)[source]

Cancel an active order. Either orderId or origClientOrderId must be sent.

https://github.com/binance-exchange/binance-official-api-docs/blob/master/rest-api.md#cancel-order-trade

Parameters:
  • symbol (str) – required
  • orderId (int) – The unique order id
  • origClientOrderId (str) – optional
  • newClientOrderId (str) – Used to uniquely identify this cancel. Automatically generated by default.
  • recvWindow (int) – the number of milliseconds the request is valid for
Returns:

API response

{
    "symbol": "LTCBTC",
    "origClientOrderId": "myOrder1",
    "orderId": 1,
    "clientOrderId": "cancelMyOrder1"
}
Raises:BinanceRequestException, BinanceAPIException
create_order(**params)[source]

Send in a new order

Any order with an icebergQty MUST have timeInForce set to GTC.

https://github.com/binance-exchange/binance-official-api-docs/blob/master/rest-api.md#new-order–trade

Parameters:
  • symbol (str) – required
  • side (str) – required
  • type (str) – required
  • timeInForce (str) – required if limit order
  • quantity (decimal) – required
  • price (str) – required
  • newClientOrderId (str) – A unique id for the order. Automatically generated if not sent.
  • icebergQty (decimal) – Used with LIMIT, STOP_LOSS_LIMIT, and TAKE_PROFIT_LIMIT to create an iceberg order.
  • newOrderRespType (str) – Set the response JSON. ACK, RESULT, or FULL; default: RESULT.
  • recvWindow (int) – the number of milliseconds the request is valid for
Returns:

API response

Response ACK:

{
    "symbol":"LTCBTC",
    "orderId": 1,
    "clientOrderId": "myOrder1" # Will be newClientOrderId
    "transactTime": 1499827319559
}

Response RESULT:

{
    "symbol": "BTCUSDT",
    "orderId": 28,
    "clientOrderId": "6gCrw2kRUAF9CvJDGP16IP",
    "transactTime": 1507725176595,
    "price": "0.00000000",
    "origQty": "10.00000000",
    "executedQty": "10.00000000",
    "status": "FILLED",
    "timeInForce": "GTC",
    "type": "MARKET",
    "side": "SELL"
}

Response FULL:

{
    "symbol": "BTCUSDT",
    "orderId": 28,
    "clientOrderId": "6gCrw2kRUAF9CvJDGP16IP",
    "transactTime": 1507725176595,
    "price": "0.00000000",
    "origQty": "10.00000000",
    "executedQty": "10.00000000",
    "status": "FILLED",
    "timeInForce": "GTC",
    "type": "MARKET",
    "side": "SELL",
    "fills": [
        {
            "price": "4000.00000000",
            "qty": "1.00000000",
            "commission": "4.00000000",
            "commissionAsset": "USDT"
        },
        {
            "price": "3999.00000000",
            "qty": "5.00000000",
            "commission": "19.99500000",
            "commissionAsset": "USDT"
        },
        {
            "price": "3998.00000000",
            "qty": "2.00000000",
            "commission": "7.99600000",
            "commissionAsset": "USDT"
        },
        {
            "price": "3997.00000000",
            "qty": "1.00000000",
            "commission": "3.99700000",
            "commissionAsset": "USDT"
        },
        {
            "price": "3995.00000000",
            "qty": "1.00000000",
            "commission": "3.99500000",
            "commissionAsset": "USDT"
        }
    ]
}
Raises:BinanceRequestException, BinanceAPIException, BinanceOrderException, BinanceOrderMinAmountException, BinanceOrderMinPriceException, BinanceOrderMinTotalException, BinanceOrderUnknownSymbolException, BinanceOrderInactiveSymbolException
create_test_order(**params)[source]

Test new order creation and signature/recvWindow long. Creates and validates a new order but does not send it into the matching engine.

https://github.com/binance-exchange/binance-official-api-docs/blob/master/rest-api.md#test-new-order-trade

Parameters:
  • symbol (str) – required
  • side (str) – required
  • type (str) – required
  • timeInForce (str) – required if limit order
  • quantity (decimal) – required
  • price (str) – required
  • newClientOrderId (str) – A unique id for the order. Automatically generated if not sent.
  • icebergQty (decimal) – Used with iceberg orders
  • newOrderRespType (str) – Set the response JSON. ACK, RESULT, or FULL; default: RESULT.
  • recvWindow (int) – The number of milliseconds the request is valid for
Returns:

API response

{}
Raises:BinanceRequestException, BinanceAPIException, BinanceOrderException, BinanceOrderMinAmountException, BinanceOrderMinPriceException, BinanceOrderMinTotalException, BinanceOrderUnknownSymbolException, BinanceOrderInactiveSymbolException
get_account(**params)[source]

Get current account information.

https://github.com/binance-exchange/binance-official-api-docs/blob/master/rest-api.md#account-information-user_data

Parameters:recvWindow (int) – the number of milliseconds the request is valid for
Returns:API response
{
    "makerCommission": 15,
    "takerCommission": 15,
    "buyerCommission": 0,
    "sellerCommission": 0,
    "canTrade": true,
    "canWithdraw": true,
    "canDeposit": true,
    "balances": [
        {
            "asset": "BTC",
            "free": "4723846.89208129",
            "locked": "0.00000000"
        },
        {
            "asset": "LTC",
            "free": "4763368.68006011",
            "locked": "0.00000000"
        }
    ]
}
Raises:BinanceRequestException, BinanceAPIException
get_account_status(**params)[source]

Get account status detail.

https://github.com/binance-exchange/binance-official-api-docs/blob/master/wapi-api.md#account-status-user_data

Parameters:recvWindow (int) – the number of milliseconds the request is valid for
Returns:API response
{
    "msg": "Order failed:Low Order fill rate! Will be reactivated after 5 minutes.",
    "success": true,
    "objs": [
        "5"
    ]
}
Raises:BinanceWithdrawException
get_aggregate_trades(**params)[source]

Get compressed, aggregate trades. Trades that fill at the time, from the same order, with the same price will have the quantity aggregated.

https://github.com/binance-exchange/binance-official-api-docs/blob/master/rest-api.md#compressedaggregate-trades-list

Parameters:
  • symbol (str) – required
  • fromId (str) – ID to get aggregate trades from INCLUSIVE.
  • startTime (int) – Timestamp in ms to get aggregate trades from INCLUSIVE.
  • endTime (int) – Timestamp in ms to get aggregate trades until INCLUSIVE.
  • limit (int) – Default 500; max 500.
Returns:

API response

[
    {
        "a": 26129,         # Aggregate tradeId
        "p": "0.01633102",  # Price
        "q": "4.70443515",  # Quantity
        "f": 27781,         # First tradeId
        "l": 27781,         # Last tradeId
        "T": 1498793709153, # Timestamp
        "m": true,          # Was the buyer the maker?
        "M": true           # Was the trade the best price match?
    }
]
Raises:BinanceRequestException, BinanceAPIException
get_all_orders(**params)[source]

Get all account orders; active, canceled, or filled.

https://github.com/binance-exchange/binance-official-api-docs/blob/master/rest-api.md#all-orders-user_data

Parameters:
  • symbol (str) – required
  • orderId (int) – The unique order id
  • limit (int) – Default 500; max 500.
  • recvWindow (int) – the number of milliseconds the request is valid for
Returns:

API response

[
    {
        "symbol": "LTCBTC",
        "orderId": 1,
        "clientOrderId": "myOrder1",
        "price": "0.1",
        "origQty": "1.0",
        "executedQty": "0.0",
        "status": "NEW",
        "timeInForce": "GTC",
        "type": "LIMIT",
        "side": "BUY",
        "stopPrice": "0.0",
        "icebergQty": "0.0",
        "time": 1499827319559
    }
]
Raises:BinanceRequestException, BinanceAPIException
get_all_tickers()[source]

Latest price for all symbols.

https://www.binance.com/restapipub.html#symbols-price-ticker

Returns:List of market tickers
[
    {
        "symbol": "LTCBTC",
        "price": "4.00000200"
    },
    {
        "symbol": "ETHBTC",
        "price": "0.07946600"
    }
]
Raises:BinanceRequestException, BinanceAPIException
get_asset_balance(asset, **params)[source]

Get current asset balance.

https://github.com/binance-exchange/binance-official-api-docs/blob/master/rest-api.md#account-information-user_data

Parameters:
  • asset (str) – required
  • recvWindow (int) – the number of milliseconds the request is valid for
Returns:

dictionary or None if not found

{
    "asset": "BTC",
    "free": "4723846.89208129",
    "locked": "0.00000000"
}
Raises:BinanceRequestException, BinanceAPIException
get_asset_details(**params)[source]

Fetch details on assets.

https://github.com/binance-exchange/binance-official-api-docs/blob/master/wapi-api.md#asset-detail-user_data

Parameters:recvWindow (int) – the number of milliseconds the request is valid for
Returns:API response
{
    "success": true,
    "assetDetail": {
        "CTR": {
            "minWithdrawAmount": "70.00000000", //min withdraw amount
            "depositStatus": false,//deposit status
            "withdrawFee": 35, // withdraw fee
            "withdrawStatus": true, //withdraw status
            "depositTip": "Delisted, Deposit Suspended" //reason
        },
        "SKY": {
            "minWithdrawAmount": "0.02000000",
            "depositStatus": true,
            "withdrawFee": 0.01,
            "withdrawStatus": true
        }
    }
}
Raises:BinanceWithdrawException
get_deposit_address(**params)[source]

Fetch a deposit address for a symbol

https://www.binance.com/restapipub.html

Parameters:
  • asset (str) – required
  • recvWindow (int) – the number of milliseconds the request is valid for
Returns:

API response

{
    "address": "0x6915f16f8791d0a1cc2bf47c13a6b2a92000504b",
    "success": true,
    "addressTag": "1231212",
    "asset": "BNB"
}
Raises:BinanceRequestException, BinanceAPIException
get_deposit_history(**params)[source]

Fetch deposit history.

https://www.binance.com/restapipub.html

Parameters:
  • asset (str) – optional
  • startTime (long) – optional
  • endTime (long) – optional
  • recvWindow (int) – the number of milliseconds the request is valid for
Returns:

API response

{
    "depositList": [
        {
            "insertTime": 1508198532000,
            "amount": 0.04670582,
            "asset": "ETH",
            "status": 1
        }
    ],
    "success": true
}
Raises:BinanceRequestException, BinanceAPIException
get_dust_log(**params)[source]

Get log of small amounts exchanged for BNB.

https://github.com/binance-exchange/binance-official-api-docs/blob/master/wapi-api.md#dustlog-user_data

Parameters:recvWindow (int) – the number of milliseconds the request is valid for
Returns:API response
{
    "success": true,
    "results": {
        "total": 2,   //Total counts of exchange
        "rows": [
            {
                "transfered_total": "0.00132256", # Total transfered BNB amount for this exchange.
                "service_charge_total": "0.00002699",   # Total service charge amount for this exchange.
                "tran_id": 4359321,
                "logs": [           # Details of  this exchange.
                    {
                        "tranId": 4359321,
                        "serviceChargeAmount": "0.000009",
                        "uid": "10000015",
                        "amount": "0.0009",
                        "operateTime": "2018-05-03 17:07:04",
                        "transferedAmount": "0.000441",
                        "fromAsset": "USDT"
                    },
                    {
                        "tranId": 4359321,
                        "serviceChargeAmount": "0.00001799",
                        "uid": "10000015",
                        "amount": "0.0009",
                        "operateTime": "2018-05-03 17:07:04",
                        "transferedAmount": "0.00088156",
                        "fromAsset": "ETH"
                    }
                ],
                "operate_time": "2018-05-03 17:07:04" //The time of this exchange.
            },
            {
                "transfered_total": "0.00058795",
                "service_charge_total": "0.000012",
                "tran_id": 4357015,
                "logs": [       // Details of  this exchange.
                    {
                        "tranId": 4357015,
                        "serviceChargeAmount": "0.00001",
                        "uid": "10000015",
                        "amount": "0.001",
                        "operateTime": "2018-05-02 13:52:24",
                        "transferedAmount": "0.00049",
                        "fromAsset": "USDT"
                    },
                    {
                        "tranId": 4357015,
                        "serviceChargeAmount": "0.000002",
                        "uid": "10000015",
                        "amount": "0.0001",
                        "operateTime": "2018-05-02 13:51:11",
                        "transferedAmount": "0.00009795",
                        "fromAsset": "ETH"
                    }
                ],
                "operate_time": "2018-05-02 13:51:11"
            }
        ]
    }
}
Raises:BinanceWithdrawException
get_exchange_info()[source]

Return rate limits and list of symbols

Returns:list - List of product dictionaries
{
    "timezone": "UTC",
    "serverTime": 1508631584636,
    "rateLimits": [
        {
            "rateLimitType": "REQUESTS",
            "interval": "MINUTE",
            "limit": 1200
        },
        {
            "rateLimitType": "ORDERS",
            "interval": "SECOND",
            "limit": 10
        },
        {
            "rateLimitType": "ORDERS",
            "interval": "DAY",
            "limit": 100000
        }
    ],
    "exchangeFilters": [],
    "symbols": [
        {
            "symbol": "ETHBTC",
            "status": "TRADING",
            "baseAsset": "ETH",
            "baseAssetPrecision": 8,
            "quoteAsset": "BTC",
            "quotePrecision": 8,
            "orderTypes": ["LIMIT", "MARKET"],
            "icebergAllowed": false,
            "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"
                }, {
                    "filterType": "MIN_NOTIONAL",
                    "minNotional": "0.00100000"
                }
            ]
        }
    ]
}
Raises:BinanceRequestException, BinanceAPIException
get_historical_klines(symbol, interval, start_str, end_str=None)[source]

Get Historical Klines from Binance

See dateparser docs for valid start and end string formats http://dateparser.readthedocs.io/en/latest/

If using offset strings for dates add “UTC” to date string e.g. “now UTC”, “11 hours ago UTC”

Parameters:
  • symbol (str) – Name of symbol pair e.g BNBBTC
  • interval (str) – Binance Kline interval
  • start_str (str|int) – Start date string in UTC format or timestamp in milliseconds
  • end_str (str|int) – optional - end date string in UTC format or timestamp in milliseconds (default will fetch everything up to now)
Returns:

list of OHLCV values

get_historical_klines_generator(symbol, interval, start_str, end_str=None)[source]

Get Historical Klines from Binance

See dateparser docs for valid start and end string formats http://dateparser.readthedocs.io/en/latest/

If using offset strings for dates add “UTC” to date string e.g. “now UTC”, “11 hours ago UTC”

Parameters:
  • symbol (str) – Name of symbol pair e.g BNBBTC
  • interval (str) – Binance Kline interval
  • start_str (str|int) – Start date string in UTC format or timestamp in milliseconds
  • end_str (str|int) – optional - end date string in UTC format or timestamp in milliseconds (default will fetch everything up to now)
Returns:

generator of OHLCV values

get_historical_trades(**params)[source]

Get older trades.

https://github.com/binance-exchange/binance-official-api-docs/blob/master/rest-api.md#recent-trades-list

Parameters:
  • symbol (str) – required
  • limit (int) – Default 500; max 500.
  • fromId (str) – TradeId to fetch from. Default gets most recent trades.
Returns:

API response

[
    {
        "id": 28457,
        "price": "4.00000100",
        "qty": "12.00000000",
        "time": 1499865549590,
        "isBuyerMaker": true,
        "isBestMatch": true
    }
]
Raises:BinanceRequestException, BinanceAPIException
get_klines(**params)[source]

Kline/candlestick bars for a symbol. Klines are uniquely identified by their open time.

https://github.com/binance-exchange/binance-official-api-docs/blob/master/rest-api.md#klinecandlestick-data

Parameters:
  • symbol (str) – required
  • interval (str) –
  • limit (int) –
    • Default 500; max 500.
  • startTime (int) –
  • endTime (int) –
Returns:

API response

[
    [
        1499040000000,      # Open time
        "0.01634790",       # Open
        "0.80000000",       # High
        "0.01575800",       # Low
        "0.01577100",       # Close
        "148976.11427815",  # Volume
        1499644799999,      # Close time
        "2434.19055334",    # Quote asset volume
        308,                # Number of trades
        "1756.87402397",    # Taker buy base asset volume
        "28.46694368",      # Taker buy quote asset volume
        "17928899.62484339" # Can be ignored
    ]
]
Raises:BinanceRequestException, BinanceAPIException
get_my_trades(**params)[source]

Get trades for a specific symbol.

https://github.com/binance-exchange/binance-official-api-docs/blob/master/rest-api.md#account-trade-list-user_data

Parameters:
  • symbol (str) – required
  • limit (int) – Default 500; max 500.
  • fromId (int) – TradeId to fetch from. Default gets most recent trades.
  • recvWindow (int) – the number of milliseconds the request is valid for
Returns:

API response

[
    {
        "id": 28457,
        "price": "4.00000100",
        "qty": "12.00000000",
        "commission": "10.10000000",
        "commissionAsset": "BNB",
        "time": 1499865549590,
        "isBuyer": true,
        "isMaker": false,
        "isBestMatch": true
    }
]
Raises:BinanceRequestException, BinanceAPIException
get_open_orders(**params)[source]

Get all open orders on a symbol.

https://github.com/binance-exchange/binance-official-api-docs/blob/master/rest-api.md#current-open-orders-user_data

Parameters:
  • symbol (str) – optional
  • recvWindow (int) – the number of milliseconds the request is valid for
Returns:

API response

[
    {
        "symbol": "LTCBTC",
        "orderId": 1,
        "clientOrderId": "myOrder1",
        "price": "0.1",
        "origQty": "1.0",
        "executedQty": "0.0",
        "status": "NEW",
        "timeInForce": "GTC",
        "type": "LIMIT",
        "side": "BUY",
        "stopPrice": "0.0",
        "icebergQty": "0.0",
        "time": 1499827319559
    }
]
Raises:BinanceRequestException, BinanceAPIException
get_order(**params)[source]

Check an order’s status. Either orderId or origClientOrderId must be sent.

https://github.com/binance-exchange/binance-official-api-docs/blob/master/rest-api.md#query-order-user_data

Parameters:
  • symbol (str) – required
  • orderId (int) – The unique order id
  • origClientOrderId (str) – optional
  • recvWindow (int) – the number of milliseconds the request is valid for
Returns:

API response

{
    "symbol": "LTCBTC",
    "orderId": 1,
    "clientOrderId": "myOrder1",
    "price": "0.1",
    "origQty": "1.0",
    "executedQty": "0.0",
    "status": "NEW",
    "timeInForce": "GTC",
    "type": "LIMIT",
    "side": "BUY",
    "stopPrice": "0.0",
    "icebergQty": "0.0",
    "time": 1499827319559
}
Raises:BinanceRequestException, BinanceAPIException
get_order_book(**params)[source]

Get the Order Book for the market

https://github.com/binance-exchange/binance-official-api-docs/blob/master/rest-api.md#order-book

Parameters:
  • symbol (str) – required
  • limit (int) – Default 100; max 1000
Returns:

API response

{
    "lastUpdateId": 1027024,
    "bids": [
        [
            "4.00000000",     # PRICE
            "431.00000000",   # QTY
            []                # Can be ignored
        ]
    ],
    "asks": [
        [
            "4.00000200",
            "12.00000000",
            []
        ]
    ]
}
Raises:BinanceRequestException, BinanceAPIException
get_orderbook_ticker(**params)[source]

Latest price for a symbol or symbols.

https://github.com/binance-exchange/binance-official-api-docs/blob/master/rest-api.md#symbol-order-book-ticker

Parameters:symbol (str) –
Returns:API response
{
    "symbol": "LTCBTC",
    "bidPrice": "4.00000000",
    "bidQty": "431.00000000",
    "askPrice": "4.00000200",
    "askQty": "9.00000000"
}

OR

[
    {
        "symbol": "LTCBTC",
        "bidPrice": "4.00000000",
        "bidQty": "431.00000000",
        "askPrice": "4.00000200",
        "askQty": "9.00000000"
    },
    {
        "symbol": "ETHBTC",
        "bidPrice": "0.07946700",
        "bidQty": "9.00000000",
        "askPrice": "100000.00000000",
        "askQty": "1000.00000000"
    }
]
Raises:BinanceRequestException, BinanceAPIException
get_orderbook_tickers()[source]

Best price/qty on the order book for all symbols.

https://www.binance.com/restapipub.html#symbols-order-book-ticker

Returns:List of order book market entries
[
    {
        "symbol": "LTCBTC",
        "bidPrice": "4.00000000",
        "bidQty": "431.00000000",
        "askPrice": "4.00000200",
        "askQty": "9.00000000"
    },
    {
        "symbol": "ETHBTC",
        "bidPrice": "0.07946700",
        "bidQty": "9.00000000",
        "askPrice": "100000.00000000",
        "askQty": "1000.00000000"
    }
]
Raises:BinanceRequestException, BinanceAPIException
get_products()[source]

Return list of products currently listed on Binance

Use get_exchange_info() call instead

Returns:list - List of product dictionaries
Raises:BinanceRequestException, BinanceAPIException
get_recent_trades(**params)[source]

Get recent trades (up to last 500).

https://github.com/binance-exchange/binance-official-api-docs/blob/master/rest-api.md#recent-trades-list

Parameters:
  • symbol (str) – required
  • limit (int) – Default 500; max 500.
Returns:

API response

[
    {
        "id": 28457,
        "price": "4.00000100",
        "qty": "12.00000000",
        "time": 1499865549590,
        "isBuyerMaker": true,
        "isBestMatch": true
    }
]
Raises:BinanceRequestException, BinanceAPIException
get_server_time()[source]

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

https://github.com/binance-exchange/binance-official-api-docs/blob/master/rest-api.md#check-server-time

Returns:Current server time
{
    "serverTime": 1499827319559
}
Raises:BinanceRequestException, BinanceAPIException
get_symbol_info(symbol)[source]

Return information about a symbol

Parameters:symbol (str) – required e.g BNBBTC
Returns:Dict if found, None if not
{
    "symbol": "ETHBTC",
    "status": "TRADING",
    "baseAsset": "ETH",
    "baseAssetPrecision": 8,
    "quoteAsset": "BTC",
    "quotePrecision": 8,
    "orderTypes": ["LIMIT", "MARKET"],
    "icebergAllowed": false,
    "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"
        }, {
            "filterType": "MIN_NOTIONAL",
            "minNotional": "0.00100000"
        }
    ]
}
Raises:BinanceRequestException, BinanceAPIException
get_symbol_ticker(**params)[source]

Latest price for a symbol or symbols.

https://github.com/binance-exchange/binance-official-api-docs/blob/master/rest-api.md#24hr-ticker-price-change-statistics

Parameters:symbol (str) –
Returns:API response
{
    "symbol": "LTCBTC",
    "price": "4.00000200"
}

OR

[
    {
        "symbol": "LTCBTC",
        "price": "4.00000200"
    },
    {
        "symbol": "ETHBTC",
        "price": "0.07946600"
    }
]
Raises:BinanceRequestException, BinanceAPIException
get_system_status()[source]

Get system status detail.

https://github.com/binance-exchange/binance-official-api-docs/blob/master/wapi-api.md#system-status-system

Returns:API response
{
    "status": 0,        # 0: normal,1:system maintenance
    "msg": "normal"     # normal or System maintenance.
}
Raises:BinanceAPIException
get_ticker(**params)[source]

24 hour price change statistics.

https://github.com/binance-exchange/binance-official-api-docs/blob/master/rest-api.md#24hr-ticker-price-change-statistics

Parameters:symbol (str) –
Returns:API response
{
    "priceChange": "-94.99999800",
    "priceChangePercent": "-95.960",
    "weightedAvgPrice": "0.29628482",
    "prevClosePrice": "0.10002000",
    "lastPrice": "4.00000200",
    "bidPrice": "4.00000000",
    "askPrice": "4.00000200",
    "openPrice": "99.00000000",
    "highPrice": "100.00000000",
    "lowPrice": "0.10000000",
    "volume": "8913.30000000",
    "openTime": 1499783499040,
    "closeTime": 1499869899040,
    "fristId": 28385,   # First tradeId
    "lastId": 28460,    # Last tradeId
    "count": 76         # Trade count
}

OR

[
    {
        "priceChange": "-94.99999800",
        "priceChangePercent": "-95.960",
        "weightedAvgPrice": "0.29628482",
        "prevClosePrice": "0.10002000",
        "lastPrice": "4.00000200",
        "bidPrice": "4.00000000",
        "askPrice": "4.00000200",
        "openPrice": "99.00000000",
        "highPrice": "100.00000000",
        "lowPrice": "0.10000000",
        "volume": "8913.30000000",
        "openTime": 1499783499040,
        "closeTime": 1499869899040,
        "fristId": 28385,   # First tradeId
        "lastId": 28460,    # Last tradeId
        "count": 76         # Trade count
    }
]
Raises:BinanceRequestException, BinanceAPIException
get_trade_fee(**params)[source]

Get trade fee.

https://github.com/binance-exchange/binance-official-api-docs/blob/master/wapi-api.md#trade-fee-user_data

Parameters:
  • symbol (str) – optional
  • recvWindow (int) – the number of milliseconds the request is valid for
Returns:

API response

{
    "tradeFee": [
        {
            "symbol": "ADABNB",
            "maker": 0.9000,
            "taker": 1.0000
        }, {
            "symbol": "BNBBTC",
            "maker": 0.3000,
            "taker": 0.3000
        }
    ],
    "success": true
}
Raises:BinanceWithdrawException
get_withdraw_fee(**params)[source]

Fetch the withdrawal fee for an asset

Parameters:
  • asset (str) – required
  • recvWindow (int) – the number of milliseconds the request is valid for
Returns:

API response

{
    "withdrawFee": "0.0005",
    "success": true
}
Raises:BinanceRequestException, BinanceAPIException
get_withdraw_history(**params)[source]

Fetch withdraw history.

https://www.binance.com/restapipub.html

Parameters:
  • asset (str) – optional
  • startTime (long) – optional
  • endTime (long) – optional
  • recvWindow (int) – the number of milliseconds the request is valid for
Returns:

API response

{
    "withdrawList": [
        {
            "amount": 1,
            "address": "0x6915f16f8791d0a1cc2bf47c13a6b2a92000504b",
            "asset": "ETH",
            "applyTime": 1508198532000
            "status": 4
        },
        {
            "amount": 0.005,
            "address": "0x6915f16f8791d0a1cc2bf47c13a6b2a92000504b",
            "txId": "0x80aaabed54bdab3f6de5868f89929a2371ad21d666f20f7393d1a3389fad95a1",
            "asset": "ETH",
            "applyTime": 1508198532000,
            "status": 4
        }
    ],
    "success": true
}
Raises:BinanceRequestException, BinanceAPIException
order_limit(timeInForce='GTC', **params)[source]

Send in a new limit order

Any order with an icebergQty MUST have timeInForce set to GTC.

Parameters:
  • symbol (str) – required
  • side (str) – required
  • quantity (decimal) – required
  • price (str) – required
  • timeInForce (str) – default Good till cancelled
  • newClientOrderId (str) – A unique id for the order. Automatically generated if not sent.
  • icebergQty (decimal) – Used with LIMIT, STOP_LOSS_LIMIT, and TAKE_PROFIT_LIMIT to create an iceberg order.
  • newOrderRespType (str) – Set the response JSON. ACK, RESULT, or FULL; default: RESULT.
  • recvWindow (int) – the number of milliseconds the request is valid for
Returns:

API response

See order endpoint for full response options

Raises:BinanceRequestException, BinanceAPIException, BinanceOrderException, BinanceOrderMinAmountException, BinanceOrderMinPriceException, BinanceOrderMinTotalException, BinanceOrderUnknownSymbolException, BinanceOrderInactiveSymbolException
order_limit_buy(timeInForce='GTC', **params)[source]

Send in a new limit buy order

Any order with an icebergQty MUST have timeInForce set to GTC.

Parameters:
  • symbol (str) – required
  • quantity (decimal) – required
  • price (str) – required
  • timeInForce (str) – default Good till cancelled
  • newClientOrderId (str) – A unique id for the order. Automatically generated if not sent.
  • stopPrice (decimal) – Used with stop orders
  • icebergQty (decimal) – Used with iceberg orders
  • newOrderRespType (str) – Set the response JSON. ACK, RESULT, or FULL; default: RESULT.
  • recvWindow (int) – the number of milliseconds the request is valid for
Returns:

API response

See order endpoint for full response options

Raises:BinanceRequestException, BinanceAPIException, BinanceOrderException, BinanceOrderMinAmountException, BinanceOrderMinPriceException, BinanceOrderMinTotalException, BinanceOrderUnknownSymbolException, BinanceOrderInactiveSymbolException
order_limit_sell(timeInForce='GTC', **params)[source]

Send in a new limit sell order

Parameters:
  • symbol (str) – required
  • quantity (decimal) – required
  • price (str) – required
  • timeInForce (str) – default Good till cancelled
  • newClientOrderId (str) – A unique id for the order. Automatically generated if not sent.
  • stopPrice (decimal) – Used with stop orders
  • icebergQty (decimal) – Used with iceberg orders
  • newOrderRespType (str) – Set the response JSON. ACK, RESULT, or FULL; default: RESULT.
  • recvWindow (int) – the number of milliseconds the request is valid for
Returns:

API response

See order endpoint for full response options

Raises:BinanceRequestException, BinanceAPIException, BinanceOrderException, BinanceOrderMinAmountException, BinanceOrderMinPriceException, BinanceOrderMinTotalException, BinanceOrderUnknownSymbolException, BinanceOrderInactiveSymbolException
order_market(**params)[source]

Send in a new market order

Parameters:
  • symbol (str) – required
  • side (str) – required
  • quantity (decimal) – required
  • newClientOrderId (str) – A unique id for the order. Automatically generated if not sent.
  • newOrderRespType (str) – Set the response JSON. ACK, RESULT, or FULL; default: RESULT.
  • recvWindow (int) – the number of milliseconds the request is valid for
Returns:

API response

See order endpoint for full response options

Raises:BinanceRequestException, BinanceAPIException, BinanceOrderException, BinanceOrderMinAmountException, BinanceOrderMinPriceException, BinanceOrderMinTotalException, BinanceOrderUnknownSymbolException, BinanceOrderInactiveSymbolException
order_market_buy(**params)[source]

Send in a new market buy order

Parameters:
  • symbol (str) – required
  • quantity (decimal) – required
  • newClientOrderId (str) – A unique id for the order. Automatically generated if not sent.
  • newOrderRespType (str) – Set the response JSON. ACK, RESULT, or FULL; default: RESULT.
  • recvWindow (int) – the number of milliseconds the request is valid for
Returns:

API response

See order endpoint for full response options

Raises:BinanceRequestException, BinanceAPIException, BinanceOrderException, BinanceOrderMinAmountException, BinanceOrderMinPriceException, BinanceOrderMinTotalException, BinanceOrderUnknownSymbolException, BinanceOrderInactiveSymbolException
order_market_sell(**params)[source]

Send in a new market sell order

Parameters:
  • symbol (str) – required
  • quantity (decimal) – required
  • newClientOrderId (str) – A unique id for the order. Automatically generated if not sent.
  • newOrderRespType (str) – Set the response JSON. ACK, RESULT, or FULL; default: RESULT.
  • recvWindow (int) – the number of milliseconds the request is valid for
Returns:

API response

See order endpoint for full response options

Raises:BinanceRequestException, BinanceAPIException, BinanceOrderException, BinanceOrderMinAmountException, BinanceOrderMinPriceException, BinanceOrderMinTotalException, BinanceOrderUnknownSymbolException, BinanceOrderInactiveSymbolException
ping()[source]

Test connectivity to the Rest API.

https://github.com/binance-exchange/binance-official-api-docs/blob/master/rest-api.md#test-connectivity

Returns:Empty array
{}
Raises:BinanceRequestException, BinanceAPIException
stream_close(listenKey)[source]

Close out a user data stream.

https://github.com/binance-exchange/binance-official-api-docs/blob/master/rest-api.md#close-user-data-stream-user_stream

Parameters:listenKey (str) – required
Returns:API response
{}
Raises:BinanceRequestException, BinanceAPIException
stream_get_listen_key()[source]

Start a new user data stream and return the listen key If a stream already exists it should return the same key. If the stream becomes invalid a new key is returned.

Can be used to keep the user stream alive.

https://github.com/binance-exchange/binance-official-api-docs/blob/master/rest-api.md#start-user-data-stream-user_stream

Returns:API response
{
    "listenKey": "pqia91ma19a5s61cv6a81va65sdf19v8a65a1a5s61cv6a81va65sdf19v8a65a1"
}
Raises:BinanceRequestException, BinanceAPIException
stream_keepalive(listenKey)[source]

PING a user data stream to prevent a time out.

https://github.com/binance-exchange/binance-official-api-docs/blob/master/rest-api.md#keepalive-user-data-stream-user_stream

Parameters:listenKey (str) – required
Returns:API response
{}
Raises:BinanceRequestException, BinanceAPIException
withdraw(**params)[source]

Submit a withdraw request.

https://www.binance.com/restapipub.html

Assumptions:

  • You must have Withdraw permissions enabled on your API key
  • You must have withdrawn to the address specified through the website and approved the transaction via email
Parameters:
  • asset (str) – required
  • amount (decimal) – required
  • name (str) – optional - Description of the address, default asset value passed will be used
  • recvWindow (int) – the number of milliseconds the request is valid for
Returns:

API response

{
    "msg": "success",
    "success": true,
    "id":"7213fea8e94b4a5593d507237e5a555b"
}
Raises:BinanceRequestException, BinanceAPIException, BinanceWithdrawException

depthcache module

class binance.depthcache.DepthCache(symbol)[source]

Bases: object

__init__(symbol)[source]

Intialise the DepthCache

Parameters:symbol (string) – Symbol to create depth cache for
add_ask(ask)[source]

Add an ask to the cache

Parameters:ask
Returns:
add_bid(bid)[source]

Add a bid to the cache

Parameters:bid
Returns:
get_asks()[source]

Get the current asks

Returns:list of asks with price and quantity as floats
[
    [
        0.0001955,  # Price
        57.0'       # Quantity
    ],
    [
        0.00019699,
        778.0
    ],
    [
        0.000197,
        64.0
    ],
    [
        0.00019709,
        1130.0
    ],
    [
        0.0001971,
        385.0
    ]
]
get_bids()[source]

Get the current bids

Returns:list of bids with price and quantity as floats
[
    [
        0.0001946,  # Price
        45.0        # Quantity
    ],
    [
        0.00019459,
        2384.0
    ],
    [
        0.00019158,
        5219.0
    ],
    [
        0.00019157,
        1180.0
    ],
    [
        0.00019082,
        287.0
    ]
]
static sort_depth(vals, reverse=False)[source]

Sort bids or asks by price

class binance.depthcache.DepthCacheManager(client, symbol, callback=None, refresh_interval=1800, bm=None)[source]

Bases: object

__init__(client, symbol, callback=None, refresh_interval=1800, bm=None)[source]

Initialise the DepthCacheManager

Parameters:
  • client (binance.Client) – Binance API client
  • symbol (string) – Symbol to create depth cache for
  • callback (function) – Optional function to receive depth cache updates
  • refresh_interval (int) – Optional number of seconds between cache refresh, use 0 or None to disable
close(close_socket=False)[source]

Close the open socket for this manager

Returns:
get_depth_cache()[source]

Get the current depth cache

Returns:DepthCache object

exceptions module

exception binance.exceptions.BinanceAPIException(response)[source]

Bases: exceptions.Exception

__init__(response)[source]

x.__init__(…) initializes x; see help(type(x)) for signature

exception binance.exceptions.BinanceOrderException(code, message)[source]

Bases: exceptions.Exception

__init__(code, message)[source]

x.__init__(…) initializes x; see help(type(x)) for signature

exception binance.exceptions.BinanceOrderInactiveSymbolException(value)[source]

Bases: binance.exceptions.BinanceOrderException

__init__(value)[source]

x.__init__(…) initializes x; see help(type(x)) for signature

exception binance.exceptions.BinanceOrderMinAmountException(value)[source]

Bases: binance.exceptions.BinanceOrderException

__init__(value)[source]

x.__init__(…) initializes x; see help(type(x)) for signature

exception binance.exceptions.BinanceOrderMinPriceException(value)[source]

Bases: binance.exceptions.BinanceOrderException

__init__(value)[source]

x.__init__(…) initializes x; see help(type(x)) for signature

exception binance.exceptions.BinanceOrderMinTotalException(value)[source]

Bases: binance.exceptions.BinanceOrderException

__init__(value)[source]

x.__init__(…) initializes x; see help(type(x)) for signature

exception binance.exceptions.BinanceOrderUnknownSymbolException(value)[source]

Bases: binance.exceptions.BinanceOrderException

__init__(value)[source]

x.__init__(…) initializes x; see help(type(x)) for signature

exception binance.exceptions.BinanceRequestException(message)[source]

Bases: exceptions.Exception

__init__(message)[source]

x.__init__(…) initializes x; see help(type(x)) for signature

exception binance.exceptions.BinanceWithdrawException(message)[source]

Bases: exceptions.Exception

__init__(message)[source]

x.__init__(…) initializes x; see help(type(x)) for signature

helpers module

binance.helpers.date_to_milliseconds(date_str)[source]

Convert UTC date to milliseconds

If using offset strings add “UTC” to date string e.g. “now UTC”, “11 hours ago UTC”

See dateparse docs for formats http://dateparser.readthedocs.io/en/latest/

Parameters:date_str (str) – date in readable format, i.e. “January 01, 2018”, “11 hours ago UTC”, “now UTC”
binance.helpers.interval_to_milliseconds(interval)[source]

Convert a Binance interval string to milliseconds

Parameters:interval (str) – Binance interval string, e.g.: 1m, 3m, 5m, 15m, 30m, 1h, 2h, 4h, 6h, 8h, 12h, 1d, 3d, 1w
Returns:int value of interval in milliseconds None if interval prefix is not a decimal integer None if interval suffix is not one of m, h, d, w

websockets module

class binance.websockets.BinanceClientFactory(*args, **kwargs)[source]

Bases: autobahn.twisted.websocket.WebSocketClientFactory, binance.websockets.BinanceReconnectingClientFactory

clientConnectionFailed(connector, reason)[source]

Called when a connection has failed to connect.

It may be useful to call connector.connect() - this will reconnect.

@type reason: L{twisted.python.failure.Failure}

clientConnectionLost(connector, reason)[source]

Called when an established connection is lost.

It may be useful to call connector.connect() - this will reconnect.

@type reason: L{twisted.python.failure.Failure}

protocol

alias of BinanceClientProtocol

class binance.websockets.BinanceClientProtocol[source]

Bases: autobahn.twisted.websocket.WebSocketClientProtocol

__init__()[source]

x.__init__(…) initializes x; see help(type(x)) for signature

onConnect(response)[source]

Callback fired directly after WebSocket opening handshake when new WebSocket server connection was established.

Parameters:response (instance of autobahn.websocket.protocol.ConnectionResponse) – WebSocket connection response information.
onMessage(payload, isBinary)[source]

Implements autobahn.websocket.interfaces.IWebSocketChannel.onMessage()

class binance.websockets.BinanceReconnectingClientFactory[source]

Bases: twisted.internet.protocol.ReconnectingClientFactory

initialDelay = 0.1
maxDelay = 10
maxRetries = 5
class binance.websockets.BinanceSocketManager(client, user_timeout=1800)[source]

Bases: threading.Thread

DEFAULT_USER_TIMEOUT = 1800
STREAM_URL = 'wss://stream.binance.com:9443/'
WEBSOCKET_DEPTH_10 = '10'
WEBSOCKET_DEPTH_20 = '20'
WEBSOCKET_DEPTH_5 = '5'
__init__(client, user_timeout=1800)[source]

Initialise the BinanceSocketManager

Parameters:
  • client (binance.Client) – Binance API client
  • user_timeout (int) – Custom websocket timeout
close()[source]

Close all connections

run()[source]

Method representing the thread’s activity.

You may override this method in a subclass. The standard run() method invokes the callable object passed to the object’s constructor as the target argument, if any, with sequential and keyword arguments taken from the args and kwargs arguments, respectively.

start_aggtrade_socket(symbol, callback)[source]

Start a websocket for symbol trade data

https://github.com/binance-exchange/binance-official-api-docs/blob/master/web-socket-streams.md#aggregate-trade-streams

Parameters:
  • symbol (str) – required
  • callback (function) – callback function to handle messages
Returns:

connection key string if successful, False otherwise

Message Format

{
    "e": "aggTrade",                # event type
    "E": 1499405254326,             # event time
    "s": "ETHBTC",                  # symbol
    "a": 70232,                             # aggregated tradeid
    "p": "0.10281118",              # price
    "q": "8.15632997",              # quantity
    "f": 77489,                             # first breakdown trade id
    "l": 77489,                             # last breakdown trade id
    "T": 1499405254324,             # trade time
    "m": false,                             # whether buyer is a maker
    "M": true                               # can be ignored
}
start_depth_socket(symbol, callback, depth=None)[source]

Start a websocket for symbol market depth returning either a diff or a partial book

https://github.com/binance-exchange/binance-official-api-docs/blob/master/web-socket-streams.md#partial-book-depth-streams

Parameters:
  • symbol (str) – required
  • callback (function) – callback function to handle messages
  • depth (str) – optional Number of depth entries to return, default None. If passed returns a partial book instead of a diff
Returns:

connection key string if successful, False otherwise

Partial Message Format

{
    "lastUpdateId": 160,  # Last update ID
    "bids": [             # Bids to be updated
        [
            "0.0024",     # price level to be updated
            "10",         # quantity
            []            # ignore
        ]
    ],
    "asks": [             # Asks to be updated
        [
            "0.0026",     # price level to be updated
            "100",        # quantity
            []            # ignore
        ]
    ]
}

Diff Message Format

{
    "e": "depthUpdate", # Event type
    "E": 123456789,     # Event time
    "s": "BNBBTC",      # Symbol
    "U": 157,           # First update ID in event
    "u": 160,           # Final update ID in event
    "b": [              # Bids to be updated
        [
            "0.0024",   # price level to be updated
            "10",       # quantity
            []          # ignore
        ]
    ],
    "a": [              # Asks to be updated
        [
            "0.0026",   # price level to be updated
            "100",      # quantity
            []          # ignore
        ]
    ]
}
start_kline_socket(symbol, callback, interval='1m')[source]

Start a websocket for symbol kline data

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

Parameters:
  • symbol (str) – required
  • callback (function) – callback function to handle messages
  • interval (str) – Kline interval, default KLINE_INTERVAL_1MINUTE
Returns:

connection key string if successful, False otherwise

Message Format

{
    "e": "kline",                                   # event type
    "E": 1499404907056,                             # event time
    "s": "ETHBTC",                                  # symbol
    "k": {
        "t": 1499404860000,                 # start time of this bar
        "T": 1499404919999,                 # end time of this bar
        "s": "ETHBTC",                              # symbol
        "i": "1m",                                  # interval
        "f": 77462,                                 # first trade id
        "L": 77465,                                 # last trade id
        "o": "0.10278577",                  # open
        "c": "0.10278645",                  # close
        "h": "0.10278712",                  # high
        "l": "0.10278518",                  # low
        "v": "17.47929838",                 # volume
        "n": 4,                                             # number of trades
        "x": false,                                 # whether this bar is final
        "q": "1.79662878",                  # quote volume
        "V": "2.34879839",                  # volume of active buy
        "Q": "0.24142166",                  # quote volume of active buy
        "B": "13279784.01349473"    # can be ignored
        }
}
start_miniticker_socket(callback, update_time=1000)[source]

Start a miniticker websocket for all trades

This is not in the official Binance api docs, but this is what feeds the right column on a ticker page on Binance.

Parameters:
  • callback (function) – callback function to handle messages
  • update_time (int) – time between callbacks in milliseconds, must be 1000 or greater
Returns:

connection key string if successful, False otherwise

Message Format

[
    {
        'e': '24hrMiniTicker',  # Event type
        'E': 1515906156273,     # Event time
        's': 'QTUMETH',         # Symbol
        'c': '0.03836900',      # close
        'o': '0.03953500',      # open
        'h': '0.04400000',      # high
        'l': '0.03756000',      # low
        'v': '147435.80000000', # volume
        'q': '5903.84338533'    # quote volume
    }
]
start_multiplex_socket(streams, callback)[source]

Start a multiplexed socket using a list of socket names. User stream sockets can not be included.

Symbols in socket name must be lowercase i.e bnbbtc@aggTrade, neobtc@ticker

Combined stream events are wrapped as follows: {“stream”:”<streamName>”,”data”:<rawPayload>}

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

Parameters:
  • streams (list) – list of stream names in lower case
  • callback (function) – callback function to handle messages
Returns:

connection key string if successful, False otherwise

Message Format - see Binance API docs for all types

start_symbol_ticker_socket(symbol, callback)[source]

Start a websocket for a symbol’s ticker data

https://github.com/binance-exchange/binance-official-api-docs/blob/master/web-socket-streams.md#individual-symbol-ticker-streams

Parameters:
  • symbol (str) – required
  • callback (function) – callback function to handle messages
Returns:

connection key string if successful, False otherwise

Message Format

{
    "e": "24hrTicker",  # Event type
    "E": 123456789,     # Event time
    "s": "BNBBTC",      # Symbol
    "p": "0.0015",      # Price change
    "P": "250.00",      # Price change percent
    "w": "0.0018",      # Weighted average price
    "x": "0.0009",      # Previous day's close price
    "c": "0.0025",      # Current day's close price
    "Q": "10",          # Close trade's quantity
    "b": "0.0024",      # Best bid price
    "B": "10",          # Bid bid quantity
    "a": "0.0026",      # Best ask price
    "A": "100",         # Best ask quantity
    "o": "0.0010",      # Open price
    "h": "0.0025",      # High price
    "l": "0.0010",      # Low price
    "v": "10000",       # Total traded base asset volume
    "q": "18",          # Total traded quote asset volume
    "O": 0,             # Statistics open time
    "C": 86400000,      # Statistics close time
    "F": 0,             # First trade ID
    "L": 18150,         # Last trade Id
    "n": 18151          # Total number of trades
}
start_ticker_socket(callback)[source]

Start a websocket for all ticker data

By default all markets are included in an array.

https://github.com/binance-exchange/binance-official-api-docs/blob/master/web-socket-streams.md#all-market-tickers-stream

Parameters:callback (function) – callback function to handle messages
Returns:connection key string if successful, False otherwise

Message Format

[
    {
        'F': 278610,
        'o': '0.07393000',
        's': 'BCCBTC',
        'C': 1509622420916,
        'b': '0.07800800',
        'l': '0.07160300',
        'h': '0.08199900',
        'L': 287722,
        'P': '6.694',
        'Q': '0.10000000',
        'q': '1202.67106335',
        'p': '0.00494900',
        'O': 1509536020916,
        'a': '0.07887800',
        'n': 9113,
        'B': '1.00000000',
        'c': '0.07887900',
        'x': '0.07399600',
        'w': '0.07639068',
        'A': '2.41900000',
        'v': '15743.68900000'
    }
]
start_trade_socket(symbol, callback)[source]

Start a websocket for symbol trade data

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

Parameters:
  • symbol (str) – required
  • callback (function) – callback function to handle messages
Returns:

connection key string if successful, False otherwise

Message Format

{
    "e": "trade",     # Event type
    "E": 123456789,   # Event time
    "s": "BNBBTC",    # Symbol
    "t": 12345,       # Trade ID
    "p": "0.001",     # Price
    "q": "100",       # Quantity
    "b": 88,          # Buyer order Id
    "a": 50,          # Seller order Id
    "T": 123456785,   # Trade time
    "m": true,        # Is the buyer the market maker?
    "M": true         # Ignore.
}
start_user_socket(callback)[source]

Start a websocket for user data

https://www.binance.com/restapipub.html#user-wss-endpoint

Parameters:callback (function) – callback function to handle messages
Returns:connection key string if successful, False otherwise

Message Format - see Binance API docs for all types

stop_socket(conn_key)[source]

Stop a websocket given the connection key

Parameters:conn_key (string) – Socket connection key
Returns:connection key string if successful, False otherwise