UNICORN Binance WebSocket API

A python API to use the Binance Websocket API in a easy, fast, flexible, robust and fully-featured way.

Create a multiplex websocket connection to Binance with just 3 lines of code:

from unicorn_binance_websocket_api.unicorn_binance_websocket_api_manager import BinanceWebSocketApiManager

binance_websocket_api_manager = BinanceWebSocketApiManager(exchange="binance.com")
binance_websocket_api_manager.create_stream(['trade', 'kline_1m'], ['btcusdt', 'bnbbtc', 'ethbtc'])

And 2 more lines to print them:

while True:
oldest_stream_data_from_stream_buffer = binance_websocket_api_manager.pop_stream_data_from_stream_buffer()
if oldest_stream_data_from_stream_buffer:
print(oldest_stream_data_from_stream_buffer)

Thats it!

Description

The python module UNICORN Binance WebSocket API provides an API to the Binance Websocket API`s of Binance , Binance Jersey, Binance DEX and Binance DEX Testnet and supports the streaming of public streams like trade, kline, ticker, depth and blockheight, but also the private userData streams which needs to be used with a valid api_key and api_secret from the Binance Exchange www.binance.com or www.binance.je - for the DEX you need a user address from www.binance.org or testnet.binance.org and you can get funds for the testnet.

The module requires python 3.5.3 or above, as it depends on pythons latest asyncio features for asynchronous/concurrent processing. The current dependencies are listed here.

Be aware that the Binance websocket API just offers to receive data. If you would like to set orders, withdraws and so on, you have to use the Binance Rest API (com, je, org) in combination.

What are the benefits of the UNICORN Binance WebSocket API?

  • Fully managed websockets and 100% auto-reconnect!
  • Supported exchanges:
    • Binance BinanceWebSocketApiManager(exchange="binance.com")
    • Binance Jersey BinanceWebSocketApiManager(exchange="binance.je")
    • Binance DEX BinanceWebSocketApiManager(exchange="binance.org")
    • Binance DEX testnet BinanceWebSocketApiManager(exchange="binance.org-testnet")
  • Streams are processing asynchronous/concurrent (python asyncio) and each stream is started in a separate thread.
  • No use of the twisted module, so you can use this lib in a daemonized application (compatible with python-daemon).
  • If you can not store your data in cause of a temporary technical issue, you can kick back the data to the stream_buffer which stores the receives in the RAM till you are able to process the data in the normal way again.
  • Compatible with UnicornFy to convert received raw data from crypto API endpoints into well-formed python dictionaries.
  • Helpful management features like get_binance_api_status(), get_stream_info(), get_stream_list(), get_stream_statistic(), is_websocket_uri_length_valid(), replace_stream(), wait_till_stream_has_started(), get_current_receiving_speed() and many more, explore them here.
  • Monitoring API service and a check_command for ICINGA/Nagios icinga2-demo
  • Excessively tested on Linux, Mac and Windows

Read the Howto: UNICORN Binance WebSocket API for installation instructions and a guide on how to use it.

UNICORN Binance WebSocket API is available on PyPI: https://pypi.org/project/unicorn-binance-websocket-api/

So you can make the package available on your system with `pip install unicorn-binance-websocket-api`!

 

UNICORN Binance WebSocket API documentation

class unicorn_binance_websocket_api_manager.BinanceWebSocketApiManager(process_stream_data=False, exchange="binance.com")

A python API to handle the Binance websocket API

Binance.com websocket API documentation:
https://github.com/binance-exchange/binance-official-api-docs/blob/master/web-socket-streams.md
https://github.com/binance-exchange/binance-official-api-docs/blob/master/user-data-stream.md
Binance.je websocket API documentation:
https://github.com/binance-jersey/binance-official-api-docs/blob/master/web-socket-streams.md
https://github.com/binance-jersey/binance-official-api-docs/blob/master/user-data-stream.md
Binance.org websocket API documentation:
https://docs.binance.org/api-reference/dex-api/ws-connection.html

Parameters
  • process_stream_data (function) – Provide a function/method to process the received webstream data. The function will be called with one variable like `process_stream_data(data)` where data` cointains the raw_stream_data. If not provided, the raw_stream_data will get stored in the stream_buffer.

  • exchange (str) – Select binance.com or binance.je (default: binance.com).

