img

How to Build a Crypto Trading Bot with Binance and Python: Connect to Binance

img
valuezone 13 October 2022

How to Build a Crypto Trading Bot with Binance and Python: Connect to Binance

Heard about the amazing opportunities available for crypto bot trading and keen to get involved? Got some Python skills?

If so, this series is for you.

Update August 2023

I could never have anticipated how popular my series and articles on algorithmic trading would become.

After a listening to my readers/viewers feedback, I realized that many people were spending huge amounts of time trying to solve installation/configuration problems — rather than experiencing the joy of algorithmic trading.

I want to change this narrative — and in so doing, open up algorithmic trading for everyone.

To do this, I’ve recently launched Tradeoxy: Trading For Everyone.

If you’re reading this, Tradeoxy will simplify 90% of this series, using a series of powerful API’s and easy to use tooling.

Currently it’s in the early-access / building stage and I’d be incredibly grateful if you’d join us on this adventure. Your feedback will help us shape a better product.

Join the early access program (for free) here.

You can also view our launch video, and follow our journey on LinkedInTwitterInstagramYouTube.

About the Series

In this series, I show you how to use the REST API from Binance, the world’s largest centralized crypto trading platform, to build a crypto trading bot. Together, we build an example trading bot that identifies fast-rising crypto assets, buying them low and selling them high. By the end of the series, you’ll have everything you need to build your own trading bot. If you’d like further assistance, contact me here.

All activity is demonstrated in Python. Each episode contains working code samples, with the full code accessible on GitHub here.

Note: all code is for example use only and I make no guarantees about the strategy. Do your own research and use it at your own risk 😊.

In this Episode

By the end of this episode, you’ll be connecting to Binance and retrieving some market data. This will set the stage for the rest of our series.

About Binance

Binance is the world’s largest crypto exchange by a number of metrics. If you’re looking to get involved in the world of crypto trading, it’s a great place to start for a few reasons:

  • Plenty of trading options
  • Huge range of trading/staking/futures possibilities
  • Huge number of trading pairs (2100 at the time of writing!)
  • Free to be involved (other than trading fees)
  • Generous free REST API limits
  • Well documented API
  • Active security team, with a Bug Bounty on Bugcrowd

I’ve personally been using Binance since 2017 and have always found it to be an impressive platform. If you’d like to sign up, here’s my referral link. I will get some money (fee schedule here) if you do, however it doesn’t cost you anything.

Prepare Your API Key

Algorithmic trading on Binance requires you to set up an API. Setting up the API provides you with two keys — an api_key and a secret_key. Both of these are required to connect to Binance. Set it up as follows:

  • Log on to Binance
  • Navigate to the person icon at top right and select API Management
  • Choose Create API
  • Go through the options and store your API Key and Secret Key somewhere safe (especially the Secret Key!)
  • Edit the restrictions to include Enable Spot & Margin Trading
  • (Highly Recommended) update your IP restrictions to ‘Restrict access to trusted IPs only’. This option will limit any access to your API such that only the IPs you specify are allowed.

Set Up Your Environment

Before getting into trading, take some time to set up your environment. Here’s what I’m using:

  • OS: Windows 10 (with a bit of final editing on my M1 Macbook Air)
  • IDE: Pycharm Community Edition
  • Python 3.10 (and a bit of testing on 3.9)
  • VCS: Git

Set Up Settings

As secure developers (and to save a ton of money), we should never expose private information directly in our code. Instead, we should import the credentials, then pass them into the code as variables.

There are many ways to do this, however, to keep it simple, I’ll do this through a settings.json file. Here’s what it looks like:

{
"BinanceKeys": {
"API_Key": "YourAPIKey",
"Secret_Key": "YourSuperSecretAPIKey"
}
}
view rawexample_settings.json hosted with ❤ by GitHub
Example of settings.json for How to Build a Crypto Trading Bot with Binance and Python

Now, immediately add settings.json to your .gitignore

Next, update main.py to import the settings into your program:

import json
import os
# Variable for the location of settings.json
import_filepath = "settings.json"
# Function to import settings from settings.json
def get_project_settings(importFilepath):
# Test the filepath to sure it exists
if os.path.exists(importFilepath):
# Open the file
f = open(importFilepath, "r")
# Get the information from file
project_settings = json.load(f)
# Close the file
f.close()
# Return project settings to program
return project_settings
else:
return ImportError
# Press the green button in the gutter to run the script.
if __name__ == '__main__':
# Import project settings
project_settings = get_project_settings(import_filepath)
print(project_settings)
view rawmain.py hosted with ❤ by GitHub
Main.py set up to import the settings for Binance. Part of the series How to Build a Crypto Trading Bot with Binance and Python

