unicorn_binance_websocket_api package¶
Submodules¶
unicorn_binance_websocket_api.connection module¶
unicorn_binance_websocket_api.exceptions module¶
- exception unicorn_binance_websocket_api.exceptions.Socks5ProxyConnectionError¶
Bases:
Exception
Exception if the manager class is not able to establish a connection to the socks5 proxy.
- exception unicorn_binance_websocket_api.exceptions.StreamRecoveryError¶
Bases:
Exception
Exception for non-recoverable streams.
- exception unicorn_binance_websocket_api.exceptions.UnknownExchange¶
Bases:
Exception
Exception if the manager class is started with an unkown exchange.
unicorn_binance_websocket_api.manager module¶
- class 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, show_secrets_in_logs=False, output_default: Literal['dict', 'raw_data', 'UnicornFy'] | None = 'raw_data', enable_stream_signal_buffer=False, disable_colorama=False, stream_buffer_maxlen=None, process_stream_signals=False, close_timeout_default: int = 1, ping_interval_default: int = 5, ping_timeout_default: int = 10, high_performance=False, debug=False, restful_base_uri: str | None = None, restful_path_userdata: str | None = None, websocket_base_uri: str | None = None, max_subscriptions_per_stream: int | None = None, exchange_type: Literal['cex', 'dex'] | None = None, socks5_proxy_server: str | None = None, socks5_proxy_ssl_verification: bool | None = True)¶
Bases:
Thread
An unofficial Python API to use the Binance Websocket API`s (com+testnet, com-margin+testnet, com-isolated_margin+testnet, com-futures+testnet, us, jex, 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.vision, binance.je, binance.us, trbinance.com, jex.com
DEX (Decentralized exchange): binance.org
Binance.com websocket API documentation:
Binance.vision (Testnet) websocket API documentation:
Binance.us websocket API documentation:
TRBinance.com 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 (callback). The function will be called instead of add_to_stream_buffer() like process_stream_data(stream_data, stream_buffer_name) where stream_data cointains the raw_stream_data. If not provided, the raw stream_data will get stored in the stream_buffer or provided to a specific callback function of create_stream()! How to read from stream_buffer!
exchange (str) – Select binance.com, binance.com-testnet, binance.com-margin, binance.com-margin-testnet, binance.com-isolated_margin, binance.com-isolated_margin-testnet, binance.com-futures, binance.com-futures-testnet, binance.com-coin_futures, binance.us, trbinance.com, jex.com, binance.org, 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.
show_secrets_in_logs (bool) – set to True to show secrets like listen_key, api_key or api_secret in log file (default=False)
output_default (str) – set to “dict” to convert the received raw data to a python dict, set to “UnicornFy” to convert with UnicornFy - otherwise with the default setting “raw_data” the output remains unchanged and gets delivered as received from the endpoints. Change this for a specific stream with the output parameter of create_stream() and replace_stream()
enable_stream_signal_buffer (bool) – set to True to enable the stream_signal_buffer and receive information about disconnects and reconnects to manage a restore of the lost data during the interruption or to recognize your bot got blind.
disable_colorama (bool) – set to True to disable the use of colorama
stream_buffer_maxlen (int or None) – Set a max len for the generic stream_buffer. This parameter can also be used within create_stream() for a specific stream_buffer.
process_stream_signals (function) – Provide a function/method to process the received stream signals. The function is running inside an asyncio loop and will be called instead of add_to_stream_signal_buffer() like process_stream_data(signal_type=False, stream_id=False, data_record=False).
close_timeout_default (int) – The close_timeout parameter defines a maximum wait time in seconds for completing the closing handshake and terminating the TCP connection. This parameter is passed through to the websockets.client.connect()
ping_interval_default (int) –
Once the connection is open, a Ping frame is sent every ping_interval seconds. This serves as a keepalive. It helps keeping the connection open, especially in the presence of proxies with short timeouts on inactive connections. Set ping_interval to None to disable this behavior. This parameter is passed through to the websockets.client.connect()
ping_timeout_default (int) –
If the corresponding Pong frame isn’t received within ping_timeout seconds, the connection is considered unusable and is closed with code 1011. This ensures that the remote endpoint remains responsive. Set ping_timeout to None to disable this behavior. This parameter is passed through to the websockets.client.connect()
high_performance (bool) – Set to True makes create_stream() a non-blocking function
debug (bool) – If True the lib adds additional information to logging outputs
restful_base_uri (str) – Override restful_base_uri. Example: https://127.0.0.1
restful_path_userdata (str) – Override restful_path_userdata. Example: api/v3/userDataStream
websocket_base_uri (str) – Override websocket_base_uri. Example: ws://127.0.0.1:8765/
max_subscriptions_per_stream (int) – Override the max_subscriptions_per_stream value. Example: 1024
exchange_type (str) – Override the exchange type. Valid options are: ‘cex’, ‘dex’
socks5_proxy_server (str) – Set this to activate the usage of a socks5 proxy. Example: ‘127.0.0.1:9050’
socks5_proxy_ssl_verification (bool) – Set to False to disable SSL server verification. Default is True.
- add_to_ringbuffer_error(error)¶
Add received error messages from websocket endpoints to the error ringbuffer
- Parameters:
error (string) – The data to add.
- Returns:
bool
- add_to_ringbuffer_result(result)¶
Add received result messages from websocket endpoints to the result ringbuffer
- Parameters:
result (string) – The data to add.
- Returns:
bool
- add_to_stream_buffer(stream_data, stream_buffer_name=False)¶
Kick back data to the stream_buffer
If it is not possible to process received stream data (for example, the database is restarting, so it’s 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
stream_buffer_name (bool or str) – If False the data is going to get written to the default stream_buffer, set to True to read the data via pop_stream_data_from_stream_buffer(stream_id) or provide a string to create and use a shared stream_buffer and read it via pop_stream_data_from_stream_buffer(‘string’).
- Returns:
bool
- add_to_stream_signal_buffer(signal_type=False, stream_id=False, data_record=False)¶
Add signals about a stream to the stream_signal_buffer
- Parameters:
signal_type (str) – “CONNECT”, “DISCONNECT” or “FIRST_RECEIVED_DATA”
stream_id (str) – id of a stream
data_record (str or dict) – The last or first received data record
- Returns:
bool
- add_total_received_bytes(size)¶
Add received bytes to the total received bytes statistic
- Parameters:
size (int) – int value of added bytes
- clear_stream_buffer(stream_buffer_name=False)¶
Clear the stream_buffer
- Parameters:
stream_buffer_name (bool or str) – False to read from generic stream_buffer, the stream_id if you used True in create_stream() or the string name of a shared stream_buffer.
- Returns:
bool
- create_payload(stream_id, method, channels=False, markets=False)¶
Create the payload for subscriptions
- Parameters:
stream_id (str) – 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, stream_buffer_name=False, api_key=False, api_secret=False, symbols=False, output=False, ping_interval=None, ping_timeout=None, close_timeout=None, stream_buffer_maxlen=None, process_stream_data=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 subscriptions limit per stream!
Create !userData streams as single streams, because it’s using a different endpoint and can not get combined with other streams in a multiplexed stream!
Example CEX:
binance_websocket_api_manager.create_stream(["arr"], ["!userData"], api_key="aaa", api_secret="bbb")
Isolated Margin:
binance_websocket_api_manager.create_stream(["arr"], ["!userData"], api_key="aaa", api_secret="bbb", symbols="ankrbtc")
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
stream_buffer_name (bool or str) – If False the data is going to get written to the default stream_buffer, set to True to read the data via pop_stream_data_from_stream_buffer(stream_id) or provide a string to create and use a shared stream_buffer and read it via pop_stream_data_from_stream_buffer(‘string’).
api_key (str) – provide a valid Binance API key
api_secret (str) – provide a valid Binance API secret
symbols (str) – provide the symbols for isolated_margin user_data streams
output (str) –
the default setting raw_data can be globaly overwritten with the parameter output_default of BinanceWebSocketApiManager`. To overrule the output_default value for this specific stream, set output to “dict” to convert the received raw data to a python dict, set to “UnicornFy” to convert with UnicornFy - otherwise with the default setting “raw_data” the output remains unchanged and gets delivered as received from the endpoints
ping_interval (int or None) –
Once the connection is open, a Ping frame is sent every ping_interval seconds. This serves as a keepalive. It helps keeping the connection open, especially in the presence of proxies with short timeouts on inactive connections. Set ping_interval to None to disable this behavior. (default: 20) This parameter is passed through to the websockets.client.connect()
ping_timeout (int or None) –
If the corresponding Pong frame isn’t received within ping_timeout seconds, the connection is considered unusable and is closed with code 1011. This ensures that the remote endpoint remains responsive. Set ping_timeout to None to disable this behavior. (default: 20) This parameter is passed through to the websockets.client.connect()
close_timeout (int or None) –
The close_timeout parameter defines a maximum wait time in seconds for completing the closing handshake and terminating the TCP connection. (default: 10) This parameter is passed through to the websockets.client.connect()
stream_buffer_maxlen (int or None) – Set a max len for the stream_buffer. Only used in combination with a non generic stream_buffer. The generic stream_buffer uses always the value of BinanceWebSocketApiManager().
process_stream_data (function) –
Provide a function/method to process the received webstream data (callback). The function will be called instead of add_to_stream_buffer() like process_stream_data(stream_data) where stream_data cointains the raw_stream_data. If not provided, the raw stream_data will get stored in the stream_buffer or provided to the global callback function provided during object instantiation! How to read from stream_buffer!
- Returns:
stream_id or ‘False’
- create_websocket_uri(channels, markets, stream_id=False, api_key=False, api_secret=False, symbols=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 (str) – 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
symbols (str) – provide the symbols for isolated_margin user_data streams
- 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 (str) – 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 (str) – 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 or False
- get_all_receives_last_second()¶
Get the number of all receives of the last second
- Returns:
int
- get_binance_api_status()¶
get_binance_api_status() is obsolete and will be removed in future releases, please use get_used_weight() instead!
- Returns:
dict
- get_current_receiving_speed(stream_id)¶
Get the receiving speed of the last second in Bytes
- Returns:
int
- get_current_receiving_speed_global()¶
Get the receiving speed of the last second in Bytes from all streams!
- Returns:
int
- static get_date_of_timestamp(timestamp)¶
Convert a timestamp into a readable date/time format for humans
- Parameters:
timestamp (timestamp) – provide the timestamp you want to convert into a date
- Returns:
str
- get_debug_log()¶
Get the debug log string.
- Returns:
str
- get_errors_from_endpoints()¶
Get all the stored error messages from the ringbuffer sent by the endpoints.
- Returns:
list
- get_event_loop_by_stream_id(stream_id: str | bool | None = False) bool ¶
Get the asyncio event loop used by a specific stream.
- Returns:
asyncio event loop or False
- 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_lucit_collector 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_lucit_collector.py 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)
- Returns:
int
- get_listen_key_from_restclient(stream_id, api_key, api_secret, symbols=False)¶
Get a new or cached (<30m) listen_key
- Parameters:
stream_id (str) – provide a stream_id
api_key (str) – provide a valid Binance API key
api_secret (str) – provide a valid Binance API secret
symbols (str) – provide the symbols for isolated_margin user_data streams
- 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:
check_command_version (str) – is the version of the calling check_command
warn_on_update (bool) – set to False to disable the update warning
- 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:
check_command_version (False or str) –
is the version of the calling check_command
warn_on_update (bool) – set to False to disable the update warning
- Returns:
dict
- get_most_receives_per_second()¶
Get the highest total receives per second value
- Returns:
int
- static get_new_uuid_id() str ¶
Get a new unique uuid in string format. This is used as ‘stream_id’ or ‘socket_id’.
- Returns:
uuid (str)
- get_number_of_all_subscriptions()¶
Get the amount of all stream subscriptions
- Returns:
int
- get_number_of_free_subscription_slots(stream_id)¶
Get the number of free subscription slots (max allowed subscriptions - subscriptions) of a specific stream
- Returns:
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_result_by_request_id(request_id=False, timeout=10)¶
Get the result related to the provided request_id
- Parameters:
request_id (stream_id (uuid)) – if you run get_stream_subscriptions() it returns a unique request_id - provide it to this method to receive the result.
timeout (int) – seconds to wait to receive the result. If not there it returns ‘False’
- Returns:
result or False
- get_results_from_endpoints()¶
Get all the stored result messages from the ringbuffer sent by the endpoints.
- Returns:
list
- get_ringbuffer_error_max_size()¶
How many entries should be stored in the ringbuffer?
- Returns:
int
- get_ringbuffer_result_max_size()¶
How many entries should be stored in the ringbuffer?
- 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(stream_buffer_name=False)¶
Get the current number of items in all stream_buffer or of a specific stream_buffer
- Parameters:
stream_buffer_name (str or stream_id) – Name of the stream_buffer
- Returns:
int
- get_stream_buffer_maxlen(stream_buffer_name=False)¶
Get the maxlen value of the stream_buffer
If maxlen is not specified or is None, stream_buffer may grow to an arbitrary length. Otherwise, the stream_buffer is bounded to the specified maximum length. Once a bounded length stream_buffer is full, when new items are added, a corresponding number of items are discarded from the opposite end.
- Parameters:
stream_buffer_name (bool or str) – False to read from generic stream_buffer, the stream_id if you used True in create_stream() or the string name of a shared stream_buffer.
- Returns:
int or False
- 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:
stream_id or False
- get_stream_info(stream_id)¶
Get all infos about a specific stream
- Parameters:
stream_id (str) – id of a stream
- Returns:
set
- get_stream_label(stream_id=False)¶
Get the stream_label of a specific stream
- Parameters:
stream_id (str) – 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 (str) – id of a stream
- Returns:
int
- get_stream_statistic(stream_id)¶
Get the statistic of a specific stream
- Parameters:
stream_id (str) – id of a stream
- Returns:
set
- get_stream_subscriptions(stream_id, request_id=False)¶
Get a list of subscriptions of a specific stream from Binance endpoints - the result can be received via the stream_buffer and is also added to the results ringbuffer - get_results_from_endpoints() to get all results or use get_result_by_request_id(request_id) to get a specific one!
This function is supported by CEX endpoints only!
- Parameters:
stream_id (str) – id of a stream
request_id (int) – id to use for the request - use get_request_id() to create a unique id. If not provided or False, then this method is using get_request_id() automatically.
- Returns:
request_id (int)
- get_total_received_bytes()¶
Get number of total received bytes
- Returns:
int
- get_total_receives()¶
Get the number of total receives
- Returns:
int
- get_used_weight()¶
Get used_weight, last status_code and the timestamp of the last status update
- Returns:
dict
- get_user_agent()¶
Get the user_agent string “lib name + lib version + python version”
- Returns:
- get_version()¶
Get the package/module version
- Returns:
str
- static help()¶
Help in iPython
- increase_processed_receives_statistic(stream_id)¶
Add the number of processed receives
- Parameters:
stream_id (str) – id of a stream
- increase_received_bytes_per_second(stream_id, size)¶
Add the amount of received bytes per second
- Parameters:
stream_id (str) – id of a stream
size (int) – amount of bytes to add
- increase_reconnect_counter(stream_id)¶
Increase reconnect counter
- Parameters:
stream_id (str) – 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: str
- 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 (str) – id of a stream
- Returns:
bool
- is_stop_request(stream_id, exclude_kill_requests=False)¶
Has a specific stream a stop_request?
- Parameters:
stream_id (str) – id of a stream
exclude_kill_requests (bool) – if True this method returns False on kill_requests
- Returns:
bool
- is_stream_signal_buffer_enabled()¶
Is the stream_signal_buffer enabled?
- Returns:
bool
- is_update_availabe_check_command(check_command_version=False)¶
Is a new release of check_lucit_collector.py available?
- Returns:
bool
- is_update_available()¶
Is a new release of this package available?
- Returns:
bool
- kill_stream(stream_id)¶
Kill a specific stream
- Parameters:
stream_id (str) – id of a stream
- Returns:
bool
- pop_stream_data_from_stream_buffer(stream_buffer_name=False, mode='FIFO')¶
Get oldest or latest entry from stream_buffer and remove from FIFO/LIFO stack.
- Parameters:
stream_buffer_name (bool or str) – False to read from generic stream_buffer, the stream_id if you used True in create_stream() or the string name of a shared stream_buffer.
mode (str) – How to read from the stream_buffer - “FIFO” (default) or “LIFO”.
- Returns:
stream_data - str, dict or False
- pop_stream_signal_from_stream_signal_buffer()¶
Get oldest entry from stream_signal_buffer and remove from stack/pipe (FIFO stack)
- Returns:
stream_signal - dict or False
- print_stream_info(stream_id, add_string='', title=None)¶
Print all infos about a specific stream, helps debugging :)
- Parameters:
stream_id (str) – id of a stream
add_string (str) – text to add to the output
title (bool) – set to True to use curses instead of print()
- Returns:
bool
- print_summary(add_string='', disable_print=False, title=None)¶
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()
title (str) – set a title (first row) for print_summary output
- 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()
LINUX ONLY It should not be hard to make it OS independent: https://github.com/LUCIT-Systems-and-Development/unicorn-binance-websocket-api/issues/61
- Parameters:
print_summary_export_path (str) – If you want to export the output of print_summary() to an image, please provide a path like “/var/www/html/”. View the Wiki!
hight_per_row (int) – set the hight per row for the image hight calculation
- 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, new_stream_label=None, new_stream_buffer_name=False, new_api_key=False, new_api_secret=False, new_symbols=False, new_output='raw_data', new_ping_interval=20, new_ping_timeout=20, new_close_timeout=10, new_stream_buffer_maxlen=None)¶
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 (str) – 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
new_stream_label (str) – provide a stream_label to identify the stream
new_stream_buffer_name (bool or str) – If False the data is going to get written to the default stream_buffer, set to True to read the data via pop_stream_data_from_stream_buffer(stream_id) or provide a string to create and use a shared stream_buffer and read it via pop_stream_data_from_stream_buffer(‘string’).
new_api_key (str) – provide a valid Binance API key
new_api_secret (str) – provide a valid Binance API secret
new_symbols (str) – provide the symbols for isolated_margin user_data streams
new_output (str) –
set to “dict” to convert the received raw data to a python dict, set to “UnicornFy” to convert with UnicornFy - otherwise the output remains unchanged and gets delivered as received from the endpoints
new_ping_interval (int or None) –
Once the connection is open, a Ping frame is sent every ping_interval seconds. This serves as a keepalive. It helps keeping the connection open, especially in the presence of proxies with short timeouts on inactive connections. Set ping_interval to None to disable this behavior. (default: 20) This parameter is passed through to the websockets.client.connect()
new_ping_timeout (int or None) –
If the corresponding Pong frame isn’t received within ping_timeout seconds, the connection is considered unusable and is closed with code 1011. This ensures that the remote endpoint remains responsive. Set ping_timeout to None to disable this behavior. (default: 20) This parameter is passed through to the websockets.client.connect()
new_close_timeout (int or None) –
The close_timeout parameter defines a maximum wait time in seconds for completing the closing handshake and terminating the TCP connection. (default: 10) This parameter is passed through to the websockets.client.connect()
new_stream_buffer_maxlen (int or None) – Set a max len for the stream_buffer. Only used in combination with a non generic stream_buffer. The generic stream_buffer uses always the value of BinanceWebSocketApiManager().
- Returns:
new stream_id
- Returns:
new_stream_id or ‘False’
- 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_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 (str) – id of the old stream
- set_ringbuffer_error_max_size(max_size)¶
How many error messages should be kept in the ringbuffer?
- Parameters:
max_size (int) – Max entries of error messages in the ringbuffer.
- Returns:
bool
- set_ringbuffer_result_max_size(max_size)¶
How many result messages should be kept in the ringbuffer?
- Parameters:
max_size (int) – Max entries of result messages in the ringbuffer.
- Returns:
bool
- set_socket_is_not_ready(stream_id: str) None ¶
Set socket_is_ready for a specific stream to False.
- Parameters:
stream_id (str) – id of the stream
- set_socket_is_ready(stream_id: str) None ¶
Set socket_is_ready for a specific stream to True.
- Parameters:
stream_id (str) – id of the stream
- set_stream_label(stream_id, stream_label=None)¶
Set a stream_label by stream_id
- Parameters:
stream_id (str) – 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 (list) – 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
Take a look into the Wiki to see how this works!
- 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
- Returns:
bool
- stop_stream(stream_id, delete_listen_key=True)¶
Stop a specific stream
- Parameters:
stream_id (str) – id of a stream
delete_listen_key (str) – If set to True (default), the listen_key gets deleted. Set to False if you run more than one userData stream with this listen_key!
- Returns:
bool
- stop_stream_as_crash(stream_id)¶
Stop a specific stream with ‘crashed’ status
- Parameters:
stream_id (str) – 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 (str) – 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 (str) – id of a stream
- Returns:
bool
- 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
- Parameters:
stream_id (str) – 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=None, markets=None)¶
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
- Parameters:
stream_id (str) – 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 and received its first stream data
- Parameters:
stream_id (str) – id of a stream
- Returns:
bool
- wait_till_stream_has_stopped(stream_id)¶
Returns True as soon a specific stream has stopped itself
- Parameters:
stream_id (str) – id of a stream
- Returns:
bool
unicorn_binance_websocket_api.restclient module¶
- class unicorn_binance_websocket_api.restclient.BinanceWebSocketApiRestclient(manager)¶
Bases:
object
- delete_listen_key(stream_id=False, api_key=False, api_secret=False, listen_key=False)¶
Delete a specific listen key
- Parameters:
stream_id (str) – provide a stream_id
api_key (str) – provide a valid Binance API key
api_secret (str) – provide a valid Binance API secret
listen_key (str or bool) – the listenkey you want to delete
- Returns:
the response
- Return type:
str or False
- get_listen_key(stream_id=False, api_key=False, api_secret=False, last_static_ping_listen_key=False, symbol=False)¶
Request a valid listen_key from binance
- Parameters:
stream_id (str) – provide a stream_id
api_key (str) – provide a valid Binance API key
api_secret (str) – provide a valid Binance API secret
last_static_ping_listen_key (int) – the last_static_ping_listen_key variable of the listen_key you want to keepalive
symbol (str) – provide the symbol for isolated_margin user_data listen_key
- Returns:
listen_key
- Return type:
str or False
- keepalive_listen_key(stream_id=False, api_key=False, api_secret=False, listen_key=False, last_static_ping_listen_key=False)¶
Ping a listenkey to keep it alive
- Parameters:
stream_id (str) – provide a stream_id
api_key (str) – provide a valid Binance API key
api_secret (str) – provide a valid Binance API secret
listen_key (str) – the listenkey you want to keepalive
last_static_ping_listen_key (int) – the last_static_ping_listen_key variable of the listen_key you want to keepalive
- Returns:
the response
- Return type:
str or False
unicorn_binance_websocket_api.restserver module¶
- class unicorn_binance_websocket_api.restserver.BinanceWebSocketApiRestServer(handler_binance_websocket_api_manager, warn_on_update=True)¶
Bases:
Resource
Provide a REST API server
Description: https://github.com/LUCIT-Systems-and-Development/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: t.ClassVar[t.Optional[t.Collection[str]]] = {'GET'}¶
The methods this view is registered for. Uses the same default (
["GET", "HEAD", "OPTIONS"]
) asroute
andadd_url_rule
by default.