Master Binance API with Python (2024)

Are you tired of struggling to use the Binance API in Python? Do you feel like you’re missing something when using the python-binance library? If so, you’re not alone!

In this tutorial, we’ll take the frustration out of using the Binance API and show you step-by-step how to use the REST APIs, WebSockets, and even place orders. Plus, we’ll provide concrete examples to make it all easy to understand.

This is a long one, so don’t hesitate to use the table of contents to skip directly to what you’re interested in.

Say goodbye to the confusing documentation and hello to confident Binance API usage with us guiding you through it all. You can even follow along with the Binance API Python Tutorial Jupyter Notebook.

What Is Binance?

Binance is an online exchange for cryptocurrency trading. It also provides electronic wallets for storing cryptocurrencies. Binance is the world’s largest cryptocurrency exchange in terms of daily trading volume.

Changpeng Zhao founded Binance in 2017, and it is registered in the Cayman Islands.

Binance.us is a sister company to Binance, built as a separate exchange in 2019 due to a regulatory ban on Binance in the USA. This independent structure of two exchanges allows Binance to access the US market. 

What Is the Binance API?

Binance API is a set of REST API calls that let users access Binance endpoints in Python or other programming languages. With the Binance API, you can develop customized trading bots and cryptocurrency applications and thus automate your crypto trading. 

Binance Pros and Cons

Pros

  • Binance provides a wide choice of cryptocurrencies.
  • Binance commission rates are low due to high liquidity and trading volumes.
  • A proprietary cold wallet ensures the security of your cryptocurrencies.
  • Free API lets users automate their trading tasks.

Cons

  • Binance has a very complex registration procedure that requires identity verification.
  • None of the regulators licenses Binance
  • The mechanism for calculating the commission is not transparent.
  • Users complain about technical issues with Binance servers.

Binance API Pricing Plans

The official Binance API is free to use. Access to various endpoints depends upon your Binance account type. For instance, you can only access margin trading account endpoints if you have a margin trading account.

Binance API allows 1200 request weights per minute, 50 orders per 10 seconds, and 160,000 orders per 24 hours. See the official documentation for API request limits

How to Get Started with Binance API in Python?

There are a couple of options to access the Binance API. 

  1. By creating a live Binance trading account.
  2. By creating a Binance Spot Test Network account.

Creating A Live Binance Trading Account

The first step is to sign up for a Binance trading account. If you live in the US, you must sign up with Binance.us.

After registration, you receive a verification email. Click on the verification link to verify your account.

Log in to your Binance API account again and verify your identity. You must provide a valid identity document, e.g., an identity card, passport, or a driving license to verify your identity. In addition, you also have to take a photograph via your computer’s webcam or a mobile camera.

You will need an API key and API secret to access Binance API. To get the API key and secret Key, click on your profile icon from the top-right corner of the Binance dashboard. Click “API Management” from the dropdown list. 

Click the “Create API” button.

Binance Create API

Enter the label for your API Key, and click the “Next” button.

Binance API Label API Key

You must enable two-factor authentication with the Google Authenticator or similar 2FA app, or your phone number.

Once you enable two-factor authentication, you will see your API key, API Secret, and base URL for the REST API. Store these keys in a safe place. Once you refresh the page, you will never be able to see these keys again. You can create multiple API Keys if you want. 

The process for generating an API key for Binance US is similar. Log in to your Binance US account. Click your profile icon, select “API Management” from the dropdown list, and follow the same process as you did while generating an API key for Binance.com.

You will only be able to generate an API key if you have a minimum of $15 in your spot wallet. You will see the following message if you need more funds in your spot wallet. 

Binance API Spot Deposit Message

Create a Demo Binance Trading Account

If you want to try the Binance API endpoints before live trading, you can create a Binance Spot Test Network account. 

Currently, the only way to access the Binance Spot Test Network is via your GitHub account integration with Spot Test Network. Click the “Log In with GitHub” link in the following screenshot.

Binance API Demo Spot Test Network Account

Click the “Authorize binance-exchange” button on the following page.

Finally, click the “Generate HMAC_SHA256 Key” link to generate your Spot Test Network API keys. 

Binance API Spot Test Network API Key

Simple Example Fetching Data Using Binance API in Python