Note the use of of the variable import_filepath to determine where settings.json is located. This can be anywhere on your computer.

If you push Play on your IDE now, it should show you your BinanceKeys.

Test the Connection

With your keys set up, let’s start interacting with Binance. We’ll do this by using a Python library provided by Binance called binance-connector-python.

Let’s check that Binance is up and running. Create a file called binance_interaction.py and add the following code:

from binance.spot import Spot
# Function to query Binance and retrieve status
def query_binance_status():
# Query for system status
status = Spot().system_status()
if status['status'] == 0:
return True
else:
raise ConnectionError
view rawbinance_interaction.py hosted with ❤ by GitHub
Function to query binance status from How to Build a Crypto Trading Bot with Binance and Python

Then, in __main__ add the following:

# Press the green button in the gutter to run the script.
if __name__ == '__main__':
# Import project settings
project_settings = get_project_settings(import_filepath)
# Get the status
status = binance_interaction.query_binance_status()
if status:
print("Binance Ready To Go")
view rawmain.py hosted with ❤ by GitHub
Updated __main__ to confirm that Binance status is ok. Part of series How to Build a Crypto Trading Bot with Binance and Python

Retrieve Account Information

Let’s continue working on the program startup by testing that the api_key and secret_key retrieved earlier work.

Create a new function in binance_interaction.py called query_account:

# Function to query Binance account
def query_account(api_key, secret_key):
return Spot(key=api_key, secret=secret_key).account()
view rawbinance_interaction.py hosted with ❤ by GitHub
Query Binance account for account information. Part of series How to Build a Crypto Trading Bot with Binance and Python

Now let’s update __main__. I’ll use this opportunity to hold off loading the keys until after we confirm that Binance is running. Here’s what it looks like (with a quick test to confirm that trading is in fact enabled on the account 😁):

# Press the green button in the gutter to run the script.
if __name__ == '__main__':
# Get the status
status = binance_interaction.query_binance_status()
if status:
# Import project settings
project_settings = get_project_settings(import_filepath)
# Set the keys
api_key = project_settings['BinanceKeys']['API_Key']
secret_key = project_settings['BinanceKeys']['Secret_Key']
# Retrieve account information
account = binance_interaction.query_account(api_key=api_key, secret_key=secret_key)
if account['canTrade']:
print("Let's Do This!")
view rawmain.py hosted with ❤ by GitHub
Updated __main__ to check Binance account. Part of series ‘How to Build a Crypto Trading Bot with Binance and Python

All going well, here’s what you should see:


How to Build a Crypto Trading Bot with Binance and Python. All Systems Go!

Retrieve Some Market Data

The final component of this episode is retrieving some market data.

Code Design

Before providing the code, I’ll quickly outline the design choices I’ve made for this function.

There are many different pieces of market data that can be retrieved from Binance. The library used in this series outlines most of them here. In order to keep this tutorial straightforward, I’ll only be focusing on the Candlestick data (called klines in Binance).

The structure of the code and results will be the same as in previous tutorials I’ve written.

Get Candles

Add the function get_candlestick_data to binance_interaction.py:

# Function to query Binance for candlestick data
def get_candlestick_data(symbol, timeframe, qty):
return Spot().klines(symbol=symbol, interval=timeframe, limit=qty)
view rawbinance_interaction.py hosted with ❤ by GitHub
get_candlestick_data from Binance for series How to Build a Crypto Trading Bot with Binance and Python

Update __main__

You could now update __main__ to retrieve a Crypto pair of your choice and print out the results 😊. We’ll be taking it back and out and moving it to a strategy function later, but it can be fun to play around with.

Here’s what it could look like:

# Press the green button in the gutter to run the script.
if __name__ == '__main__':
# Get the status
status = binance_interaction.query_binance_status()
if status:
# Import project settings
project_settings = get_project_settings(import_filepath)
# Set the keys
api_key = project_settings['BinanceKeys']['API_Key']
secret_key = project_settings['BinanceKeys']['Secret_Key']
# Retrieve account information
account = binance_interaction.query_account(api_key=api_key, secret_key=secret_key)
if account['canTrade']:
print("Let's Do This!")
market_data = binance_interaction.get_candlestick_data("BTCUSDT", "1h", 2)
print(market_data)
view rawmain.py hosted with ❤ by GitHub
Updated __main__ to retrieve market data from Binance and print it out. Part of the series How to Build a Crypto Trading Bot with Binance and Python

I tested it with the symbol BTCUSDT on a timeframe of 1h and a qty of 2. Here’s what I got:


Query Binance REST API to get Market Data. Part of series How to Build a Crypto Trading Bot with Binance and Python