Skip to content

Latest commit

 

History

History
600 lines (454 loc) · 48.4 KB

README.md

File metadata and controls

600 lines (454 loc) · 48.4 KB

Get a UNICORN Binance Suite License

GitHub Release GitHub Downloads Anaconda Release Anaconda Downloads PyPi Release PyPi Downloads License Supported Python Version PyPI - Status codecov CodeQL Unit Tests Build and Publish GH+PyPi Build and Publish Anaconda Read the Docs Read How To`s Github Telegram Gitter Get Free Professional Support

LUCIT-UBWA-Banner

UNICORN Binance WebSocket API

Description | Live Demo | Installation | How To | Documentation | Examples | Change Log | Wiki | Social | Notifications | Bugs | Contributing | Disclaimer | Commercial Support

A Python SDK by LUCIT to use the Binance Websocket API`s (com+testnet, com-margin+testnet, com-isolated_margin+testnet, com-futures+testnet, com-coin_futures, us, tr, dex/chain+testnet) in a simple, fast, flexible, robust and fully-featured way.

Part of 'UNICORN Binance Suite'.

Get help with the integration of the UNICORN Binance Suite modules!

Get a UNICORN Binance Suite License

To run modules of the UNICORN Binance Suite you need a valid license!

Receive Data from Binance WebSockets

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

from unicorn_binance_websocket_api import BinanceWebSocketApiManager

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

And 4 more lines to print out the data

while True:
    oldest_data_from_stream_buffer = ubwa.pop_stream_data_from_stream_buffer()
    if oldest_data_from_stream_buffer:
        print(oldest_data_from_stream_buffer)

Or with a callback function just do

from unicorn_binance_websocket_api import BinanceWebSocketApiManager

def process_new_receives(stream_data):
    print(str(stream_data))

ubwa = BinanceWebSocketApiManager(exchange="binance.com")
ubwa.create_stream(channels=['trade', 'kline_1m'], 
                   markets=['btcusdt', 'bnbbtc', 'ethbtc'], 
                   process_stream_data=process_new_receives)

Or with an async callback function just do

from unicorn_binance_websocket_api import BinanceWebSocketApiManager
import asyncio

async def process_new_receives(stream_data):
    print(stream_data)
    await asyncio.sleep(1)

ubwa = BinanceWebSocketApiManager()
ubwa.create_stream(channels=['trade', 'kline_1m'],
                   markets=['btcusdt', 'bnbbtc', 'ethbtc'],
                   process_stream_data_async=process_new_receives)

Or await the stream data in an asyncio coroutine

All the methods of data collection presented have their own advantages and disadvantages. However, this is the generally recommended method for processing data from streams.

from unicorn_binance_websocket_api import BinanceWebSocketApiManager
import asyncio

async def main():
    async def process_asyncio_queue(stream_id=None):
        print(f"Start processing the data from stream '{ubwa.get_stream_label(stream_id)}':")
        while ubwa.is_stop_request(stream_id) is False:
            data = await ubwa.get_stream_data_from_asyncio_queue(stream_id)
            print(data)
            ubwa.asyncio_queue_task_done(stream_id)
    ubwa.create_stream(channels=['trade'],
                       markets=['ethbtc', 'btcusdt'],
                       stream_label="TRADES",
                       process_asyncio_queue=process_asyncio_queue)
    while not ubwa.is_manager_stopping():
        await asyncio.sleep(1)

with BinanceWebSocketApiManager(exchange='binance.com') as ubwa:
    try:
        asyncio.run(main())
    except KeyboardInterrupt:
        print("\r\nGracefully stopping ...")
    except Exception as e:
        print(f"\r\nERROR: {e}\r\nGracefully stopping ...")

Basically that's it, but there are more options.

Convert received stream data into well-formed Python dictionaries with UnicornFy

unicorn_fied_stream_data = UnicornFy.binance_com_websocket(data)

or

ubwa.create_stream(['trade'], ['btcusdt'], output="UnicornFy")

Subscribe / unsubscribe new markets and channels

markets = ['engbtc', 'zileth']
channels = ['kline_5m', 'kline_15m', 'kline_30m', 'kline_1h', 'kline_12h', 'depth5']

ubwa.subscribe_to_stream(stream_id=stream_id, channels=channels, markets=markets)

ubwa.unsubscribe_from_stream(stream_id=stream_id, markets=markets)

ubwa.unsubscribe_from_stream(stream_id=stream_id, channels=channels)

Send Requests to Binance WebSocket API

from unicorn_binance_websocket_api import BinanceWebSocketApiManager

api_key = "YOUR_BINANCE_API_KEY"
api_secret = "YOUR_BINANCE_API_SECRET"

async def process_api_responses(stream_id=None):
    while ubwa.is_stop_request(stream_id=stream_id) is False:
        data = await ubwa.get_stream_data_from_asyncio_queue(stream_id=stream_id)
        print(data)
        ubwa.asyncio_queue_task_done(stream_id=stream_id)

