Skip to main content

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

Project description

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
  • Inclusion of test cases and examples
  • Customizable base URL, request timeout and HTTP proxy
  • Response metadata can be displayed

Installation

pip install binance-connector

Documentation

https://binance-connector.readthedocs.io

RESTful APIs

Usage examples:

from binance.spot import Spot 

client = Spot()
print(client.time())

client = Spot(key='<api_key>', secret='<api_secret>')

# Get account information
print(client.account())

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

response = client.new_order(**params)
print(response)

Please find examples folder to check for more endpoints.

Testnet

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

To use testnet:

from binance.spot import Spot as Client

client = Client(base_url='https://testnet.binance.vision')
print(client.time())

Base URL

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

  • https://api1.binance.com
  • https://api2.binance.com
  • https://api3.binance.com

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 binance.spot import Spot as Client

client = Client(key, secret)
response = client.get_order('BTCUSDT', orderId=11, recvWindow=10000)

Timeout

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 binance.spot import Spot as Client

client= Client(timeout=1)

Proxy

Proxy is supported.

from binance.spot import Spot as Client

proxies = { 'https': 'http://1.2.3.4:8080' }

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 binance.spot import Spot as Client

client = Client(show_limit_usage=True)
print(client.time())

returns:

{'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)
print(client.time())

returns:

{'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.

Error

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 4 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.
  • binance.error.ServerError
    • This is thrown when server returns 5XX, it's an issue from server side.

Websocket

from binance.websocket.spot.websocket_client import SpotWebsocketClient as WebsocketClient

def message_handler(message):
    print(message)

ws_client = WebsocketClient()
ws_client.start()

ws_client.mini_ticker(
    symbol='bnbusdt',
    id=1,
    callback=message_handler,
)

# Combine selected streams
ws_client.instant_subscribe(
    stream=['bnbusdt@bookTicker', 'ethusdt@bookTicker'],
    callback=message_handler,
)

ws_client.stop()

More websocket examples are available in the examples folder

Heartbeat

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.

Testnet

from binance.websocket.spot.websocket_client import SpotWebsocketClient as WebsocketClient

ws_client = WebsocketClient(stream_url='wss://testnet.binance.vision')

Test Case

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

pytest

Limitation

Futures and Vanilla Options APIs are not supported:

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

Contributing

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

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

aisling-connector-1.10.0.tar.gz (32.6 kB view details)

Uploaded Source

Built Distribution

aisling_connector-1.10.0-py3-none-any.whl (43.2 kB view details)

Uploaded Python 3

File details

Details for the file aisling-connector-1.10.0.tar.gz.

File metadata

  • Download URL: aisling-connector-1.10.0.tar.gz
  • Upload date:
  • Size: 32.6 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/3.8.0 pkginfo/1.8.2 readme-renderer/32.0 requests/2.27.1 requests-toolbelt/0.9.1 urllib3/1.26.8 tqdm/4.62.3 importlib-metadata/4.11.1 keyring/23.5.0 rfc3986/2.0.0 colorama/0.4.4 CPython/3.9.10

File hashes

Hashes for aisling-connector-1.10.0.tar.gz
Algorithm Hash digest
SHA256 197fd31392093a914cc1f625dbd9591941da0652a4ef8b38e07b2775646ce434
MD5 dc0513c09008a661684520a27cec88fa
BLAKE2b-256 c6de2b76a4be9683c54850ff9aaa0370adf4e45eed3c01f034b8a73260721a65

See more details on using hashes here.

File details

Details for the file aisling_connector-1.10.0-py3-none-any.whl.

File metadata

  • Download URL: aisling_connector-1.10.0-py3-none-any.whl
  • Upload date:
  • Size: 43.2 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/3.8.0 pkginfo/1.8.2 readme-renderer/32.0 requests/2.27.1 requests-toolbelt/0.9.1 urllib3/1.26.8 tqdm/4.62.3 importlib-metadata/4.11.1 keyring/23.5.0 rfc3986/2.0.0 colorama/0.4.4 CPython/3.9.10

File hashes

Hashes for aisling_connector-1.10.0-py3-none-any.whl
Algorithm Hash digest
SHA256 69b9eaa50d5d2ff5ee31838f8cbdbef1236f977601d15f15b87d9322740b506c
MD5 ad1ea220eaeffb32a4f9b9c432a70e5f
BLAKE2b-256 b0552c1ae8af889e57e4fc93aa4b64f515dfc74a22991de4445a3f8faba2f3ac

See more details on using hashes here.

Supported by

AWS AWS Cloud computing and Security Sponsor Datadog Datadog Monitoring Fastly Fastly CDN Google Google Download Analytics Microsoft Microsoft PSF Sponsor Pingdom Pingdom Monitoring Sentry Sentry Error logging StatusPage StatusPage Status page