Skip to content


Switch branches/tags

Name already in use

A tag already exists with the provided branch name. Many Git commands accept both tag and branch names, so creating this branch may cause unexpected behavior. Are you sure you want to create this branch?

Latest commit


Git stats


Failed to load latest commit information.
Latest commit message
Commit time

Binance Public API Connector Python

PyPI version Python version Documentation Code Style License: MIT

This is a lightweight library that works as a connector to Binance public API

  • Supported APIs:
    • /api/*
    • /sapi/*
    • Spot Websocket Market Stream
    • Spot User Data Stream
    • Spot WebSocket API
  • Inclusion of test cases and examples
  • Customizable base URL, request timeout and HTTP proxy
  • Response metadata can be displayed


pip install binance-connector



Usage examples:

from import Spot

client = Spot()

# Get server timestamp
# Get klines of BTCUSDT at 1m interval
print(client.klines("BTCUSDT", "1m"))
# Get last 10 klines of BNBUSDT at 1h interval
print(client.klines("BNBUSDT", "1h", limit=10))

# API key/secret are required for user data endpoints
client = Spot(api_key='<api_key>', api_secret='<api_secret>')

# Get account and balance information

# Post a new order
params = {
    'symbol': 'BTCUSDT',
    'side': 'SELL',
    'type': 'LIMIT',
    'timeInForce': 'GTC',
    'quantity': 0.002,
    'price': 9500

response = client.new_order(**params)

Please find examples folder to check for more endpoints.

  • In order to set your API and Secret Key for use of the examples, create a file examples/config.ini with your keys.
  • Eg:
    # examples/config.ini


Binance supports HMAC, RSA and ED25519 API authentication.

# HMAC: pass API key and secret
client = Client(api_key, api_secret)

# RSA Keys
client = Client(api_key=api_key, private_key=private_key)

# ED25519 Keys
api_key = ""
private_key = "./private_key.pem"
private_key_pass = "<password_if_applicable>"

with open(private_key, 'rb') as f:
    private_key =

spot_client = Client(api_key=api_key, private_key=private_key, private_key_pass=private_key_pass)

# Encrypted RSA Key
client = Client(api_key=api_key, private_key=private_key, private_key_pass='password')

Please find examples/spot/wallet/ for more details on ED25519. Please find examples/spot/trade/ for more details on RSA.


Spot Testnet is available, it can be used to test /api/* endpoints.

To use testnet:

from import Spot as Client

client = Client(base_url='')

Base URL

If base_url is not provided, it defaults to
It's recommended to pass in the base_url parameter, even in production as Binance provides alternative URLs in case of performance issues:


Optional parameters

PEP8 suggests lowercase with words separated by underscores, but for this connector, the methods' optional parameters should follow their exact naming as in the API documentation.

# Recognised parameter name
response = client.cancel_oco_order('BTCUSDT', orderListId=1)

# Unrecognised parameter name
response = client.cancel_oco_order('BTCUSDT', order_list_id=1)

RecvWindow parameter

Additional parameter recvWindow is available for endpoints requiring signature.
It defaults to 5000 (milliseconds) and can be any value lower than 60000(milliseconds). Anything beyond the limit will result in an error response from Binance server.

from import Spot as Client

client = Client(api_key, api_secret)
response = client.get_order('BTCUSDT', orderId=11, recvWindow=10000)


timeout is available to be assigned with the number of seconds you find most appropriate to wait for a server response.
Please remember the value as it won't be shown in error message no bytes have been received on the underlying socket for timeout seconds.
By default, timeout is None. Hence, requests do not time out.

from import Spot as Client

client= Client(timeout=1)


Proxy is supported.

from import Spot as Client

proxies = { 'https': '' }

client= Client(proxies=proxies)

Response Metadata

The Binance API server provides weight usages in the headers of each response. You can display them by initializing the client with show_limit_usage=True:

from import Spot as Client

client = Client(show_limit_usage=True)


{'data': {'serverTime': 1587990847650}, 'limit_usage': {'x-mbx-used-weight': '31', 'x-mbx-used-weight-1m': '31'}}

You can also display full response metadata to help in debugging:

client = Client(show_header=True)


{'data': {'serverTime': 1587990847650}, 'header': {'Context-Type': 'application/json;charset=utf-8', ...}}

If ClientError is received, it'll display full response meta information.

Display logs

Setting the log level to DEBUG will log the request URL, payload and response text.


There are 2 types of error returned from the library:

  • binance.error.ClientError
    • This is thrown when server returns 4XX, it's an issue from client side.
    • It has 5 properties:
      • status_code - HTTP status code
      • error_code - Server's error code, e.g. -1102
      • error_message - Server's error message, e.g. Unknown order sent.
      • header - Full response header.
      • error_data* - Additional detailed data which supplements the error_message.
        • *Only applicable on select endpoints, eg. cancelReplace
  • binance.error.ServerError
    • This is thrown when server returns 5XX, it's an issue from server side.


Connector v3

WebSocket can be established through either of the following types of connections:

  • WebSocket API (
  • WebSocket Stream (
# WebSocket API Client
from import SpotWebsocketAPIClient

def message_handler(_, message):

my_client = SpotWebsocketAPIClient(on_message=message_handler)

my_client.ticker(symbol="BNBBUSD", type="FULL")

time.sleep(5)"closing ws connection")
# WebSocket Stream Client
from import SpotWebsocketStreamClient

def message_handler(_, message):

my_client = SpotWebsocketStreamClient(on_message=message_handler)

# Subscribe to a single symbol stream
time.sleep(5)"closing ws connection")


Proxy is supported for both WebSocket API and WebSocket Stream.

To use it, pass in the proxies parameter when initializing the client.

The format of the proxies parameter is the same as the one used in the Spot RESTful API.

It consists on a dictionary with the following format, where the key is the type of the proxy and the value is the proxy URL:

For websockets, the proxy type is http.

proxies = { 'http': '' }

You can also use authentication for the proxy by adding the username and password parameters to the proxy URL:

proxies = { 'http': 'http://username:password@host:port' }
# WebSocket API Client
from import SpotWebsocketAPIClient

def message_handler(_, message):

proxies = { 'http': '' }

my_client = SpotWebsocketAPIClient(on_message=message_handler, proxies=proxies)

my_client.ticker(symbol="BNBBUSD", type="FULL")

time.sleep(5)"closing ws connection")
# WebSocket Stream Client
from import SpotWebsocketStreamClient

def message_handler(_, message):

proxies = { 'http': '' }

my_client = SpotWebsocketStreamClient(on_message=message_handler, proxies=proxies)

# Subscribe to a single symbol stream
time.sleep(5)"closing ws connection")

Request Id

Client can assign a request id to each request. The request id will be returned in the response message. Not mandatory in the library, it generates a uuid format string if not provided.

# id provided by client

# library will generate a random uuid string

Combined Streams

  • If you set is_combined to True, "/stream/" will be appended to the baseURL to allow for Combining streams.
  • is_combined defaults to False and "/ws/" (raw streams) will be appended to the baseURL.

More websocket examples are available in the examples folder.

Example file "examples/websocket_api/" demonstrates how Websocket API and Websocket Stream can be used together.

Connector v1 and v2

from import SpotWebsocketClient as WebsocketClient

def message_handler(message):

ws_client = WebsocketClient()


# Combine selected streams
    stream=['bnbusdt@bookTicker', 'ethusdt@bookTicker'],



Once connected, the websocket server sends a ping frame every 3 minutes and requires a response pong frame back within a 10 minutes period. This package handles the pong responses automatically.


from import SpotWebsocketClient as WebsocketClient

ws_client = WebsocketClient(stream_url='wss://')

Test Case

# In case packages are not installed yet
pip install -r requirements/requirements-test.txt



Futures and Vanilla Options APIs are not supported:

  • /fapi/*
  • /dapi/*
  • /vapi/*
  • Associated Websocket Market and User Data Streams


Contributions are welcome.
If you've found a bug within this project, please open an issue to discuss what you would like to change.
If it's an issue with the API, please open a topic at Binance Developer Community