ubwa = BinanceWebSocketApiManager(exchange="binance.com")
api_stream = ubwa.create_stream(api=True,
                                api_key=api_key,
                                api_secret=api_secret,
                                output="UnicornFy",
                                process_asyncio_queue=process_api_responses)

response = ubwa.api.spot.get_server_time(return_response=True)
print(f"Binance serverTime: {response['result']['serverTime']}")

orig_client_order_id = ubwa.api.spot.create_order(order_type="LIMIT",
                                                  price = 1.1,
                                                  quantity = 15.0,
                                                  side = "SELL",
                                                  symbol = "BUSDUSDT")

ubwa.api.spot.cancel_order(orig_client_order_id=orig_client_order_id, symbol="BUSDUSDT")                                   

All available methods:

Here you can find a complete guide on how to process requests via the Binance WebSocket API!

Stop ubwa after usage to avoid memory leaks

When you instantiate UBWA with with, ubwa.stop_manager() is automatically executed upon exiting the with-block.

with BinanceWebSocketApiManager() as ubwa:
    ubwa.create_stream(channels="trade", markets="btcusdt", stream_label="TRADES")

Without with, you must explicitly execute ubwa.stop_manager() yourself.

ubwa.stop_manager()

stream_signals - know the state of your streams

Usually you want to know when a stream is working and when it is not. This can be useful to know that your own system is currently "blind" and you may want to close open positions to be on the safe side, know that indicators will now provide incorrect values or that you have to reload the missing data via REST as an alternative.

For this purpose, the UNICORN Binance WebSocket API provides so-called stream_signals, which are used to tell your code in real time when a stream is connected, when it received its first data record, when it was disconnected and stopped, and when the stream cannot be restored.

from unicorn_binance_websocket_api import BinanceWebSocketApiManager
import time

def process_stream_signals(signal_type=None, stream_id=None, data_record=None, error_msg=None):
    print(f"Received stream_signal for stream '{ubwa.get_stream_label(stream_id=stream_id)}': "
          f"{signal_type} - {stream_id} - {data_record} - {error_msg}")

with BinanceWebSocketApiManager(process_stream_signals=process_stream_signals) as ubwa:
    ubwa.create_stream(channels="trade", markets="btcusdt", stream_label="TRADES")
    print(f"Waiting a few seconds and then stopping the stream ...")
    time.sleep(7)

More?

Discover even more possibilities, use this script to stream everything from "binance.com" or try our examples!

This should be known by everyone using this lib:

Description