You can use a third-party Python library or the Python requests module to fetch data from the Binance API. 

Binance API Python Library Example

Several third-party libraries are available for the Binance API; the most widely used is python-binance. Binance held a contest in 2017 for the best client libraries for different languages. The python-binance library won that contest. 

The following script installs the python-binance library. 

pip install python-binance

The Client class from the binance.client module contains methods that call the Binance API. If you’re not familiar with how to do that, read my tutorial on how to use dotenv files.

import pandas as pd
from dotenv import load_dotenv
load_dotenv() # read from local .env file

Let’s also import Pandas and our API keys from our local environment variables.

The script below imports the Client class. You must create an object of the Client class and pass it your API key and secret. 

If you are using the Binance Spot Test Network for testing Binance API calls, you must pass True as the value for the testnet attribute of the Client class. In addition, you need to assign the API URL of the Spot Test Network to the API_URL attribute of the Client class. 

import os
from binance.client import Client

# Test 
api_key = os.environ['BINANCE_API_KEY_TEST']
api_secret = os.environ['BINANCE_API_SECRET_TEST']
client = Client(api_key, api_secret, testnet=True)

# Live trading
#api_key = os.environ['BINANCE_API_KEY_LIVE']
#api_secret = os.environ['BINANCE_API_SECRET_LIVE']
#client = Client(api_key, api_secret)

US users accessing the Binance.us endpoints must pass us as the value for the tld parameter of the Client class, as shown below:

client = Client(api_key, api_secret, tld='us')

Once you initialize the Client class object, you can use a class method to call any Binance API endpoint. For instance, in the script below, the `get_all_tickers()` method returns Binance ticker prices. 

tickers = client.get_all_tickers()
tickers
Binance API Python Biance Get All Tickers List

Convert the Binance API method response to a Pandas dataframe to improve readability:

import pandas as pd
df = pd.DataFrame(tickers)
df.head()
Binance API Python Requests Get All Tickers DataFrame

Binance API Requests Module Example

Use the Python requests module to call Binance API endpoints if you are looking for a speedy response. In addition, third-party libraries do not immediately update with the REST API changes. You can use the Python requests module if a third-party library doesn’t have the functionality you need.  

The base URLs for  Binance and Binance US API endpoints are as follows:

BinanceBinance.US
Base URLhttps://api1.binance.comhttps://api.binance.us

The following script uses the Python requests module to fetch ticker prices from the Python Binance API. Notice the API call to retrieve ticker prices is ‘/api/v3/ticker/price’. 

import requests
from requests.exceptions import ConnectionError, Timeout, TooManyRedirects
import json
import os

api_key = os.environ['BINANCE_API_KEY_TEST']
api_secret = os.environ['BINANCE_API_SECRET_TEST']

url = 'https://api1.binance.com'
# url = https://api.binance.us # for US users

api_call = '/api/v3/ticker/price'

headers = {'content-type': 'application/json', 
           'X-MBX-APIKEY': api_key}

response = requests.get(url + api_call, headers=headers)

response = json.loads(response.text)
df = pd.DataFrame.from_records(response)
df.head()
Binance API Python Binance Get All Tickers DataFrame

See the official Binance API documentation for other REST API endpoints.  

What are Binance API Endpoints?

Binance groups its endpoints into the following main categories:

  • General Endpoints
  • Market Data Endpoints
  • Account Endpoints
  • Sub Account Endpoints
  • Margin Trading Endpoints

The following sections explain how to call some of the most common functions from these endpoints.

General Endpoint

The general endpoint functions allow users to perform some of the most frequent Binance API tasks, e.g., get server time and status, ticker prices, exchange and symbol information, etc. 

Get Binance Server Time and Status

The ping() method from the Client class tells if the Binance server is up and running. 

print(client.ping()) # Empty response means no errors

An empty response or no error means the server is running. 

To get the Binance API server time, you can use the get_server_time() method. 

import datetime
res = client.get_server_time()
print(res)

The Binance API returns a timestamp in UNIX format, as shown in the output below. 

{'serverTime': 1665955501799}

The following Python script converts the UNIX time format into ISO standard date time format. 

