How to Set up and Use Binance API with Python
Part I: A step by step tutorial to set up and use Binance API in Python to backtest strategies, plot data, or live trade using predefined rules.

- Introduction
- Create your Binance API Key
- Connect to Binance client using Python
- Use Binance API
- Get all coins prices
- Get historical prices
- Visualize Data
- Conclusion
Introduction
A Step by Step tutorial to set up and use Binance API in Python to backtest strategies, plot data, or live trade using predefined rules.
This part (Part I) will cover how to create API keys, connect to the Binance API and get the current price of the assets available to trade. We will also see how to have the historical data to later backtest strategies.
Part II will cover how to place a spot order and future order. How to close these trades and have information about them.
Part III will cover how to create a live stream data flow to be able to have each second the new live price of a specific asset.
Create Your Binance Key
Connect to Binance and go to API management to create a key pair:
And create your API key pair:
Select the options you want and the restriction you want to use. Be careful to not share your API keys especially if your key has future or withdrawn enabled.
The important information you will need is your API Keys and your secret Keys. These two will be used in our python program.
Connect to Binance Client Using Python
Now that you have your key, you are ready for the next steps.
To use and manage Binance API easily we will use a python library. Install it with the following command:
pip install python-binance#and then import it in your python file withfrom binance.client import ClientThen we will import the library to the python file and connect it to the Binance client.
To connect to the client just define your API and secret key variable and execute the client function.
from python-binance import Clientapi_key = "your api key"
api_secret = "your api secret key"client=Client(api_key,api_secret)To verify that your keys are correct and that you’re connected to Binance, execute this function that will ping the server.
If this returns an empty dictionary, this means that all is correct and that you are ready for the next steps.
print(client.ping())
#if it's return "{}" all is good, you're ready for next stepUsing Binance API
Now we are connected to a Binance client. So we could play a bit with the API to have data about a specific asset to backtest a strategy, or just execute some trades.
Here are some useful functions that you may frequently use.
Get all coins tickers and price
This function will return a list with all the coins available to trade on the platform with their price.
info = client.get_all_tickers()Example of output :
[{'symbol': 'ETHBTC', 'price': '0.07284200'}, {'symbol': 'LTCBTC', 'price': '0.00322200'}, {'symbol':'BNBBTC', 'price': '0.00885500'} ........]To work with this data we’ll use the python library pandas to stock these in a DataFrame. This will facilitate the manipulation.
Just install and import pandas in the python document with:
pip install pandasWe will just add a few lines of code to select the data type of the columns, and add an index in the DataFrame.
import pandas as pddf=pd.DataFrame(client.get_all_tickers())
df=df.set_index("symbol")
df["price"]=df["price"].astype("float")
df.index=df.index.astype("string")print(df)Here is the output table:
symbol priceETHBTC 0.073483
LTCBTC 0.003261
BNBBTC 0.008944
NEOBTC 0.000749
QTUMETH 0.003475
... ...
NUAUD 1.227500
NURUB 65.840000
REEFTRY 0.353900
REEFBIDR 521.200000
SHIBDOGE 0.000238To isolate a specific price for a precise asset just use:
print(df.loc["BTCUSDT])Output:
price 62228.99
Name: BTCUSDT, dtype: float64Get Historical Price
This function is crucial if you want to have the historic prices of a specific asset to backtest a strategy or just plot it on a graph. We will cover how to backtest strategy to find the best parameters in a future article.
To execute this function we will specify an asset, a start date, an end date, and a timeframe.
The timeframe will be the delta between the two price data.
import pandas as pdasset="BTCUSDT"
start="2021.10.1"
end="2021.11.1"
timeframe="1d"df =pd.DataFrame(assert,timeframe,start,end)This will return a table with all the data of the asset (BTC/USDT) between the 1st October 2021 and 1st November 2021 with a 1-day timeframe.
To clean a bit and have a nice Table I suggest adding these few lines. These will select the columns that are interesant in the DataFrame and convert the data in a readable format.
df= pd.DataFrame(client.get_historical_klines(asset, timeframe,start,end))df=df.iloc[:,:6]
df.columns=["Date","Open","High","Low","Close","Volume"]
df=df.set_index("Date")
df.index=pd.to_datetime(df.index,unit="ms")
df=df.astype("float")print(df)You have now a nice Table containing The Date, The Open price, High, Low, Close price and Volume executed. This data is crucial to make a strategy and calculate some technical indicators, we will use them in a near future.
Here is an example of the output :
Date Open High Low Close Volume2021-10-01 43820.01 48495.00 43283.03 48141.61 66244.874920
2021-10-02 48141.60 48336.59 47430.18 47634.90 30508.981310
2021-10-03 47634.89 49228.08 47088.00 48200.01 30825.056010
2021-10-04 48200.01 49536.12 46891.00 49224.94 46796.493720
2021-10-05 49224.93 51886.30 49022.40 51471.99 52125.667930
2021-10-06 51471.99 55750.00 50382.41 55315.00 79877.545181
2021-10-07 55315.00 55332.31 53357.00 53785.22 54917.377660
2021-10-08 53785.22 56100.00 53617.61 53951.43 46160.257850
2021-10-09 53955.67 55489.00 53661.67 54949.72 55177.080130Visualize the Data
If you want to easily visualize the DataFrame that you just recover from the Binance API, this is the easy way :
Install and import the mplfinance library :
pip install mplfinanceAnd then import it in your python code. Then you just have to plot the DataFrame using the mpl library to have a nice graph of the asset, if you would like to change the design of the graph just refer to the documentation of mplfinance library.
import mplfinance as mpl#Insert the code for the creation of the DataFrame that we see earliermpl.plot(df, type='candle')Here is the output and the beautiful graph:

In this option you can easily add some technical indicators like some simple moving average and the volume graph with:
mpl.plot(df, type='candle', volume=True, mav=7)
Conclusion
We have seen how to create API keys and connect to Binance API using Python.
We can now easily have the historical data of an asset to backtest a strategy, we will see how to do this in a future article.
Follow this guide to easily be able to create your trading bot.
Thanks for reading.
Learn more
How to Develop an Arbitrage Betting Bot Using Python

© All rights reserved, Siméon FEREZ
More content at plainenglish.io






