Package: unicorn-binance-websocket-api
UNICORN Binance WebSocket APIDescription|Live Demo|Installation|How To|Documentation|Examples|Change Log|Wiki|Social|Notifications|Bugs|Contributing|Disclaimer|Commercial SupportA Python API byLUCITto 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 easy, fast, flexible, robust and fully-featured way.Part of 'UNICORN Binance Suite'.Get help with the integration of theUNICORN Binance Suitemodules from theUNICORN Binance Suite AssistantGPTora real human LUCIT employee.Get a UNICORN Binance Suite LicenseTo run modules of theUNICORN Binance Suiteyou need avalid license!Receive Data from Binance WebSocketsCreate a multiplex websocket connectionto Binance with astream_bufferwith 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 the receives: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 acallback functionjust 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)Basically that's it, but there are more options.Convert received raw webstream data into well-formed Python dictionaries withUnicornFy:unicorn_fied_stream_data = UnicornFy.binance_com_websocket(oldest_data_from_stream_buffer)orubwa.create_stream(['trade'], ['btcusdt'], output="UnicornFy")Subscribe/unsubscribenew 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 APIPlace orders,cancel ordersorsend other requestsvia WebSocket:from unicorn_binance_websocket_api import BinanceWebSocketApiManager


def process_api_responses(stream_data):
    print(str(stream_data))


api_key = "YOUR_BINANCE_API_KEY"
api_secret = "YOUR_BINANCE_API_SECRET"


ubwa = BinanceWebSocketApiManager(exchange="binance.com")
api_stream = ubwa.create_stream(api=True, 
                                api_key=api_key, 
                                api_secret=api_secret,
                                process_stream_data=process_api_responses)
                                
orig_client_order_id = ubwa.api.create_order(order_type="LIMIT", 
                                             price=1.1, 
                                             quantity=15.0, 
                                             side="SELL", 
                                             symbol="BUSDUSDT")