import datetime
your_dt = datetime.datetime.fromtimestamp(int(time_res['serverTime'])/1000) print(your_dt.strftime("%Y-%m-%d %H:%M:%S"))
2022-10-16 23:25:01

Get All Binance Coins Info

If you are interested in finding out the current trading price of a Binance cryptocurrency symbol, use the get_all_tickers() method:

coin_info = client.get_all_tickers()
df = pd.DataFrame(coin_info)
df.head()
Binance API Python Binance Get All Tickers DataFrame

Get Binance Exchange and Symbol Info

You can get general information about the Binance exchange using the get_exchange_info() method. In the response, you will see the time zone info, server time, symbols, etc. 

exchange_info = client.get_exchange_info()
exchange_info.keys()
dict_keys(['timezone', 'serverTime', 'rateLimits', 'exchangeFilters', 'symbols'])

Use a dictionary key to get information about one of the entities mentioned above. For instance, the script below returns details of all the symbols on the Binance exchange: 

df = pd.DataFrame(exchange_info['symbols'])
df

You can get detailed information about a symbol using the get_symbol_info() method. The method returns information such as quote precision:

exchange_info_symbol = client.get_symbol_info('BTCBUSD')
exchange_info_symbol
Binance API Python Binance Module Get Symbol Info for BTCUSD Dictionary

Market Data End Point

Get Market Depth 

The market depth of a symbol refers to orders asking and bid prices at a certain point. An order book lists market depth. 

With python-binance client, you can retrieve the market depth of a symbol via the get_order_book() method. 

arket_depth = client.get_order_book(symbol='BTCBUSD')
print(market_depth.keys())
print(market_depth)
Binance API Python Module Get Order Book for BTCUSD Dictionary

We can create a dataframe to visualize this data more easily.

bids = pd.DataFrame(market_depth['bids'])
bids.columns = ['price', 'bids']
asks = pd.DataFrame(market_depth['asks'])
asks.columns = ['price', 'asks']
df = pd.concat([bids,asks]).fillna(0)
df
Binance API Bid Ask Spread DataFrame

Get Binance Recent Trades

The get_recent_trades() method returns information about a symbol’s recent 500 trades. The method returns information such as the bid price, quantity, time of the trade, etc.

recent_trades = client.get_recent_trades(symbol='BTCBUSD')

df = pd.DataFrame(recent_trades)
df.head()
Binance API Python Binance Get Recent Trades for BTCUSD DataFrame

Get Historical Trades on Binance

The get_historical_trades()  method returns historical data for a symbol’s trade. 

If you do not pass a trade id value to the fromid attribute of the get_historical_trades() method, the method will return the most recent trades.

id = df.loc[499,'id']
historical_trades = client.get_historical_trades(symbol='BTCBUSD', limit=1000, fromId=id)
df = pd.DataFrame(historical_trades)
df.head()
Binance API Python Module Get Historial Trades for BTCUSD DataFrame

Get Binance Average Symbol Price

You can get the average price of a symbol using the get_avg_price() method over a period. 

avg_price = client.get_avg_price(symbol='BTCBUSD')
avg_price
{'mins': 5, 'price': '19321.59434215'}

Get All Binance Tickers Prices

You can get different types of price information, such as price change, percentage price change, previous closing price, last price, etc., of a symbol using the get_tickers() method. 

tickers = client.get_ticker()
df = pd.DataFrame(tickers)
df
Binance API Python Binance Get Tickers DataFarme

Account and Sub-Account Endpoints

Using the account and sub-account endpoints, you can get information about your assets, trades, orders, etc. 

Account Endpoint

Get Binance Account Info

The get_account() method returns general information about your Binance account, e.g., the type of your account, assets you hold, etc. 

info = client.get_account()
info
Binance API Python Binance Module Get Account Dictionary

Get Binance Asset Details

You can retrieve details of all account assets using the get_asset_details() method. You will see the withdrawal fee, minimum withdrawal amount, withdrawal status, etc., of all your account assets.  You’ll get an error if using a test account.

details = client.get_asset_details()
df = pd.DataFrame(details)
df.T
Binance API Python Binance Module Get Asset Details DataFrame

You can get the balance of an account asset using the get_asset_balance() method. The asset symbol is passed as a parameter to the method, as shown in the script below:

asset_balance = client.get_asset_balance(asset='ETH')
asset_balance

Get Asset Dividend History

Finally, to get the dividend history of all your account assets, you can call the get_asset_dividend_history().

div_history = client.get_asset_dividend_history()
div_history

Get Binance Trades

You can retrieve information about your trades for a particular symbol using the get_my_trades() method:

trades = client.get_my_trades(symbol='BTCBUSD')
trades

Order Endpoint

The order endpoint contains functions to fetch your orders, create a new order, check order status, cancel an order, etc. 

Fetch All Binance Orders

To fetch all your Binance selling or buying orders for a symbol, you can use the get_all_orders() method. 

orders = client.get_all_orders(symbol='BTCBUSD', limit=10)
orders

Place Binance Order

Placing a new binance order via the Python API can be tricky initially. The python-binance library contains the  create_test_order() method that lets you test if your order meets the required criteria for being placed on the Binance exchange. Once you test your order, you can call the create_order() method to place an order. 

As an example, the following script places a market-type buying order for the BTCUSD symbol. 

buy_order = client.create_test_order(symbol='BTCBUSD', 
                                     side='BUY', 
                                     type='MARKET', 
                                     quantity=0.0005
                                    )

Once you execute the above script, you will see the following error.

Binance API Create Order BTCUSD MIN_NOTIONAL error

The error says that the order failed the MIN_NOTIONAL filter. You can only place an order if it passes all the filters. See the details of different types of Binance order filters

To get symbol values for a specific filter, you can use the get_symbol_info() method. 

info = client.get_symbol_info('BTCBUSD')
print(info)

In the output, you will see various filter values. For instance, in the output below, you can see that the LOT_SIZE for BTCUSD it’s 0.00000100 and the MIN_NOTIONAL is 10.

Binance Python API Get Symbol Info for BTCUSD Dict

To get a better view, you can display all filter values in a Pandas dataframe using the following script.

import pandas as pd
new = pd.DataFrame.from_dict(info['filters'])
new.head()

## filter details
## https://binance-docs.github.io/apidocs/spot/en/#filters
Binance API Get Symbol Info Filters for BTCUSD Dataframe

Let’s determine the value of our prior test order.

coin_info = client.get_all_tickers()
df = pd.DataFrame(coin_info)
df = df[df['symbol']== 'BTCBUSD']
df['price'] = df['price'].astype(float)
price = df['price'].values[0]

The price * 0.0005, our previous order amount, is 8.38. This is less than our MIN_NOTIONAL, which is why it failed. If you run into a lot size or any other error when creating orders, the filters will be your guide.

Let’s resolve our issue and buy 0.005 BTCBUSD.

buy_order = client.create_test_order(symbol='BTCBUSD', 
                                     side='BUY', 
                                     type='MARKET', 
                                     quantity=0.005,
                                   )

Once you validate your test order, you can place an actual order using the create_order() method, as shown in the following script:

order = client.order_market_buy(
    symbol='BTCBUSD',
    quantity=0.005)
print(order)
{'symbol': 'BTCBUSD',
 'orderId': 3449170,
 'orderListId': -1,
 'clientOrderId': 'axX2osoSaNsPQ8V2WYVX5X',
 'price': '0.00000000',
 'origQty': '0.00500000',
 'executedQty': '0.00500000',
 'cummulativeQuoteQty': '83.93500000',
 'status': 'FILLED',
 'timeInForce': 'GTC',
 'type': 'MARKET',
 'side': 'BUY',
 'stopPrice': '0.00000000',
 'icebergQty': '0.00000000',
 'time': 1671657526062,
 'updateTime': 1671657526062,
 'isWorking': True,
 'workingTime': 1671657526062,
 'origQuoteOrderQty': '0.00000000',
 'selfTradePreventionMode': 'NONE'}

Following are some other methods that let you place a specific type of order. 

  • order_limit_buy()
  • order_limit_sell()
  • order_market_buy()
  • order_market_sell()
  • order_oco_buy()
  • order_oco_sell()

Check Binance Order Status

You can check the current status of the order you placed using the get_order() method. You must pass your order’s symbol and id as parameter values to the get_order() method. 

order = client.get_order(    symbol='AGIXBUSD',
    orderId='your_order_id')