add_to_stream_buffer(stream_data)

Kick back data to the stream_buffer

If it is not possible to process received stream data (for example, the database is restarting, so its 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

create_stream(channels, markets)

Create a websocket stream

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

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

binance.com and binance.je:
channel "trade" with `markets = {'bnbbtc', 'ethbtc', 'btcusdt'}`
channel "aggTrade" with `markets = {'bnbbtc', 'ethbtc', 'btcusdt'}`
channel "kline_<interval>" (1m, 3m, 5m, 15m, 30m, 1h, 2h, 4h, 6h, 8h, 12h, 1d, 3d, 1w, 1M)
with `markets = {'bnbbtc', 'ethbtc', 'btcusdt'}`
channel "miniTicker" with `markets = {'bnbbtc', 'ethbtc', 'btcusdt'}`
channel "ticker" with `markets = {'bnbbtc', 'ethbtc', 'btcusdt'}`
channel "depth<level>" (5, 10, 20) with `markets = {'bnbbtc', 'ethbtc', 'btcusdt'}`
channel "depth" with `markets = {'bnbbtc', 'ethbtc', 'btcusdt'}`
channel "arr" with `"!ticker"`or "!miniTicker" or "!userData"
binance.org and binance.org-testnet:
channel "trades" with `markets = {'AWC-986_BNB', 'COVA-218_BNB', 'BTCB-1DE_USDSB-1AC'}`
channel "kline_<interval>" (1m, 3m, 5m, 15m, 30m, 1h, 2h, 4h, 6h, 8h, 12h, 1d, 3d, 1w, 1M)
with `markets = {'AWC-986_BNB', 'COVA-218_BNB', 'BTCB-1DE_USDSB-1AC'}`
channel "miniTicker" with `markets = {'AWC-986_BNB', 'COVA-218_BNB', 'BTCB-1DE_USDSB-1AC'}`
channel "ticker" with `markets = {'AWC-986_BNB', 'COVA-218_BNB', 'BTCB-1DE_USDSB-1AC'}`
channel "marketDepth" with `markets = {'bnbbtc', 'ethbtc', 'btcusdt'}`
channel "orders" or "accounts" or transfers" with `markets = userAddress`
Returns

stream_id or False

create_websocket_uri(channels, markets, stream_id, api_key, api_secret)

Create a websocket URI

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

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

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

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

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

Returns

str or False

delete_listen_key_by_stream_id(stream_id)

Delete a binance listen_key from a specific !userData stream

Parameters

stream_id (uuid) – id of a !userData stream

delete_stream_from_stream_list(stream_id)

Delete a stream from the stream_list

Even if a stream crashes or gets 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 (uuid) – id of a stream

Returns

bool

get_active_stream_list()

Get a list of all active streams

Returns

set

get_all_receives_last_second()

Get the number of all receives of the last second

Returns

int

get_binance_api_status()

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

Returns

dict

get_current_receiving_speed(stream_id)

Get the receiving speed of the last second in Bytes

Parameters

stream_id (uuid) – id of a stream

Returns

int

get_exchange()

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

Returns

str

get_keep_max_received_last_second_entries()

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

Returns

int

get_monitoring_status_icinga(warn_on_update)

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

status: OK, WARNING, CRITICAL

perfdata:
  • average_receives_per_second
  • current_receiving_speed_per_second
  • total_received_length
  • total_received_size
  • stream_buffer_size
  • stream_buffer_length
  • reconnects
  • uptime_days
Parameters
  • warn_on_update (bool) – set to `False` to disable the update warning

Returns

dict (text, time, return_code)

get_monitoring_status_plain(warn_on_update)

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
  • warn_on_update (bool) – set to `False` to disable the update warning

Returns

dict

get_latest_release_info()

Get infos about the latest available release

Returns

dict or False

get_latest_release_info_check_command()

Get infos about the latest available `check_unicorn_monitoring_api` release

Returns

dict or False

get_latest_version()

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

Returns

str or False

get_latest_version_check_command()

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

Returns

str or False

get_listen_key_from_restclient(stream_id, api_key, api_secret)

Get a new or cached (<30m) listen_key

Parameters
  • stream_id (uuid) – provide a stream_id

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

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

Returns

str or False

get_most_receives_per_second()

Get the highest total receives per second value

Returns

int

get_number_of_streams_in_stream_list()

Get the number of streams that are stored in the stream_list

Returns

int

get_reconnects()

Get the number of total reconnects

Returns

int

get_start_time()

Get the start_time of the BinanceWebSocketApiManager instance

Returns

timestamp

get_stream_buffer_byte_size()

Get the current byte size of the stream_buffer

Returns

int

get_stream_buffer_length()

Get the current number of items in the stream_buffer

Returns

int

get_stream_info(stream_id)

Get infos about a specific stream

Parameters

stream_id (uuid) – id of a stream

Returns

set

get_stream_list()

Get a list of all streams

Returns

set

get_stream_receives_last_second(stream_id)

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

Parameters

stream_id (uuid) – id of a stream

Returns

int

get_stream_statistic(stream_id)

Get the statistic of a specific stream

Parameters

stream_id (uuid) – id of a stream

Returns

set

get_total_received_bytes()

Get number of total received bytes

Returns

int

get_total_receives()

Get the number of total receives

Returns

int

get_version()

Get the package/module version

Returns

str

get_websocket_uri_length(channels, markets)

Get the length of the generated websocket URI

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

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

Returns

int

is_manager_stopping()

Returns `True` if the manager has a stop request, 'False' if not.

Returns

bool

is_stop_request(stream_id)

Has a specific stream a stop_request?

Parameters

stream_id (uuid) – id of a stream

Returns

bool

is_update_availabe()

Is a new release of this package available?

Returns

bool

is_update_availabe_check_command()

Is a new release of `check_unicorn_monitoring_api` available?

Returns

bool

is_websocket_uri_length_valid()

Is the websocket URI length valid?

Binance DEX is using the subscribe method, so this function must not get used with them and will always return`False`!

A test with https://github.com/unicorn-data-analysis/unicorn-binance-websocket-api/blob/master/tools/test_max_websocket_uri_length.py indicates that the allowed max length of an URI to binance websocket server is 8004 characters.

Returns

bool

pop_stream_data_from_stream_buffer()

Get oldest entry from stream_buffer and remove from stack (FIFO stack)

Returns

raw_stream_data (set) or False

print_stream_info(stream_id, add_string)

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

Parameters

stream_id (uuid) – id of a stream

add_string (str) – text to add to the output

Returns

print_summary(add_string)

Print an overview of all streams

Parameters

add_string (str) – text to add to the output

Returns

replace_stream(stream_id, new_channels, new_markets)

Replace a stream

If you want to start a stream with a new config, it is 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 (uuid) – 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

Returns

new stream_id

restart_stream(stream_id)

Restart a specific stream

Parameters

stream_id (uuid) – id of a stream

Returns

stream_id

set_private_api_config(binance_api_key, binance_api_secret)

Set binance_api_key and binance_api_secret

This settings are needed to acquire a listenKey from Binance to establish a userData stream

Parameters
  • binance_api_key (str) – The Binance API key

  • binance_api_secret (str) – The Binance API secret

set_private_dex_config(binance_dex_user_address)

Set binance_dex_user_address

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

start_monitoring_api(host, port, warn_on_update)

Start the monitorint API server

Parameters
  • host (str) – host name or ip address (default: 127.0.0.1)

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

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

stop_manager_with_all_streams()

Stop the BinanceWebSocketApiManager with all streams and management threads

stop_monitoring_api()

Stop the monitoring API service

stop_stream(stream_id)

Stop a specific stream

Parameters

stream_id (uuid) – id of a stream

Returns

bool

wait_till_stream_has_started(stream_id)

Returns True as soon a specific stream has started

Parameters

stream_id (uuid) – id of a stream

Returns

True

wait_till_stream_has_stopped(stream_id)

Returns True as soon a specific stream has stopped itself

Parameters

stream_id (uuid) – id of a stream

Returns

True