Binance is one of the largest cryptocurrency exchanges supporting multiple cryptocurrencies. Some of the cryptocurrencies on Binance include Bitcoin, Ethereum, Dogecoin, Litecoin, etc. Binance owns its native cryptocurrency called Binance coin(BNB).
For trading on Binance, there is a need to interact with the Binance exchange. The Binance exchange server has support for both RESTful and Web-socket APIs for trading. As a developer, using these direct APIs is a bit cumbersome and not user-friendly.
Here is where the python-binance client APIs come to the rescue. It acts as an abstraction layer and provides a clean python interface, thus relieving us from the nitty-gritty details of Binance. In this post, we will explore how to use the python-binance package.
Table of Contents
Installation and Initialisation
The documentation of python-binance is available here: Welcome to python-binance v1.0.12 — python-binance 0.2.0 documentation. To install python-binance, assuming you have python3 installed, type this on the terminal.
pip install python-binance
To initialize python-binance, first create an account with Binance exchange for actual cryptocurrency trading here Binance: Bitcoin Exchange | Cryptocurrency Exchange OR Binance Testnet for virtual(fake) currency trading here Binance Testnet. After account creation, it is vital to create an API key and API secret for your account. Jot down the same on a text pad or some piece of paper.
PS: If you are a novice, advice is to use Binance Testnet to try out crypto trading so that you are risk-averse!
# INITIALISE # for synchronous client from binance.client import Client client = Client(api_key, api_secret) # for asynchronous client async def main(): # initialise the client client = await AsyncClient.create(api_key, api_secret) if __name__ == "__main__": loop = asyncio.get_event_loop() loop.run_until_complete(main())
Pass the api_key and api_secret parameters that you noted previously.
The Binance market supports the Spot, Futures, and Margin trading options. They are described in brief.
In the spot market, trading happens on the spot (i.e., current price). Here you execute the trade immediately for buying or selling. To instantly buy or sell, you need to have available assets to pay in your account. e.g., if you buy $1000 of bitcoin, you must have $1000 in your account.
In the futures market, you agree on a contract at a set price for a later date. The seller will sell, or the buyer will buy the cryptocurrency at this price, on this date, irrespective of the market price on that particular agreed date.
In the margin market, which is buying on a margin involves borrowing money from an exchange, in this case, Binance. You borrow the funds for trading now and then pay them back later. With borrowing, the buying power increases.
To interact with the Binance exchange, there are some generic APIs available. These API methods return a dictionary of the JSON response. There is also support for both Sync and Async APIs. It is not possible to mention all the APIs as it is covered in the documentation, however below are some of the important APIs, that are frequently used for trading or bot design.
# For spot trading res = client.get_exchange_info() # Return rate limits and list of symbols res = client.get_symbol_info(symbol) # Return information about a symbol res = client.get_symbol_ticker(**params) # Latest price for a symbol or symbols res = client.get_account(**params) # Get current account information res = client.get_asset_balance(asset, **params) # Get current asset balance res = client.get_avg_price(**params) # Current average price for a symbol res = client.create_order(**params) # Send in a new order # For futures trading res = client.futures_account(**params) # get futures account information res = client.futures_account_balance(**params) # returns futures account balance res = client.futures_exchange_info() # return rate limits and list of symbols for future res = client.futures_create_order(**params) # Send in a new futures order
To know more on using generic APIs, see Binance API — python-binance 0.2.0 documentation
In most of the bots or trading logic, you need a way to get a continuous stream of data, needed to make trading decisions. e.g., If the closing price of BTC (bitcoin) yesterday is more than $45000, then sell ETH (Ethereum). In this case, we can receive a historical price of BTC from Binance using a stream of data. This stream of data can be received using Web-Socket API.
Python-binance provides two ways to interact with Web-Socket API, viz. ThreadedWebsocketManager and BinanceSocketManager. ThreadedWebsocketManager does not need asyncIO programming, while BinanceSocketManager does. Below are commonly used Web-SocketAPIs.
# ThreadedWebsocketManager # instantiate the socket manager twm = ThreadedWebsocketManager(api_key=api_key, api_secret=api_secret) twm.start() # start socket manager # attach kline callback for a symbol twm.start_kline_socket(callback=handle_socket_message, symbol=symbol) # attach depth callback for a symbol twm.start_depth_socket(callback=handle_socket_message, symbol=symbol) # attach multiplex socket callback for a symbol twm.start_multiplex_socket(callback=handle_socket_message, streams=streams) twm.stop() # stop all socket streams # BinanceSocketManager async def main(): client = await AsyncClient.create() bm = BinanceSocketManager(client) # Instantiate binancesocketmanager # start any sockets here, i.e a trade socket ts = bm.trade_socket('BNBBTC') # then start receiving messages async with ts as tscm: while True: res = await tscm.recv() print(res) await client.close_connection()
To know more on using Web-Socket API, link Websockets — python-binance 0.2.0 documentation
To buy or sell a cryptocurrency such as ETH (Ethereum), BTC (bitcoin), etc. you need to create an order on Binance. It is always safe, and a good idea to first create a test order which creates an order but does not interact with the exchange. The test order helps you in raising an exception if the order is incorrect. Below is an example of, code to place an order using python-binance.
# create order # make a test order first. This will raise an exception if the order is incorrect. order = client.create_test_order( symbol='BNBBTC', side=SIDE_BUY, type=ORDER_TYPE_LIMIT, timeInForce=TIME_IN_FORCE_GTC, quantity=100, price='0.00001') # actual order order = client.create_order( symbol='BNBBTC', side=SIDE_BUY, type=ORDER_TYPE_LIMIT, timeInForce=TIME_IN_FORCE_GTC, quantity=100, price='0.00001') # There are also helper functions to buy or sell easily order = client.order_market_buy( symbol='BNBBTC', quantity=100) order = client.order_market_sell( symbol='BNBBTC', quantity=100) # To cancel order result = client.cancel_order( symbol='BNBBTC', orderId='orderId') # Get order status order = client.get_order( symbol='BNBBTC', orderId='orderId') # Get all open orders orders = client.get_open_orders(symbol='BNBBTC') # Get all orders orders = client.get_all_orders(symbol='BNBBTC')
It is important to capture exceptions on errors during the bot design. This helps in debugging the problems when making an API call. On an API call, a Binance exception is raised if a non JSON response is returned. The exception provides this information.
- response – response object
- status_code – response status code
- message – Binance error message
- code – Binance error code
- request – request object if available
try: client.get_all_orders() except BinanceAPIException as e: print e.status_code print e.message
The blog post was an attempt to cover the python-binance usage. All the APIs were not covered, but the ones mentioned here are frequently used in trading or bot design. The python-binance has a user-friendly usage compared to directly using the Binance exchange. Another advantage of using python-binance is the support for the Binance Testnet server. Passing a single parameter like testnet=True, during client object creation, you can easily connect to a testnet. If you are a beginner, this is a good option to learn trading without the fear of losing any real money !.