Cancel Binance Order

Finally, as the following script demonstrates, you can cancel your Binance order using the cancel_order() method. 

order = client.cancel_order( symbol='AGIXBUSD',
    orderId='your_order_id')

Get Binance Sub Account List

Binance allows its corporate and VIP individual users to create sub-accounts. With sub-accounts, users can divide responsibilities and manage transactions in a more organized manner. 

You can get a list of all your sub-accounts using the get_sub_account_list() method, as shown in the following script:

## Functionality only available for Corporate and VIP Individual Users
accounts = client.get_sub_account_list()
print(accounts)
## Functionality only available for Corporate and VIP Individual Usersaccounts = client.get_sub_account_list()print(accounts)

Margin Trading Endpoints

Binance margin trading endpoints allow you to perform various margin trading tasks. In simplest terms, margin trading refers to buying and selling stocks using borrowed money. 

To access Binance margin trading endpoints, you must create a margin trading account with Binance. 

You can create a cross-margin trading account or an isolated margin trading account. In cross-margin trading, all your margin accounts share risk. On the contrary, in isolated margin trading, the risk margin is independent for each trading pair.

Binance Margin Trading Accounts Endpoint

Binance margin trading account endpoints allow you to create cross-margin and isolated margin trading accounts and get various information about your margin trading account.

Get Cross-Margin Account

You can create a cross-margin trading account through your Binance dashboard. 

Once you create your cross-margin account, you can get general information about the account using the  get_margin_account() method.

margin_account_info = client.get_margin_account()
margin_account_info

Create an Isolated Margin Account

You can create an isolated margin trading account using the create_isolated_margin_account() method of the python-binance library. You must pass base and quote asset values for your isolated margin trading account. 

account = client.create_isolated_margin_account(base='BTC', quote='ETH')

Get Isolated Margin Account Info

You can retrieve details of your isolated margin trading account using the get_isolated_margin_account() method. 

info = client.get_isolated_margin_account()
info
{'assets': [], 'totalAssetOfBtc': '0', 'totalLiabilityOfBtc': '0', 'totalNetAssetOfBtc': '0'}

Binance Margin Trading Market Data Endpoint

Get Cross-Margin Asset Info

The get_margin_asset() method returns details of an asset you can buy or sell via margin trading. Here is an example:

asset_info = client.get_margin_asset(asset='ETH')
asset_info
{'assetName': 'ETH', 'assetFullName': 'Etherum', 'isBorrowable': True, 'isMortgageable': True, 'userMinBorrow': '0', 'userMinRepay': '0'}

Get Cross-Margin Symbol Info

Similarly, you can use the get_margin_symbol() method to get information about if you can trade a symbol via margin trading. Here is an example:

symbol_info = client.get_margin_symbol(symbol='ETHBTC')
symbol_info
{'id': 351638524530850581, 'symbol': 'ETHBTC', 'base': 'ETH', 'quote': 'BTC', 'isMarginTrade': True, 'isBuyAllowed': True, 'isSellAllowed': True}

Binance Margin-Trading Orders Endpoint

The python-binance library also provides functions for placing margin trading orders. By default, these endpoints functions create orders using your cross-margin account. For an isolated margin account, you must pass True as the value for the isolated parameter.

Fetch All Margin Trading Orders

The get_all_margin_orders() method returns all your orders involved in margin trading.  

orders = client.get_all_margin_orders(symbol='ETHBTC', limit=10)

Place a Margin Trading Order

You can place a margin trading order using the create_margin_order() method. The syntax is similar to creating simple Binance orders, as shown below:

from binance.enums import order = client.create_margin_order(    symbol='ETHBTC',    side=SIDE_BUY,    type=ORDER_TYPE_LIMIT,    timeInForce=TIME_IN_FORCE_GTC,    quantity=100,    price='0.0001')
from binance.enums import *
order = client.create_margin_order(
symbol=’ETHBTC’,
side=SIDE_BUY, 
type=ORDER_TYPE_LIMIT,
timeInForce=TIME_IN_FORCE_GTC,
quantity=100,
price=’0.0001′)

Check Margin Trading Order Status

Similarly, you can use the get_margin_order() method to find the status of your margin trading order. 