The Python package UNICORN Binance WebSocket API provides an API to the Binance Websocket API`s of Binance (+Testnet), Binance Margin (+Testnet), Binance Isolated Margin (+Testnet), Binance Futures (+Testnet), Binance COIN-M Futures, Binance US, Binance TR, Binance DEX and Binance DEX Testnet and supports sending requests to the Binance Websocket API and the streaming of all public streams like trade, kline, ticker, depth, bookTicker, forceOrder, compositeIndex, blockheight etc. and also all private userData streams which needs to be used with a valid api_key and api_secret from the Binance Exchange www.binance.com, testnet.binance.vision or www.binance.us - for the DEX you need a user address from www.binance.org or testnet.binance.org, and you can get funds for the testnet.

Use the UNICORN Binance REST API in combination.

What are the benefits of the UNICORN Binance WebSocket API?

Exchange Exchange string WS WS API
Binance binance.com yes yes
Binance Testnet binance.com-testnet yes yes
Binance Margin binance.com-margin yes no
Binance Margin Testnet binance.com-margin-testnet yes no
Binance Isolated Margin binance.com-isolated_margin yes no
Binance Isolated Margin Testnet binance.com-isolated_margin-testnet yes no
Binance USD-M Futures binance.com-futures yes yes
Binance USD-M Futures Testnet binance.com-futures-testnet yes yes
Binance Coin-M Futures binance.com-coin_futures yes no
Binance US binance.us yes no
Binance TR trbinance.com yes no
Binance DEX binance.org yes no
Binance DEX Testnet binance.org-testnet yes no

If you like the project, please star it on GitHub!

Live Demo

This live demo script is streaming from binance.com and runs on a CCX13 virtual machine of HETZNER CLOUD

Open live monitor!

live-demo

(Refresh update once a minute!)

Installation and Upgrade

The module requires Python 3.8 and runs smoothly up to and including Python 3.12.

Anaconda packages are available from Python version 3.8 and higher, but only in the latest version!

For the PyPy interpreter we offer packages via PyPi only from Python version 3.9 and higher.

The current dependencies are listed here.

If you run into errors during the installation take a look here.

Packages are created automatically with GitHub Actions

When a new release is to be created, we start two GitHubActions:

Both start virtual Windows/Linux/Mac servers provided by GitHub in the cloud with preconfigured environments and create the respective compilations and stub files, pack them into wheels and conda packages and then publish them on GitHub, PYPI and Anaconda. This is a transparent method that makes it possible to trace the source code behind a compilation.

A Cython binary, PyPy or source code based CPython wheel of the latest version with pip from PyPI

Our Cython and PyPy Wheels are available on PyPI, these wheels offer significant advantages for Python developers:

  • Performance Boost with Cython Wheels: Cython is a programming language that supplements Python with static typing and C-level performance. By compiling Python code into C, Cython Wheels can significantly enhance the execution speed of Python code, especially in computationally intensive tasks. This means faster runtimes and more efficient processing for users of our package.

  • PyPy Wheels for Enhanced Efficiency: PyPy is an alternative Python interpreter known for its speed and efficiency. It uses Just-In-Time (JIT) compilation, which can dramatically improve the performance of Python code. Our PyPy Wheels are tailored for compatibility with PyPy, allowing users to leverage this speed advantage seamlessly.

Both Cython and PyPy Wheels on PyPI make the installation process simpler and more straightforward. They ensure that you get the optimized version of our package with minimal setup, allowing you to focus on development rather than configuration.

On Raspberry Pi and other architectures for which there are no pre-compiled versions, the package can still be installed with PIP. PIP then compiles the package locally on the target system during installation. Please be patient, this may take some time!

Installation

pip install unicorn-binance-websocket-api

Update

pip install unicorn-binance-websocket-api --upgrade

A Conda Package of the latest version with conda from Anaconda

The unicorn-binance-websocket-api package is also available as a Cython version for the linux-64, osx-64 and win-64 architectures with Conda through the lucit channel.

For optimal compatibility and performance, it is recommended to source the necessary dependencies from the conda-forge channel.

Installation

conda config --add channels conda-forge
conda config --add channels lucit
conda install -c lucit unicorn-binance-websocket-api

Update

conda update -c lucit unicorn-binance-websocket-api

From source of the latest release with PIP from GitHub

Linux, macOS, ...

Run in bash:

pip install https://github.com/LUCIT-Systems-and-Development/unicorn-binance-websocket-api/archive/$(curl -s https://api.github.com/repos/LUCIT-Systems-and-Development/unicorn-binance-websocket-api/releases/latest | grep -oP '"tag_name": "\K(.*)(?=")').tar.gz --upgrade

Windows

Use the below command with the version (such as 2.9.0) you determined here:

pip install https://github.com/LUCIT-Systems-and-Development/unicorn-binance-websocket-api/archive/2.9.0.tar.gz --upgrade

From the latest source (dev-stage) with PIP from GitHub

This is not a release version and can not be considered to be stable!

pip install https://github.com/LUCIT-Systems-and-Development/unicorn-binance-websocket-api/tarball/master --upgrade

Change Log

https://unicorn-binance-websocket-api.docs.lucit.tech/changelog.html

Documentation

Examples

Howto

Project Homepage

https://www.lucit.tech/unicorn-binance-websocket-api.html

Wiki

https://github.com/LUCIT-Systems-and-Development/unicorn-binance-websocket-api/wiki

Social

Receive Notifications

To receive notifications on available updates you can watch the repository on GitHub, write your own script with using is_update_available() or you use the monitoring API service.

Follow us on LinkedIn, X or Facebook!

To receive news (like inspection windows/maintenance) about the Binance API`s subscribe to their telegram groups:

How to report Bugs or suggest Improvements?

List of planned features - click thumbs-up if you need one of them or suggest a new feature!

Before you report a bug, try the latest release. If the issue still exists, provide the error trace, OS and Python version and explain how to reproduce the error. A demo script is appreciated.

If you don't find an issue related to your topic, please open a new issue!

Report a security bug!

Contributing

UNICORN Binance WebSocket API is an open source project which welcomes contributions which can be anything from simple documentation fixes and reporting dead links to new features. To contribute follow this guide.

Contributors

Contributors

We love open source!

Disclaimer

This project is for informational purposes only. You should not construe this information or any other material as legal, tax, investment, financial or other advice. Nothing contained herein constitutes a solicitation, recommendation, endorsement or offer by us or any third party provider to buy or sell any securities or other financial instruments in this or any other jurisdiction in which such solicitation or offer would be unlawful under the securities laws of such jurisdiction.

If you intend to use real money, use it at your own risk!

Under no circumstances will we be responsible or liable for any claims, damages, losses, expenses, costs or liabilities of any kind, including but not limited to direct or indirect damages for loss of profits.

SOCKS5 Proxy / Geoblocking

We would like to explicitly point out that in our opinion US citizens are exclusively authorized to trade on Binance.US and that this restriction must not be circumvented!

The purpose of supporting a SOCKS5 proxy in the UNICORN Binance Suite and its modules is to allow non-US citizens to use US services. For example, GitHub actions with UBS will not work without a SOCKS5 proxy, as they will inevitably run on servers in the US and be blocked by Binance.com. Moreover, it also seems justified that traders, data scientists and companies from the US analyze binance.com market data - as long as they do not trade there.

Commercial Support

Get professional and fast support

Do you need a developer, operator or consultant? Contact us for a non-binding initial consultation!