Binance API and Python - Part 1

BinancePython-1
Binance is relatively new to the cryptocurrency exchange scene. Binance offers a charting and trading platform that is suitable for users ranging from basic to advanced. At first glance, you will notice the simplicity of the UI, with a color scheme of charcol black and dull yellow. Unsuspectingly, underneath that simple, smooth layout lies a fairly robust API with the capability of connecting to a websocket, piping you a direct stream of data.

Implementing this API can be done with several languages, but Python is arguably the best option due to its simplicity and ease of use. Python comes with a stable and robust offering of build tools, but also allows the user to import custom functionality.

In part one of the Binance API and Python series, we will take a look at Python, Binance, and the python-binance library, which will take care of most of the manual work.

Part 1: Getting started

  1. Install Python 3 and Pip
  2. Open up your favorite editor and start a new project. I use Visual Sudio Code
  3. In your terminal install python-binance by running pip install python-binance. This should install all of the libraries necessary to interact with binance through python.
  4. Once installed, jump into the Python RELP and import binance. If no errors appear, python-binance has been installed successfully.
  5. Create two files: app.py and settings.py
    • app.py will contain the logic for our first application
    • settings.py will hold confidential information like API keys and secrets.
    • To aquire an API Key for your account, access API Settings or your Binance Account.

Structure

These should be the only files in your directory.

├── app.py
└── settings.py

settings.py

Your settings.py file should have two variables: APIKEY and SECRET
Both variables must be assigned as a string to reflect the values of your API Key and Secret.

e.g. APIKEY = "EnJP7JGBhEwOePgTDerP4GxRHzHerpT6zAgvqCjaJM05dherp"

app.py

In app.py, we will need to import a couple of libraries.

Imports

import settings
import datetime
from binance.client import Client

Settings are being imported to allow access to the APIKEY and SECRET. Datetime will allow us to convert epoch into a readable date and time. Lastly, import the Client module from binance.client. This gives us the functionality to make requests as the user.

Variables

client = Client(settings.APIKEY, settings.SECRET)
trades = client.get_my_trades(symbol='IOTABTC')
  • client - This initializes the client by passing our APIKEY and SECRET to the Client() function. This prevents us from having to continue passing the key and secret when we want to perform a request as the client.
  • trades - Trades utilizes our client variable to make a call to get all the trades we have made on the IOTABTC market.

Data returned will been in an array([]) of dictionaries({})

Example Data:
[{'id': 730863, 'orderId': 4354909, 'price': '0.00012994', 'qty': '56.00000000', 'commission': '0.05600000', 'commissionAsset': 'IOTA', 'time': 1512109714090, 'isBuyer': True, 'isMaker': True, 'isBestMatch': True}]

Logic

The next step is to loop through the data we get from trades, convert time from epoch to something human readable, and display the formatted information.

for trade in trades:
    etime = int(trade['time']) / 1000
    tradetime = datetime.datetime.fromtimestamp(etime) 
    print("Time: {} | Price: {} | Quantity: {} | Commission: {}".format(
                                                            str(tradetime),
                                                          trade['price'],
                                                            trade['qty'],
                                                    trade['commission']))

The first statement is looping through the collection of data in the list or array.

for trade in trades:

In the for loop block we pass trade['time'] /1000 into etime to cut the milliseconds off of the returned data in the variable tradetime. tradetime contains the results from converting the epoch timestamp to a date and time.

As we loop through and clean up the data, we then display it in the console by formatting the string "Time: {} | Price: {} | Quantity: {} | Commission: {}" and replacing the {} with the variables within .format()

Ultimately, this is what you should have:

import settings
import datetime
from binance.client import Client

client = Client(settings.APIKEY, settings.SECRET)
trades = client.get_my_trades(symbol='IOTABTC')


for trade in trades:
    etime = int(trade['time']) / 1000
    tradetime = datetime.datetime.fromtimestamp(etime) 
    print("Time: {} | Price: {} | Quantity: {} | Commission: {}".format(
                                                          str(tradetime),
                                                          trade['price'],
                                                            trade['qty'],
                                                    trade['commission']))

Run

To run the script in your terminal, run python app.py

The output should look like this if you've made any trades on IOTABTC:

Time: 2017-12-10 20:14:54.281000 | Price: 0.00026916 | Quantity: 12.00000000 | Commission: 0.00000323
Time: 2017-12-10 20:14:54.281000 | Price: 0.00026907 | Quantity: 22.00000000 | Commission: 0.00000592

Part 2: Coming Soon