- WebsocketsВ¶
- ThreadedWebsocketManager Websocket UsageВ¶
- BinanceSocketManager Websocket UsageВ¶
- Using a different TLDВ¶
- Websocket ErrorsВ¶
- Multiplex SocketВ¶
- Depth SocketВ¶
- Kline SocketВ¶
- Binance api websocket python
- Start Streaming Binance with Websockets in Python
- Sign up for Binance & Get API Keys
- Set up a Websocket Connection to Binance
- Make the Data Useful
- Perform Some Calculations on Real Time Data
- First lets determine how many bitcoins were exchanged per ETHBTC trade:
- Now lets make that time a little bit prettier:
- Lets find out if this was a buy or sell event:
- All Together
- A Better Way
- LiveDataFrame
- Binance api websocket python
- unicorn-binance-websocket-api 1.30.0
- Navigation
- Project links
- Statistics
- Maintainers
- Classifiers
- Project description
- UNICORN Binance WebSocket API
- Create a multiplex websocket connection to Binance with just 3 lines of code:
- And 4 more lines to print the receives:
- Convert received raw webstream data into well-formed Python dictionaries with UnicornFy:
- Subscribe / unsubscribe new markets and channels:
- Description
- What are the benefits of the UNICORN Binance WebSocket API?
- Live Demo
- Installation and Upgrade
- A wheel of the latest release with PIP from PyPI
- From source of the latest release with PIP from Github
- Linux, macOS, .
- Windows
- From the latest source (dev-stage) with PIP from Github
- Conda environment, Virtualenv or plain Python
- Change Log
- Documentation
- Examples
- Howto
- Project Homepage
- Social
- Receive Notifications
- How to report Bugs or suggest Improvements?
- Contributing
- Contributors
- Commercial Support
- Donate
WebsocketsВ¶
There are 2 ways to interact with websockets.
ThreadedWebsocketManager does not require asyncio programming, while BinanceSocketManager does.
ThreadedWebsocketManager function begin with start_ , e.g start_ticker_socket while BinanceSocketManager is simple ticker_socket
Multiple socket connections can be made through either manager.
Only one instance of each socket type will be created, i.e. only one BNBBTC Depth socket can be created and there can be both a BNBBTC Depth and a BNBBTC Trade socket open at once.
Messages are received as dictionary objects relating to the message formats defined in the Binance WebSocket API documentation.
Websockets are setup to reconnect with a maximum of 5 retries with an exponential backoff strategy.
ThreadedWebsocketManager Websocket UsageВ¶
Starting sockets on the ThreadedWebsocketManager requires a callback parameter, similar to old implementations of websockets on python-binance
ThreadedWebsocketManager takes similar parameters to the Client class as it creates an AsyncClient internally.
For authenticated streams api_key and api_stream are required.
As these use threads start() is required to be called before starting any sockets.
To keep the ThreadedWebsocketManager running using join() to join it to the main thread.
Stop Individual Stream
When starting a stream, a name for that stream will be returned. This can be used to stop that individual stream
Stop All Streams
Attempting to start a stream after stop is called will not work.
BinanceSocketManager Websocket UsageВ¶
Create the manager like so, passing an AsyncClient.
Set a custom timeout for the websocket connections
Manually enter and exit the Asynchronous context manager
Using a different TLDВ¶
The ThreadedWebsocketManager can take the tld when created if required.
The BinanceSocketManager uses the same tld value as the AsyncClient that is passed in. To use the вЂus’ tld we can do this.
Websocket ErrorsВ¶
If the websocket is disconnected and is unable to reconnect a message is sent to the callback to indicate this. The format is
Multiplex SocketВ¶
Create a socket combining multiple streams.
These streams can include the depth, kline, ticker and trade streams but not the user stream which requires extra authentication.
Symbols in socket name must be lowercase i.e bnbbtc @ aggTrade, neobtc @ ticker
Depth SocketВ¶
Depth sockets have an optional depth parameter to receive partial book rather than a diff response. By default this the diff response is returned. Valid depth values are 5, 10 and 20 and defined as enums.
Kline SocketВ¶
Kline sockets have an optional interval parameter. By default this is set to 1 minute. Valid interval values are defined as enums.
Источник
Binance api websocket python
There are 2 ways to interact with websockets.
ThreadedWebsocketManager does not require asyncio programming, while BinanceSocketManager does.
ThreadedWebsocketManager function begin with start_, e.g start_ticker_socket while BinanceSocketManager is simple ticker_socket
Multiple socket connections can be made through either manager.
Only one instance of each socket type will be created, i.e. only one BNBBTC Depth socket can be created and there can be both a BNBBTC Depth and a BNBBTC Trade socket open at once.
Messages are received as dictionary objects relating to the message formats defined in the Binance WebSocket API documentation.
Websockets are setup to reconnect with a maximum of 5 retries with an exponential backoff strategy.
ThreadedWebsocketManager Websocket Usage
Starting sockets on the ThreadedWebsocketManager requires a callback parameter, similar to old implementations of websockets on python-binance
ThreadedWebsocketManager takes similar parameters to the Client class as it creates an AsyncClient internally.
For authenticated streams api_key and api_stream are required.
As these use threads start() is required to be called before starting any sockets.
To keep the ThreadedWebsocketManager running using join() to join it to the main thread.
Stop Individual Stream
When starting a stream, a name for that stream will be returned. This can be used to stop that individual stream
Stop All Streams
Attempting to start a stream after stop is called will not work.
BinanceSocketManager Websocket Usage
Create the manager like so, passing an AsyncClient.
Set a custom timeout for the websocket connections
Manually enter and exit the Asynchronous context manager
Using a different TLD
The ThreadedWebsocketManager can take the tld when created if required.
The BinanceSocketManager uses the same tld value as the AsyncClient that is passed in. To use the ‘us’ tld we can do this.
If the websocket is disconnected and is unable to reconnect a message is sent to the callback to indicate this. The format is
Create a socket combining multiple streams.
These streams can include the depth, kline, ticker and trade streams but not the user stream which requires extra authentication.
Symbols in socket name must be lowercase i.e bnbbtc@aggTrade, neobtc@ticker
Depth sockets have an optional depth parameter to receive partial book rather than a diff response. By default this the diff response is returned. Valid depth values are 5, 10 and 20 and defined as enums.
Kline sockets have an optional interval parameter. By default this is set to 1 minute. Valid interval values are defined as enums.
Источник
Start Streaming Binance with Websockets in Python
Most exchanges provide a public websocket service that sends real-time market data to you. You can use this free service to automate trading or perform quick calculations that are not easy to perform on the exchange’s charts. This data arrives in massive amounts, sometimes making real-time processing of the data difficult.
In this tutorial, I will show you how to subscribe to a websocket on Binance, and then we will do some cool things with the stream.
What we will accomplish:
- Sign up for Binance and get your API key
- Set up a websocket connection to Binance
- Process the data into a useful form
- Perform some calculations on realtime data
- Look at a better way of accomplishing the same thing
Sign up for Binance & Get API Keys
The first step is to get yourself signed up on binance.
Once you have signed up, visit your account and click API Setting
Then, go ahead and name your API key. We’ll call it binance-websocket-tutorial for now. Because that is what this is, afterall.
After you verify, you will see a screen that has your API key and API Secret. You wont be able to see your secret key again, so make note of it.
Set up a Websocket Connection to Binance
Sammchardy on github has provided an amazing library to interface with Binance’s api. First you’re going to have to install the python-binance wrapper from github like so:
pip3 install python-binance
Sockets are handled through the BinanceSocketManager. It can handle multiple socket connections. When creating a socket connection, a callback function is passed which receives the messages. Lets jump right into an example. We are going to listen to the websocket for the symbol ETHBTC . We want to see every trades as it occurs, and we can do so using Binance’s trade socket. Use the following code sample:
Output:
Congratulations. You are new streaming cryptocurrency data!
Make the Data Useful
As you saw earlier, we were streaming real trades from Binance. But, we didn’t get the most useful data printing out. That is because our handle_message function was fairly simple. Let’s work on it a bit to create something more useful.
The trade socket returns a dictionary as specified in Binance’s official api documentation for every trade that occurs. We expect the payload to look like this:
In the event of an error, the BinanceSocketManager tries reconnecting a maximum of 5 times. If it fails to do so, we should expect a message like this:
With all of that in mind, let’s create a smarter callback function that will define what to do when we get a trade message. We will call it handle_message.
We will again specify that we want to listen to ETHBTC , and we want handle_message to deal with the trades as they come. Lets try this again.
Output:
Perform Some Calculations on Real Time Data
We can make our handle_message even smarter. Let’s say we were interested in how many bitcoins were exchanging hands per ETHBTC trade. We need to do a few things:
- Each trade has a price and a quantity. We can multiply that to get the amount of bitcoin traded.
- Since humans don’t respond with “1529616742353 milliseconds since Thursday, 1 January 1970” when asked for the time, we’ll make the time format human readable.
- It would also be useful to know if the trade was a buy or a sell.
First lets determine how many bitcoins were exchanged per ETHBTC trade:
If we run this again…
We run into the following error: builtins.TypeError: can’t multiply sequence by non-int of type ‘str’
This is a funny error. We would expect price and quantity to come back as numbers, but for some reason they are actually coming to us from BinanceSocketManager as strings. If you look at schema of the dictionary that is returned, you can see for yourself:
«q»: «100», // Quantity
I don’t know whose decision that was… but, it’s a good thing we caught that. Let’s try again by turning price and quantity into floats.
Output:
Now lets make that time a little bit prettier:
Output:
Lets find out if this was a buy or sell event:
In our dictionary, we are given a boolean if the buyer is the market maker.
«m»: true, // Is the buyer the market maker?
As a refresher, the market maker adds liquidity to the market. If the buyer is a market maker, it means that someone has bought the asset from at his or her price. Therefore, we can classify this as a ‘sell’ event.
All Together
Output:
A Better Way
What we did above was pretty cool. We subscribed to a stream of realtime trade data from binance, made it easy to read, and performed a simple calculation on it. But there was a lot of work that we had to do to get there. What if we had to do this for every exchange? A lot of time evaluating the market would be spent getting stuck on issues like dealing with numbers as strings, or cryptic ‘is buyer market maker’ type fields. Every exchange is different too.
We also need to keep in mind that we only start getting new trades. We don’t even have access to historical data yet for binance.
LiveDataFrame
The good news is, LiveDataFrame has taken care of that for you. It provides access to every coin on Binance (and other exchanges too!), with realtime updates of OHLC data with 5 second granularity. It also provides up to 4 hours of historical data for every coin!
Lets see how easy it is to start with LiveDataFrame. First, sign up and get your api keys.
Then pip install livedataframe to install the client and use the code below:
Output:
You can access a symbol that is trading on binance using the symbols dictionary. What you get is a DataFrame that is always up to date with the current OHLC data on binance. Not bad for 15 lines of code.
Lets look at last price and last trade quantity:
Output:
last_price | last_trade_qty | |
---|---|---|
2018-06-22 06:50:24+00:00 | 0.078322 | 0.055 |
Very easy to read isn’t it? Lets do some magic and watch this in real time:
Источник
Binance api websocket python
Python client for the Binance API.
Requires python 3.6 or greater.
First, enter your API key and secret into config.yaml. Then run the command below:
python setup.py test
Any log messages are written to tests/test.log .
To enter a pdb shell on a test failure, run
See the pytest docs for more information.
Enabling all tests
By default, tests that would change your account in any way, such as placing an order or withdrawing funds, are disabled. To enable them, edit pytest.ini by changing
then follow the instructions in tests/test_actions.py.
Enabling these tests means that your account balances will be changed if the tests are successful. Follow the configuration instructions very carefully. Failing to do so could result in the tests altering your account in a negative way.
Most client methods described below return objects that can be found in binance/storage.py. These objects convert values into their natives types, including:
- decimal strings to float
- timestamps to datetime.datetime
Each object accepts a raw API version of the object in its constructor. These objects also have a to_json() method that returns the object as a JSON-dumpable dictionary.
Methods with names ending with _async are asynchronous coroutines that perform the same action as their synchronous counterpart. (Read more about Python’s asynchronous features here.)
Источник
unicorn-binance-websocket-api 1.30.0
pip install unicorn-binance-websocket-api Copy PIP instructions
Released: Apr 13, 2021
An unofficial Python API to use the Binance Websocket API`s (com+testnet, com-margin+testnet, com-isolated_margin+testnet, com-futures+testnet, jersey, us, jex, dex/chain+testnet) in a easy, fast, flexible, robust and fully-featured way.
Navigation
Project links
- Homepage
- Author
- Wiki
- Documentation
- Howto
Statistics
View statistics for this project via Libraries.io, or by using our public dataset on Google BigQuery
License: MIT License (MIT License)
Author: Oliver Zehentleitner
Tags binance, asyncio, async, asynchronous, concurrent, websocket-api, webstream-api, binance-websocket, binance-webstream, webstream, websocket, api, binance-jersey, binance-dex, binance-futures, binance-margin
Requires: Python >=3.6.1
Maintainers
Classifiers
- Development Status
- 5 — Production/Stable
- Framework
- AsyncIO
- Intended Audience
- Developers
- Financial and Insurance Industry
- Information Technology
- Science/Research
- License
- OSI Approved :: MIT License
- Operating System
- OS Independent
- Programming Language
- Python :: 3.6
- Python :: 3.7
- Python :: 3.8
- Python :: 3.9
- Topic
- Office/Business :: Financial :: Investment
- Software Development :: Libraries :: Python Modules
Project description
UNICORN Binance WebSocket API
An unofficial Python API to use the Binance Websocket API`s (com+testnet, com-margin+testnet, com-isolated_margin+testnet, com-futures+testnet, jersey, us, tr, jex, dex/chain+testnet) in a easy, fast, flexible, robust and fully-featured way.
Create a multiplex websocket connection to Binance with just 3 lines of code:
And 4 more lines to print the receives:
Basically that’s it, but there are more options:
Convert received raw webstream data into well-formed Python dictionaries with UnicornFy:
Subscribe / unsubscribe new markets and channels:
This should be known by everyone using this lib: Do you want consistent data from binance?
Description
The Python module 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 Jersey, Binance US, Binance TR, Binance JEX, Binance DEX and Binance DEX Testnet and supports the streaming of all public streams like trade, kline, ticker, depth, bookTicker, forceOrder, compositeIndex and blockheight 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, www.binance.je, www.binance.us or www.jex.com — for the DEX you need a user address from www.binance.org or testnet.binance.org and you can get funds for the testnet.
Be aware that the Binance websocket API just offers to receive data. If you would like to set orders, withdraws and so on, you can to use the UNICORN Binance REST API in combination.
What are the benefits of the UNICORN Binance WebSocket API?
- Fully managed websockets and 100% auto-reconnect! Also handles maintenance windows!
- Supported exchanges:
Exchange | Exchange string |
---|---|
Binance | BinanceWebSocketApiManager(exchange=»binance.com») |
Binance Testnet | BinanceWebSocketApiManager(exchange=»binance.com-testnet») |
Binance Margin | BinanceWebSocketApiManager(exchange=»binance.com-margin») |
Binance Margin Testnet | BinanceWebSocketApiManager(exchange=»binance.com-margin-testnet») |
Binance Isolated Margin | BinanceWebSocketApiManager(exchange=»binance.com-isolated_margin») |
Binance Isolated Margin Testnet | BinanceWebSocketApiManager(exchange=»binance.com-isolated_margin-testnet») |
Binance Futures | BinanceWebSocketApiManager(exchange=»binance.com-futures») |
Binance Futures Testnet | BinanceWebSocketApiManager(exchange=»binance.com-futures-testnet») |
Binance Jersey | BinanceWebSocketApiManager(exchange=»binance.je») |
Binance US | BinanceWebSocketApiManager(exchange=»binance.us») |
Binance TR | BinanceWebSocketApiManager(exchange=»trbinance.com») |
Binance JEX | BinanceWebSocketApiManager(exchange=»jex.com») |
Binance DEX | BinanceWebSocketApiManager(exchange=»binance.org») |
Binance DEX Testnet | BinanceWebSocketApiManager(exchange=»binance.org-testnet») |
-
Streams are processing asynchronous/concurrent (Python asyncio) and each stream is started in a separate thread, so you dont need to deal with asyncio in your code!
No use of the twisted module, so you can use this lib in a daemonized application (compatible with python-daemon).
Supports subscribe/unsubscribe on all exchanges! (Take a look to the max supported subscriptions per stream in the endpoint configuration overview!)
UNICORN Binance WebSocket API respects Binance’s API guidelines and protects you from avoidable reconnects and bans.
Support for multiple private !userData streams with different api_key and api_secret . (example_multiple_userdata_streams.py)
Pick up the received data from the stream_buffer — if you can not store your data in cause of a temporary technical issue, you can kick back the data to the stream_buffer which stores the receives in the RAM till you are able to process the data in the normal way again. Learn more!
Use separate stream_buffers for specific streams or users!
Watch the stream_signal_buffer to receive CONNECT , DISCONNECT and FIRST_RECEIVED_DATA signals about the streams! Learn more!
Get the received data unchanged as received, as Python dictionary or converted with UnicornFy into well-formed Python dictionaries. Use the output parameter of create_stream() to control the output format.
Monitor the status of the created BinanceWebSocketApiManager() instance within your code with get_monitoring_status_plain() and specific streams with get_stream_info() .
Nice to use with iPython: «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 the Jupyter Notebook 🙂
Excessively tested on Linux, Mac and Windows
If you like the project, please it on GitHub!
Live Demo
This live demo script is streaming from binance.com!
(Refresh update once a minute!)
Installation and Upgrade
The module requires Python 3.6.1 or above, as it depends on Pythons latest asyncio features for asynchronous/concurrent processing.
The current dependencies are listed here.
If you run into errors during the installation take a look here.
A wheel of the latest release with PIP from PyPI
pip install unicorn-binance-websocket-api —upgrade
From source of the latest release with PIP from Github
Linux, macOS, .
pip install https://github.com/oliver-zehentleitner/unicorn-binance-websocket-api/archive/$(curl -s https://api.github.com/repos/oliver-zehentleitner/unicorn-binance-websocket-api/releases/latest | grep -oP ‘»tag_name»: «\K(.*)(?=»)’).tar.gz —upgrade
Windows
Use the below command with the version (such as 1.27.0) you determined here:
pip install https://github.com/oliver-zehentleitner/unicorn-binance-websocket-api/archive/1.27.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/oliver-zehentleitner/unicorn-binance-websocket-api/tarball/master —upgrade
Conda environment, Virtualenv or plain Python
Change Log
Documentation
Examples
Howto
Project Homepage
Social
Receive Notifications
To receive notifications on available updates you can the repository on GitHub, write your own script with using is_update_availabe() or you use the monitoring API service.
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 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 dont find an issue related to your topic, please open a new issue!
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
Commercial Support
Need a Python developer or consulting?
Contact me for a non-binding and free consultation via my company LUCIT from Vienna (Austria) or via Telegram.
Donate
Developing, documenting and testing the UNICORN Binance Suite and supporting the community takes a lot of time and time is a form of cost. I am extremely happy to do this, but need a solution for sharing the costs.
I think we are lucky, as our community consists of traders and programmers I expect to find mostly rational thinking people who also benefit financially from these libraries.
I would like to create a fair model for funding. My goals are that unicorn-binance-websocket-api, unicorn-binance-rest-api and unicorn-fy remain freely available as open source and that I am compensated at least to some extent and thus can invest my time more easily.
If you know the hooker principle from negotiation research or game theory, you know about the problem that people don’t often pay for something out of their own impulse if they have already received it for free.
So my idea is to give every donor who gives an amount over 50 EUR access to a private Github repository where Python classes for trading algos are provided (OrderBook, advanced stop-loss, . ). Moreover, maybe a nice ApiTrader community will be formed.
So the donor not only helps to push the open source development but also gets access to a well maintained collection of practical code for little money.
Furthermore community members can help me by donating own developments to make the unicorn-coding-club repository more attractive to create further incentives for new donors. This way we generate added value for all sides in an uncomplicated way.
Источник