unicorn_binance_websocket_api package

Submodules

unicorn_binance_websocket_api.unicorn_binance_websocket_api_connection module

class unicorn_binance_websocket_api.unicorn_binance_websocket_api_connection.BinanceWebSocketApiConnection(handler_binance_websocket_api_manager, stream_id, channels, markets)

Bases: object

async close()
async receive()
async send(data)

unicorn_binance_websocket_api.unicorn_binance_websocket_api_manager module

class unicorn_binance_websocket_api.unicorn_binance_websocket_api_manager.BinanceWebSocketApiManager(process_stream_data=False, exchange='binance.com', warn_on_update=True, throw_exception_if_unrepairable=False, restart_timeout=6)

Bases: threading.Thread

A python API to use the Binance Websocket API`s (com, com-margin, com-futures, jersey, us, dex/chain+testnet) in a easy, fast, flexible, robust and fully-featured way.

This library supports two different kind of websocket endpoints:

  • CEX (Centralized exchange): binance.com, binance.je, binance.us, jex.com

  • DEX (Decentralized exchange): binance.org

Binance.com websocket API documentation:

Binance.je websocket API documentation:

Binance.us websocket API documentation:

Jex.com websocket API documentation:

Binance.org websocket API documentation:

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! (How to read from stream_buffer: https://oliver-zehentleitner.github.io/unicorn-binance-websocket-api/README.html#and-4-more-lines-to-print-the-receives)

  • exchange (str) – Select binance.com, binance.com-margin, binance.com-futures, binance.je, binance.us, jex.com, binance.org or binance.org-testnet (default: binance.com)

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

  • throw_exception_if_unrepairable (bool) – set to True to activate exceptions if a crashed stream is unrepairable (invalid API key, exceeded subscription limit) or an unknown exchange is used

  • restart_timeout (int) – A stream restart must be successful within this time, otherwise a new restart will be initialized. Default is 6 seconds.

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

add_total_received_bytes(size)

Add received bytes to the total received bytes statistic

Parameters

size (int) – int value of added bytes

create_payload(stream_id, method, channels=False, markets=False)

Create the payload for subscriptions

Parameters
  • stream_id (uuid) – provide a stream_id

  • method (str) – SUBSCRIBE or UNSUBSCRIBE

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

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

Returns

payload (list) or False

create_stream(channels, markets, stream_label=None)

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 limit of 1024 subscriptions per stream. https://github.com/binance-exchange/binance-official-api-docs/blob/5fccfd572db2f530e25e302c02be5dec12759cf9/CHANGELOG.md#2020-04-23

Create !userData streams as single streams, because its using a different endpoint and can not get combined with other streams in a multiplexed stream!

Example CEX:

Set api_key and api_secret:

binance_websocket_api_manager.set_private_api_config(binance_api_key, binance_api_secret)

Then start the stream:

binance_websocket_api_manager.create_stream(["arr"], ["!userData"])

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 - dont 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, tuple, list, set) – provide the channels you wish to stream

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

  • stream_label (str) – provide a stream_label to identify the stream

Returns

stream_id or ‘False’

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

Create a websocket URI

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

  • markets (str, tuple, list, set) – provide the markets 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 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 (uuid) – id of a stream

Returns

bool

fill_up_space_centered(demand_of_chars, string, filling=' ')

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

fill_up_space_left(demand_of_chars, string, filling=' ')

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

fill_up_space_right(demand_of_chars, string, filling=' ')

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

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

Returns

int

get_exchange()

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

Returns

str

static get_human_bytesize(bytes, suffix='')

Convert the bytes to something readable

Parameters
  • bytes (int) – amount of bytes

  • suffix (str) – add a string after

Returns

static get_human_uptime(uptime)

Convert a timespan of seconds into hours, days, …

Parameters

uptime (int) – Uptime in seconds

Returns

get_keep_max_received_last_second_entries()

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

Returns

int

static get_latest_release_info()

Get infos about the latest available release

Returns

dict or False

static 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_limit_of_subscriptions_per_stream()

Get the number of allowed active subscriptions per stream (limit of binance API) :return: int

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_monitoring_status_icinga(check_command_version=False, warn_on_update=True)

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
Returns

dict (text, time, return_code)

get_monitoring_status_plain(check_command_version=False, warn_on_update=True)

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
Returns

dict

get_most_receives_per_second()

Get the highest total receives per second value

Returns

int

get_number_of_all_subscriptions()

Get the amount of all stream subscriptions

Returns

inf

get_number_of_free_subscription_slots(stream_id)

Get the number of free subscription slots (max allowed subscriptions - subscriptions) of a specific stream :return: int

get_number_of_streams_in_stream_list()

Get the number of streams that are stored in the stream_list

Returns

int

get_number_of_subscriptions(stream_id)

Get the number of subscriptions of a specific stream

Returns

int

get_process_usage_cpu()

Get the used cpu power of this process

Returns

int

get_process_usage_memory()

Get the used memory of this process

Returns

str

get_process_usage_threads()

Get the amount of threads that this process is using

Returns

int

get_reconnects()

Get the number of total reconnects

Returns

int

get_request_id()

Get a unique request ID

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 estimation of the stream_buffer

Returns

int

get_stream_buffer_length()

Get the current number of items in the stream_buffer

Returns

int

get_stream_id_by_label(stream_label=False)

Get the stream_id of a specific stream by stream label

Parameters

stream_label (str) – stream_label of the stream you search

Returns

str or False

get_stream_info(stream_id)

Get all infos about a specific stream

Parameters

stream_id (uuid) – id of a stream

Returns

set

get_stream_label(stream_id=False)

Get the stream_label of a specific stream

Parameters

stream_id (uuid) – id of a stream

Returns

str or False

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_stream_subscriptions(stream_id, request_id=False)

Listing subscriptions

This function is supported by CEX endpoints only!

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

Parameters
  • stream_id (uuid) – id of a stream

  • request_id (int) – id to use for the request

Returns

bool

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

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

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

Returns

int

static help()

Help in iPython

increase_processed_receives_statistic(stream_id)

Add the number of processed receives

Parameters

stream_id (uuid) – id of a stream

increase_received_bytes_per_second(stream_id, size)

Add the amount of received bytes per second

Parameters
  • stream_id (uuid) – id of a stream

  • size (int) – amount of bytes to add

increase_reconnect_counter(stream_id)

Increase reconnect counter

Parameters

stream_id (uuid) – id of a stream

increase_transmitted_counter(stream_id)

Increase the counter of transmitted payloads :param stream_id: id of a stream :type stream_id: uuid

is_exchange_type(exchange_type=False)

Check the exchange type!

Parameters

exchange_type (str) – Valid types are dex and cex!

Returns

bool

is_manager_stopping()

Returns True if the manager has a stop request, ‘False’ if not.

Returns

bool

is_stop_as_crash_request(stream_id)

Has a specific stream a stop_as_crash_request?

Parameters

stream_id (uuid) – id of a stream

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(check_command_version=False)

Is a new release of check_unicorn_monitoring_api available?

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

bool

print_summary(add_string='', disable_print=False)

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()

print_summary_to_png(print_summary_export_path, hight_per_row=12.5)

Create a PNG image file with the console output of print_summary()

Parameters
Returns

bool

static remove_ansi_escape_codes(text)

Remove ansi excape codes from the text string!

Parameters

text – str

Returns

replace_stream(stream_id, new_channels, new_markets)

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 (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

run()

This method overloads threading.run() and starts management threads

set_heartbeat(stream_id)

Set heartbeat for a specific thread (should only be done by the stream itself)

set_keep_max_received_last_second_entries(number_of_max_entries)

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

Parameters

binance_dex_user_address (str) – Binance DEX user address

set_restart_request(stream_id)

Set a restart request for a specific stream

Parameters

stream_id (uuid) – id of the old stream

set_stream_label(stream_id, stream_label=None)

Set a stream_label by stream_id

Parameters
  • stream_id (uuid) – id of the stream

  • stream_label (str) – stream_label to set

split_payload(params, method, max_items_per_request=350)

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 (str) – params of subscribe payload

  • method (str) – SUBSCRIBE or UNSUBSCRIBE

  • max_items_per_request – max size for params, if more it gets splitted

Returns

list or False

start_monitoring_api(host='127.0.0.1', port=64201, warn_on_update=True)

Start the monitoring API server

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_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

stop_stream_as_crash(stream_id)

Stop a specific stream with ‘crashed’ status

Parameters

stream_id (uuid) – id of a stream

Returns

bool

stream_is_crashing(stream_id, error_msg=False)

If a stream can not heal itself in cause of wrong parameter (wrong market, channel type) it calls this method

Parameters
  • stream_id (uuid) – id of a stream

  • error_msg (str) – Error msg to add to the stream status!

stream_is_stopping(stream_id)

Streams report with this call their shutdowns

Parameters

stream_id (uuid) – id of a stream

Returns

subscribe_to_stream(stream_id, channels=[], markets=[])

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: https://oliver-zehentleitner.github.io/unicorn-binance-websocket-api/unicorn_binance_websocket_api.html#unicorn_binance_websocket_api.unicorn_binance_websocket_api_manager.BinanceWebSocketApiManager.create_stream

Parameters
  • stream_id (uuid) – id of a stream

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

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

Returns

bool

unsubscribe_from_stream(stream_id, channels=[], markets=[])

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: https://oliver-zehentleitner.github.io/unicorn-binance-websocket-api/unicorn_binance_websocket_api.html#unicorn_binance_websocket_api.unicorn_binance_websocket_api_manager.BinanceWebSocketApiManager.create_stream

Parameters
  • stream_id (uuid) – id of a stream

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

  • markets (str, tuple, list, set) – provide the markets you wish to 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

unicorn_binance_websocket_api.unicorn_binance_websocket_api_restclient module

class unicorn_binance_websocket_api.unicorn_binance_websocket_api_restclient.BinanceWebSocketApiRestclient(exchange, binance_api_key, binance_api_secret, unicorn_binance_websocket_api_version, binance_api_status)

Bases: object

delete_listen_key(listen_key)

Delete a specific listen key

Parameters

listen_key (str) – the listenkey you want to delete

Returns

the response

Return type

str or False

get_listen_key()

Request a valid listen_key from binance

Returns

listen_key

Return type

str or False

keepalive_listen_key(listen_key)

Ping a listenkey to keep it alive

Parameters

listen_key (str) – the listenkey you want to keepalive

Returns

the response

Return type

str or False

unicorn_binance_websocket_api.unicorn_binance_websocket_api_restserver module

class unicorn_binance_websocket_api.unicorn_binance_websocket_api_restserver.BinanceWebSocketApiRestServer(handler_binance_websocket_api_manager, warn_on_update=True)

Bases: flask_restful.Resource

Provide a REST API server

Description: https://github.com/oliver-zehentleitner/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)

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 = {'GET'}

unicorn_binance_websocket_api.unicorn_binance_websocket_api_socket module

class unicorn_binance_websocket_api.unicorn_binance_websocket_api_socket.BinanceWebSocketApiSocket(handler_binance_websocket_api_manager, stream_id, channels, markets)

Bases: object

async start_socket()

Module contents