order = client.get_margin_order(
    symbol='AGIXBUSD', 
    orderId='your_order_id')

Cancel a Margin Trading Order 

Finally, you can cancel your margin trading order using the cancel_margin_order() method. 

result = client.cancel_margin_order(
    symbol='AGIXBUSD',
    orderId='your_order_id')

Binance Loans Endpoint

Binance loans endpoints allow you to borrow and repay Binance margin trading loans.

Create Loan

The create_margin_loan() method allows you to borrow a loan for margin trading. For instance, the following script creates a margin loan of quantity 1.1 for Ethereum. 

transaction = client.create_margin_loan(asset='ETH', amount='1.1')

Repay Loan

To repay a loan, you can use the repay_margin_loan() method, as demonstrated in the following script:

transaction = client.repay_margin_loan(asset='ETH', amount='1.1')

Get Loan Details

Finally, to get details of a borrowed or repaid loan, you can use the get_margin_loan_details() method. You must pass the asset’s name and the transaction id to the get_margin_loan_details() method. 

details = client.get_margin_loan_details(asset='BTC', txId='100001')

Get Binance All Margin Trades

Finally, you can retrieve  information about your margin trades for a particular symbol using the get_margin_trades method, as shown in the following example:

trades = client.get_margin_trades(symbol='BTCBUSD')

Working with Binance WebSockets

Installing WebSockets Library

The python-binance library contains ThreadedWebSocketManager class, which you can use to retrieve streaming data from the Binance API. I ran into an issue while using the ThreadedWebSocketManager class. After a bit of research, I found that the issue is due to a bug in the API. 

You can use the Python WebSockets library to retrieve streaming data from Binance. The websockets library is not specifically designed for Binance API. You can use the websockets library to retrieve streaming data via WebSockets from any API.  

You can install the websockets library via the following pip command.

pip install websocket-client

Now let’s import the required libraries.

import json
import websocket
import pandas as pd

Retrieving Streaming Data from Binance

The Binance API also offers streaming data via WebSockets. As per the official documentation, you can use WebSockets to retrieve streaming data via the following base endpoints:

  • wss://stream.binance.com:9443 
  • wss://stream.binance.com:443

You must append the URL of the raw stream that you want to retrieve with the base endpoint URL. Your final URL should look like this:

 wss://stream.binance.com:9443//ws/<streamName>

If you go to the official documentation, you can see the raw URL for various streams. For example, the raw stream for the latest trade is <symbol>@trade.

The final URL for retrieving the latest trades via WebSockets will be as follows: 

 wss://stream.binance.com:9443//ws/<symbol>@trade

Here you need to replace the symbol value with the ticker, e.g., “btcusdt.”

Let’s see an example.

Binance WebSockets Streaming Prices

symbol = 'btcusdt'
socket = f'wss://stream.binance.com:9443/ws/{symbol}@trade'

We also need to define the functions for the websocket client.

def on_message(ws, message):
    print(message)

def on_error(ws, error):
    print(error)

def on_close(ws, close_status_code, close_msg):
    print("### closed ###")

def on_open(ws):
    print("Opened connection")

ws = websocket.WebSocketApp(socket,
                              on_open=on_open,
                              on_message=on_message,
                              on_error=on_error,
                              on_close=on_close)

With the socket set and the functions created, let’s run this thing forever… or at least until we escape it.

ws.run_forever()

Here is the output of the above script:

Binance API WebStocks BTCUSD Streaming Output Json

This is great, but it’s not easy to see. Let’s convert this to a dataframe.

df = pd.DataFrame()

def on_message(ws, message):
    msg = json.loads(message)
    d = [(msg['T'], msg['p'])]
    global df
    df = pd.concat([df, pd.DataFrame.from_records(d)])
    
def on_error(ws, error):
    print(error)

def on_close(ws, close_status_code, close_msg):
    df.columns = ['time', 'price']
    df['time'] = pd.to_datetime(df['time'], unit='ms')
    df.set_index(df['time'], inplace=True)
    df.drop(columns='time', inplace=True)
    print("### closed ###")
    print(df)

def on_open(ws):
    print("Opened connection")

ws = websocket.WebSocketApp(socket,
                              on_open=on_open,
                              on_message=on_message,
                              on_error=on_error,
                              on_close=on_close)
