6 min read

Build Your Own Crypto Trading Bot with Binance

Learn how to build a crypto trading bot using Binance and Python. Episode 1: Connecting to Binance
Build Your Own Crypto Trading Bot with Binance
Build Your Own Crypto Trading Bot

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.


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.

💡
All code is for example use only and I make no guarantees about the strategy. This is not financial advice. Do your own research and use it at your own risk 😊.

Working GitHub Code

GitHub - jimtin/crypto_trading_bot_with_binance_and_python: Tutorial on how to build a crypto trading bot with Binance and Python
Tutorial on how to build a crypto trading bot with Binance and Python - jimtin/crypto_trading_bot_with_binance_and_python

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"
    }
}

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)

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

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")

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()

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!")

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

Gif showing my results from code sections so far. Part of the series ‘How to Build a Crypto Trading Bot with Binance and Python’.
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)

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)

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

Gif showing my results from querying the Binance API. Part of the series ‘How to Build a Crypto Trading Bot with Binance and Python’.
Query Binance REST API to get Market Data. Part of series How to Build a Crypto Trading Bot with Binance and Python

That’s It for Episode 1

That’s a wrap! You’re well on your way to developing a crypto trading bot. We’ve connected to Binance, confirmed you can trade, and learned how to securely import sensitive variables!

In the next episode, we’ll dive straight into our strategy.

List of Episodes

  1. Connecting to Binance
  2. Crypto Trading Bot Strategy Example
  3. Automating Trade Placement
  4. Binance Crypto Bot Take Off: Putting it All Together

Say Hi!

I love hearing from my readers, so feel free to reach out. It means a ton to me when you clap for my articles or drop a friendly comment — it helps me know that my content is helping.