ubwa.api.cancel_order(orig_client_order_id=orig_client_order_id, symbol="BUSDUSDT")Hereyou can find a complete
guide onhow to process requests via the Binance WebSocket API!Stopubwaafter usage to avoid memory leaksubwa.stop_manager()Discover even more possibilitiesoruse this scriptto stream everything from "binance.com".This should be known by everyone using this lib:Best practice solutions for a maximum stable connectionDo you want consistent data from binance?DescriptionThe Python packageUNICORN Binance WebSocket APIprovides an API to the Binance Websocket API`s ofBinance(+Testnet),Binance Margin(+Testnet),Binance Isolated Margin(+Testnet),Binance Futures(+Testnet),Binance COIN-M Futures,Binance US,Binance TR,Binance DEXandBinance DEX Testnetand supports sending requests
to theBinance Websocket APIand 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 validapi_key and api_secretfrom the Binance Exchangewww.binance.com,testnet.binance.visionorwww.binance.us- for the DEX you need a user address fromwww.binance.orgortestnet.binance.organd you canget fundsfor the testnet.Use theUNICORN Binance REST APIin combination.What are the benefits of the UNICORN Binance WebSocket API?Fully managed websockets and 100% auto-reconnect! Also handles maintenance windows!Support forBinance Websocket API, send
requests likecreate_order,cancel_open_ordersandmany moredirectly over websocket!Supported exchanges:ExchangeExchange stringWSWS APIBinancebinance.comBinance Testnetbinance.com-testnetBinance Marginbinance.com-marginBinance Margin Testnetbinance.com-margin-testnetBinance Isolated Marginbinance.com-isolated_marginBinance Isolated Margin Testnetbinance.com-isolated_margin-testnetBinance USD-M Futuresbinance.com-futuresBinance USD-M Futures Testnetbinance.com-futures-testnetBinance Coin-M Futuresbinance.com-coin_futuresBinance USbinance.usBinance TRtrbinance.comBinance DEXbinance.orgBinance DEX Testnetbinance.org-testnetStreams are processing asynchronous/concurrent (Python asyncio) and each stream is started in a separate thread, so
you don't need to deal with asyncio in your code!Supportssubscribe/unsubscribeon all exchanges! (Take a look to the max supported subscriptions per stream in theendpoint configuration overview!)UNICORN Binance WebSocket APIrespects Binance's API guidelines and protects you from avoidable reconnects and bans.Support for multiple private!userDatastreams with differentapi_keyandapi_secret. (example_multiple_userdata_streams.py)Pick up the received data from thestream_buffer-
if you can not store your data in cause of a temporary technical issue, you cankick back the data to thestream_bufferwhich stores the receives in the RAM till you are able to process the data in the normal way again.Learn more!Use separatestream_buffersforspecific streamsorusers!Watch thestream_signal_bufferto receiveCONNECT,DISCONNECTandFIRST_RECEIVED_DATAsignals about the
streams!Learn more!Get the received data unchanged as received, as Python dictionary or converted withUnicornFyinto well-formed Python dictionaries. Use theoutputparameter ofcreate_stream()to control the output format.Helpful management features likeget_binance_api_status(),get_current_receiving_speed(),get_errors_from_endpoints(),get_limit_of_subscriptions_per_stream(),get_request_id(),get_result_by_request_id(),get_results_from_endpoints(),get_stream_buffer_length(),get_stream_info(),get_stream_list(),get_stream_id_by_label(),get_stream_statistic(),get_stream_subscriptions(),get_version(),is_update_available(),pop_stream_data_from_stream_buffer(),print_summary(),replace_stream(),set_stream_label(),set_ringbuffer_error_max_size(),subscribe_to_stream(),stop_stream(),stop_manager_with_all_streams(),unsubscribe_from_stream(),wait_till_stream_has_started()and many more! Explore themhere.Monitor the status of the createdBinanceWebSocketApiManager()instance within your code withget_monitoring_status_plain()and specific streams withget_stream_info().Nice to use withiPython:
"IPython (Interactive Python) is a command shell for interactive computing that offers introspection,
rich media, shell syntax, tab completion, and history."
(example_interactive_mode.py)Also, nice to use with theJupyter Notebook:)Monitoring API serviceand acheck_commandforICINGA/NagiosIntegration oftest casesandexamples.Customizable base URL.Socks5 Proxysupport:ubwa = BinanceWebSocketApiManager(exchange="binance.com", socks5_proxy_server="127.0.0.1:9050")Read thedocsor thishow tofor more information or tryexample_socks5_proxy.py.Excessively tested on Linux, Mac and WindowsIf you like the project, pleaseit onGitHub!Live DemoThis live demo script is streaming frombinance.comand runs on acx31virtual
machine ofHETZNER CLOUD-get 20 EUR starting credit!Open live monitor!(Refresh update once a minute!)Installation and UpgradeThe module requires Python 3.7 or above, as it depends on Pythons latest asyncio features for asynchronous/concurrent
processing.For the PyPy interpreter we offer packages only from Python version 3.9 and higher.Anaconda packages are available from Python version 3.8 and higher.The current dependencies are listedhere.If you run into errors during the installation take a lookhere.A Cython binary, PyPy or source code based CPython wheel of the latest version withpipfromPyPIOurCythonandPyPyWheels are available onPyPI,
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.Installationpip install unicorn-binance-websocket-apiUpdatepip install unicorn-binance-websocket-api --upgradeA Conda Package of the latest version withcondafromAnacondaTheunicorn-binance-websocket-apipackage is also available as a Cython version for thelinux-64,osx-64andwin-64architectures withCondathrough thelucitchannel.For optimal compatibility and performance, it is recommended to source the necessary dependencies from theconda-forgechannel.Installationconda config --add channels conda-forge
conda config --add channels lucit
conda install -c lucit unicorn-binance-websocket-apiUpdateconda update -c lucit unicorn-binance-websocket-apiFrom source of the latest release with PIP fromGitHubLinux, 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 --upgradeWindowsUse the below command with the version (such as 2.1.4) you determinedhere:pip install https://github.com/LUCIT-Systems-and-Development/unicorn-binance-websocket-api/archive/2.1.4.tar.gz --upgradeFrom the latest source (dev-stage) with PIP fromGitHubThis 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 --upgradeConda environment,Virtualenvor plainPythonDownload thelatest releaseor thecurrent master branchand use:./environment.yml./pyproject.toml./requirements.txt./setup.pyChange Loghttps://unicorn-binance-websocket-api.docs.lucit.tech/changelog.htmlDocumentationGeneralModulesExamplesexample_apache_kafka.pyexample_binance_coin_futures.pyexample_binance_dex.pyexample_binance_futures.pyexample_binance_futures_1s.pyexample_binance_us.pyexample_bookticker.pyexample_ctrl-c.pyexample_demo.pyexample_easy_migration_from_python-binance.pyexample_interactive_mode.pyexample_kline_1m_with_unicorn_fy.pyexample_logging.pyexample_monitoring.pyexample_multi_stream.pyexample_multiple_userdata_streams.pyexample_pandas_ta-lib.pyexample_plotting_last_price.pyexample_process_streams.pyexample_socks5_proxy.pyexample_stream_buffer.pyexample_stream_buffer_extended.pyexample_stream_buffer_fifo-lifo.pyexample_stream_everything.pyexample_stream_management.pyexample_stream_management_extended.pyexample_stream_signals.pyexample_stream_signals_callback.pyexample_subscribe.pyexample_ticker_and_miniticker.pyexample_trade_stream.pyexample_trbinance.com.pyexample_userdata_stream.pyexample_userdata_stream_new_style.pyexample_version_of_this_package.pyexample_websocket_api.pyHowtoHow to Obtain and Use a Unicorn Binance Suite License Key and Run the UBS Module According to Best PracticeCreate and Cancel Orders via WebSocket on BinanceHow to Download Klines from Binance using Python?Passing Binance Market Data to Apache Kafka in Python with aiokafkaHow to Connect to binance.com Websockets using Python via a Socks5 ProxyProject Homepagehttps://www.lucit.tech/unicorn-binance-websocket-api.htmlWikihttps://github.com/LUCIT-Systems-and-Development/unicorn-binance-websocket-api/wikiSocialDiscussionsGitterhttps://t.me/unicorndevshttps://dev.binance.visionhttps://community.binance.orgReceive NotificationsTo receive notifications on available updates you canthe repository onGitHub, write yourown scriptwith usingis_update_available()or you use themonitoring API service.Follow us onLinkedIn,XorFacebook!To receive news (like inspection windows/maintenance) about the Binance API`s subscribe to their telegram groups:https://t.me/binance_api_announcementshttps://t.me/binance_api_englishhttps://t.me/Binance_USAhttps://t.me/TRBinanceTRhttps://t.me/BinanceDEXchangehttps://t.me/BinanceExchangeHow to report Bugs or suggest Improvements?List of planned features- clickif 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 newissue!Report a security bug!ContributingUNICORN Binance WebSocket APIis an open
source project which welcomes contributions which can be anything from simple documentation fixes and reporting dead links to new features. To
contribute followthis guide.ContributorsWeopen source!DisclaimerThis 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 / GeoblockingWe 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 SupportDo you need a developer, operator or consultant?Contact usfor a non-binding initial consultation!