Article-Details

Howto: UNICORN Binance WebSocket API

by Oliver Zehentleitner

Documentation: API reference
Github: https://github.com/unicorn-data-analysis/unicorn-binance-websocket-api
PyPI: https://pypi.org/project/unicorn-binance-websocket-api/
UnicornFy: https://github.com/unicorn-data-analysis/unicorn_fy
Icinga Plugin: https://github.com/unicorn-data-analysis/check_unicorn_monitoring_api

Installation

You can install the library with `pip install unicorn-binance-websocket-api` from PyPI or you download the latest release or the dev-stage. The easiest way to test the examples is to clone the repository from git with `git clone git@github.com:unicorn-data-analysis/unicorn-binance-websocket-api.git` to your local system.

How to use the class?

Import the `BinanceWebSocketApiManager` class:

from unicorn_binance_websocket_api.unicorn_binance_websocket_api_manager import BinanceWebSocketApiManager

Additionally we need more imports for this example:

import logging
import time
import os

Configure logging, to get a very verbose mode use DEBUG instead of INFO:

logging.basicConfig(filename=os.path.basename(__file__) + '.log')
logging.getLogger(__name__).setLevel(logging.INFO)
logging.getLogger(__name__).addHandler(logging.StreamHandler())

Create an instance of the `BinanceWebSocketApiManager` to connect to Binance (binance.com):

binance_websocket_api_manager = BinanceWebSocketApiManager(exchange="binance.com")

If you would like to use the Binance Jersey API then use:

binance_websocket_api_manager = BinanceWebSocketApiManager(exchange="binance.je")

Other supported exchanges:

binance_websocket_api_manager = BinanceWebSocketApiManager(exchange="binance.org")
binance_websocket_api_manager = BinanceWebSocketApiManager(exchange="binance.org-testnet")

In this tutorial we continue with streams for binance.com (example_binance_dex.py, example_binance_jersey.py):

Now define the channels and markets you wish to stream. In this example we define a multiplex stream with 3 channels and 5 markets, resulting in 15 different streams (in one multistream - only one connection) Unfortunately you can not receive !miniTicker, !ticker or !userData with the other streams combined. All of this 3 (!miniTicker, !ticker and !userData) must be created as a single websocket stream. If you want all stream types you have to create minimum 4 streams at least. Be also aware, that Binance doesnt allow infinity long URIs, so you can not create one stream with kline_5m, kline_15m, kline_30m, kline_1h, kline_12h and trades for 150 markets in one stream. Binance blocks this and the stream could not establish a connection.

channels = {'trade', 'kline_5m', 'depth5'}
markets = {'bnbbtc', 'ethbtc', 'btcusdt', 'bchabcusdt', 'eosusdt'}

Then create and start the multiplex stream:

multi_stream_id = binance_websocket_api_manager.create_stream(channels, markets)

And create a `!userData` stream:

binance_websocket_api_manager.set_private_api_config(binance_api_key, binance_api_secret)
user_data_stream_id = binance_websocket_api_manager.create_stream('arr', '!userData')

And a `!ticker` and `!miniTicker` stream:

ticker_stream_id = binance_websocket_api_manager.create_stream(["arr"], ["!miniTicker"])
miniticker_stream_id = binance_websocket_api_manager.create_stream(["arr"], ["!ticker"])

To watch what your streams are doing use:

while True:
binance_websocket_api_manager.print_summary()
time.sleep(1)


Now your streams should be running, and everything happening with the received data is, its stored in the stream_buffer. To get and remove the oldest entry from the stream_buffer stack do:

oldest_stream_data_from_stream_buffer = binance_websocket_api_manager.pop_stream_data_from_stream_buffer()

Then you can do with it what every you want. If your database is down for a restart or anything else, you can kick the data back to the stream_buffer with:

binance_websocket_api_manager.add_to_stream_buffer(oldest_stream_data_from_stream_buffer)

View this stream_buffer example!

An other way to process the received data is, to provide an own process_streams class (use this template to start) when creating the manager instance, so instead of writing the raw_stream_data to the stream_buffer, each receive will directly trigger the function/method you provided:

from unicorn_binance_websocket_api_process_streams import BinanceWebSocketApiProcessStreams
binance_websocket_api_manager = BinanceWebSocketApiManager(BinanceWebSocketApiProcessStreams.process_stream_data)

The process_streams template is only printing the data, so you have to extend the file `unicorn_binance_websocket_api_process_streams.py` and replace "print" with your business logic.

If you would like to unify the received data with UnicornFy, please follow this guide.

Here are some working example files (just clone the repository and run them):
https://github.com/unicorn-data-analysis/unicorn-binance-websocket-api/blob/master/example_binance_dex.py
https://github.com/unicorn-data-analysis/unicorn-binance-websocket-api/blob/master/example_binance_jersey.py
https://github.com/unicorn-data-analysis/unicorn-binance-websocket-api/blob/master/example_demo.py
https://github.com/unicorn-data-analysis/unicorn-binance-websocket-api/blob/master/example_monitoring.py
https://github.com/unicorn-data-analysis/unicorn-binance-websocket-api/blob/master/example_multi_stream.py
https://github.com/unicorn-data-analysis/unicorn-binance-websocket-api/blob/master/example_stream_management.py
https://github.com/unicorn-data-analysis/unicorn-binance-websocket-api/blob/master/example_stream_management_extended.py
https://github.com/unicorn-data-analysis/unicorn-binance-websocket-api/blob/master/example_stream_buffer.py
https://github.com/unicorn-data-analysis/unicorn-binance-websocket-api/blob/master/example_ticker_and_miniticker.py
https://github.com/unicorn-data-analysis/unicorn-binance-websocket-api/blob/master/example_trade_stream.py
https://github.com/unicorn-data-analysis/unicorn-binance-websocket-api/blob/master/example_userdata_stream.py
https://github.com/unicorn-data-analysis/unicorn-binance-websocket-api/blob/master/example_version_of_this_package.py

UNICORN Binance WebSocket API Demo

Go back

Add a comment

Please calculate 8 plus 1.