Extracting Real-Time Order Book Data Using Python-Binance
It is important for a bot to analyze real-time order book data to make informed decisions. In this article, we will look at how to extract variables from the Binance API real-time order book using the python-binance library.
Prerequisites
- Install the required libraries: “python-binance”, “pandas” and “numpy”
- Set up Binance API credentials
- Run the script locally or use the CLI tool “binance-api-client”
Code
Import pandas as pd
from binance.client import client
Import JSON

Set up Binance API credentialsAPI_KEY = 'YOUR_API_KEY'
API_SECRET = 'YOUR_API_SECRET'
Create an instance of the Binance clientClient = Client(API key=API KEY, API secret=API SECRET)
def get_order_book(symbol):
Get the order book for the given symboldepth = Client.get_order_book(symbol=symbol)
Extract bids and ASCII as dictionariesbids = {k: v['bids'] for k, v in depth['bids'].items()}
asks = {k: v['asks'] for k, v in depth['asks'].items()}
Output the extracted dataprint(pd.DataFrame(list(bids.items()), columns=['symbol', 'bidprice']))
print(pd.DataFrame(list(asks.items()), columns=['symbol', 'askprice']))
Usage exampleget_order_book('BTCUSDT')
Explanation
- We set up our Binance API credentials using the binance-api-client CLI tool.
- We create an instance of the Binance client using our API credentials.
- The get_order_book() function retrieves the order book for the specified symbol (“symbol”) from the Binance API.
- We extract bids and asks as dictionaries using dictionary comprehension.
- Finally, we output the extracted data to a Pandas DataFrame.
Sample Output
Symbol Bid Price
0 BTCUSDT 34657.7
1 BTCUSDT 34658.8
Symbol Ask Price
0 BTCUSDT 34656.2
1 BTCUSDT 34659.5
Note: Output may vary based on real-time order book data.
Tips and Variations
- To extract variables other than bids and offers, you can change the dictionary comprehension to suit your needs.
- If you need to process additional data from the API, such as candlestick prices or chart data, be sure to check the Binance API documentation.
- Be aware of the API’s speed limitations and usage recommendations when collecting order book data for live trading.
I hope this article helps you extract valuable data from orders for real trading on Binance!