ws.run_forever()
Binance API WebSockets BTCUSD Price Dataframe

Binance WebSockets Candlesticks (Kline)

Most technical analysts use candlesticks to trade. Let’s create 1-minute bars with the kline stream.

symbol = 'ethusdt'
socket = f'wss://stream.binance.com:9443/ws/{symbol}@kline_1m'

We’ll add the OHLCV values to a list, and on close we’ll add it to a dataframe.

t, o, h, l, c, v = [], [], [], [], [],  []

def on_message(ws, message):
    msg = json.loads(message)
    bar = msg['k']
    if bar['x'] == False:
        t.append(bar['t'])
        o.append(bar['o'])
        h.append(bar['h'])
        l.append(bar['l'])
        c.append(bar['c'])
        v.append(bar['v'])
        
def on_error(ws, error):
    print(error)

def on_close(ws, close_status_code, close_msg):
    print("### closed ###")
    global df
    bars = {'time':t, 'open':o, 'high':h, 'low':l, 'close':c, 'volume':v}
    df = pd.DataFrame.from_dict(bars)
    df.set_index('time', inplace=True)
    print(df)

def on_open(ws):
    print("Opened connection")

ws = websocket.WebSocketApp(socket,
                              on_open=on_open,
                              on_message=on_message,
                              on_error=on_error,
                              on_close=on_close)
ws.run_forever()
Binance API Python WebSockets Kline of BTCUSD Dataframe

Common Errors and Issues Accessing Binance API

Server Time Synchronization Error

You might get a server time error while accessing Binance server time. For instance, executing the following script on a Windows machine returned an error for me:

time_res = client.get_server_time()
time_res
"BinanceAPIException: APIError(code=-1021): Timestamp for this request was 1000ms ahead of the server's time."

You can solve this error by going to Windows -> Setting-> Time & Language -> Date & Time -> ‘Sync Now’, as shown in the following screenshot:

Binance API Sync Time Resolution

Invalid API Key Error

Another common error you will likely encounter is the Invalid API-Key error. For instance, executing the following script using the Binance Spot Test Network returns an invalid key error:

historical_trades = client.get_historical_trades(symbol='BTCBUSD')
df = pd.DataFrame(historical_trades)
df.shape
BinanceAPIException: APIError(code=-2015): Invalid API-key, IP, or permissions for action.

This error usually occurs when you access Binance sapi/wapi endpoints via the Spot Test Network, as the Spot Test Network does not support these endpoints. 

To see if a method calls a sapi/wapi endpoint, click the method name from the python-binance API; you will see the underlying REST API call. You can see from the REST API call if the method calls a sapi/wapi endpoint.

Binance API SAPI WAPI Calls

 You can access these endpoints only through a live Binance trading account. 

Binance Alternatives

Following are some alternatives to Binance:

Frequently Asked Questions

Is Python-Binance API Safe?

Synk.io security scan of the python-Binance API reveals one vulnerability or license issue with the python-binance API. The overall health score of the library is 68/100. The library is generally considered secure as users do not report any security breaches. 

Can I Share My Binance API Key?

Binance recommends that you never share your API key or secret with anyone. 

Does Binance Provide Private Keys?

Binance is a centralized exchange and doesn’t provide its users with a private key. 

What Clients Are Available for Binance API?

Apart from Python, Binance clients are available in the Java, PHP, Node, .NET and Go programming languages.

How to Delete My Binance API Key

Binance API Delete API Key

To delete a Binance API key, go to your dashboard, click your profile icon from the top-right corner and click “API Management”. A list of your API Keys will appear. Click the “Delete” button for the API Key you want to delete.

The Bottom Line

With the largest daily trading volume, Binance is the world’s leading cryptocurrency exchange allowing you to buy and sell the most commonly traded cryptocurrencies. Binance’s secure cold wallet ensures the security and safety of your crypto data. In addition to an easy-to-use GUI interface, Binance offers a rich REST API. 

In this article, you saw some options to connect to the Binance API via the Python programming language. The information in this tutorial can help you develop cryptocurrency software and automate your Binance trading tasks using a trading bot. Moreover, machine learning and data science researchers can leverage the python-binance API for financial data research.

Leave a Comment