img

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

img
valuezone 13 October 2022

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

Welcome back to my series on building your own trading bot using Binance.

Crypto bot trading can be a lot of fun. There can be a lot of joy found in analyzing data, identifying trends, and then making (hopefully lots) of money from your decisions. In the stock market world, many people have stated that the discipline of quantitative analysis can make you a better trader overall.

Whatever your motivation, I hope you enjoy this series.

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 of 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 😊.

Update March 2023

When I first wrote this series, I could never have imagined the incredible response I received.

After the requests from many readers, I’ve since launched a YouTube Channel and website to help take this content even further. Why not drop in and say hi ❤

In This Episode

By the end of this episode, you’ll have built your very own trading strategy and to actively analyze market data.

Strategy Development

A Quick Note

Before diving into strategy development, I want to make a quick note about the strategy. The strategy I’m demonstrating should only be used at your own risk — after you do your own research. I cannot and do not make any statements about its viability.

If you do choose to use it, I only ask that you give me a quick shout-out on LinkedIn ❤

Strategy

The strategy I’ll be demonstrating is designed to take advantage of momentum-based trading events. Here are the rules:

  • Condition 1: If the closing price of a token experiences a 10% or more price rise per hour, for three consecutive hours, then open a trade. Call this a pump.
  • Condition 2: If a previously pumped token experiences price rises of less than 5% per 30 minutes for two consecutive time periods, exit the position.
  • Condition 3: Use a trailing stop to constantly lock in profit.

Here’s what this would look like visually:


Visual representation of strategy for How to Build a Crypto Trading Bot with Binance and Python

To simplify code development, I’ll also implement the following restrictions:

  • Restriction 1: Only trade in tokens with a Quote Asset of Binance USD (BUSD) pairs. This helps us avoid having to dynamically shift around our liquid capital to esoteric pairs.
  • Restriction 2: Only trade on the Spot Market.
  • Restriction 3: Never risk more than 10% of available capital.

Note. If you’re someone who tracks crypto pump and dump events, this strategy could be easily modified to identify these events. You could then filter these out from your trading.

Getting Data

Strategy implementation starts with correctly formatting data.

I’ll start by updating the function get_candlestick_data from Episode 1 (episode list at the bottom of the article). Readers who have seen my previous series How to Build a MetaTrader 5 Python Trading Bot will recognize the data format. Without giving too much away, I’ve standardized the format in preparation for a future series 😉

The Binance API documentation for Kline/Candlestick Data explains how to interpret the results from the queries. Expressed in code, it looks like this:

# Function to query Binance for candlestick data
def get_candlestick_data(symbol, timeframe, qty):
# Retrieve the raw data
raw_data = Spot().klines(symbol=symbol, interval=timeframe, limit=qty)
# Set up the return array
converted_data = []
# Convert each element into a Python dictionary object, then add to converted_data
for candle in raw_data:
# Dictionary object
converted_candle = {
'time': candle[0],
'open': float(candle[1]),
'high': float(candle[2]),
'low': float(candle[3]),
'close': float(candle[4]),
'volume': float(candle[5]),
'close_time': candle[6],
'quote_asset_volume': float(candle[7]),
'number_of_trades': int(candle[8]),
'taker_buy_base_asset_volume': float(candle[9]),
'taker_buy_quote_asset_volume': float(candle[10])
}
# Add to converted_data
converted_data.append(converted_candle)
# Return converted data
return converted_data
view rawbinance_interaction.py hosted with ❤ by GitHub
Updated function for get_candlestick_data. Converts the data retrieved from Binance into a format consistent with MetaTrader 5. Part of the series How to Build a Crypto Trading Bot with Binance and Python

If you’re following on from Episode 1, press Play on your IDE and you should see some nicely formatted results come back 😊

Next, I’ll convert this data into a Pandas DataFrame. To do this, create a new Python file called strategy.py in your project. Add the below code to this file, noting that I’ve added a column RedOrGreen to the original data to identify if it’s ‘Red’ (trending down) or ‘Green’ (trending up):

import pandas
import numpy
import binance_interaction
# Function to convert candle data from Binance into a dataframe
def get_and_transform_binance_data(symbol, timeframe, number_of_candles):
# Retrieve the raw data from Binance
raw_data = binance_interaction.get_candlestick_data(symbol=symbol, timeframe=timeframe, qty=number_of_candles)
print(raw_data[0]['time'])
# Transform raw_data into a Pandas DataFrame
df_data = pandas.DataFrame(raw_data)
# Convert the time to human readable format. Note that Binance uses micro-seconds.
df_data['time'] = pandas.to_datetime(df_data['time'], unit='ms')
# Convert the close time to human readable format. Note that Binance uses micro-seconds.
df_data['close_time'] = pandas.to_datetime(df_data['close_time'], unit='ms')
# Calculate if Red or Green
df_data['RedOrGreen'] = numpy.where((df_data['open'] < df_data['close']), 'Green', 'Red')
# Return the dataframe
return df_data
view rawstrategy.py hosted with ❤ by GitHub
Update strategy.py with a function to convert raw Binance Data into a Pandas DataFrame. Part of the series How to Build a Crypto Trading Bot with Binance and Python.

So far so good! Our Binance trading bot is coming along well!

Identifying a Buy

The strategy provides a series of rules which can be used to identify a buy. Here they are in normal human speak:

  1. Ensure the previous three candles are Green (rising)
  2. If they are, ensure the closing price rise for each was ≥ 10%
  3. If true, buy
  4. Discard everything else.

Analyzing Individual Symbols

To implement this signal, a method is needed to analyze a given symbol. This can be done by passing each symbol into a function called determine_buy_event. Here’s the code, placed in strategy.py:

# Function to determine a 'Buy' event for strategy
def determine_buy_event(symbol, timeframe, percentage_rise):
# Retrieve the previous 3 candles
candlestick_data = get_and_transform_binance_data(symbol=symbol, timeframe=timeframe, number_of_candles=3)
# Determine if last three values were Green
if candlestick_data.loc[0, 'RedOrGreen'] == "Green" and candlestick_data.loc[1, 'RedOrGreen'] == "Green" and candlestick_data.loc[2, 'RedOrGreen'] == "Green":
# Determine price rise percentage
rise_one = determine_percent_rise(candlestick_data.loc[0, 'open'], candlestick_data.loc[0, 'close'])
rise_two = determine_percent_rise(candlestick_data.loc[1, 'open'], candlestick_data.loc[1, 'close'])
rise_three = determine_percent_rise(candlestick_data.loc[2, 'open'], candlestick_data.loc[2, 'close'])
# Compare price rises against stated percentage rise
if rise_one >= percentage_rise and rise_two >= percentage_rise and rise_three >= percentage_rise:
# We can enter a trade!
return True
else:
# Return False as price not rising fast enough
return False
else:
# Return False as price not rising
return False
# Function to calculate the percentage price rise as a float
def determine_percent_rise(close_previous, close_current):
return (close_current-close_previous)/close_previous
view rawstrategy.py hosted with ❤ by GitHub
Code to programmatically determine a buy signal. Part of the series How to Build a Crypto Trading Bot with Binance and Python

Note. Astute programmers will note the use of hard-coded functions for determining buy events. This could certainly be abstracted into a simple for loop. I’ve done it this way to emphasize the calculation.

Retrieving a List of Symbols

Next, a method is needed to generate a list of all the signals to be analyzed. To do this, extract all the symbols with a specified base asset. Do this by adding the function query_quote_asset_list in binance_interaction.py:

# Function to query Binance for all symbols with a base asset of BUSD
def query_quote_asset_list(quote_asset_symbol):
# Retrieve a list of symbols from Binance. Returns as a dictionary
symbol_dictionary = Spot().exchange_info()
# Convert into a dataframe
symbol_dataframe = pandas.DataFrame(symbol_dictionary['symbols'])
# Extract only those symbols with a base asset of BUSD and status of TRADING
quote_symbol_dataframe = symbol_dataframe.loc[symbol_dataframe['quoteAsset'] == quote_asset_symbol]
quote_symbol_dataframe = quote_symbol_dataframe.loc[quote_symbol_dataframe['status'] == "TRADING"]
# Return base_symbol_dataframe
return quote_symbol_dataframe
view rawbinance_interaction.py hosted with ❤ by GitHub
Function to query the full list of Binance trading pairs and extract only those with a specified quote asset. Part of the series ‘How to Build a Crypto Trading Bot with Binance and Python’

At the time of writing, this returned 365 assets (tokens).

Analyze Each Symbol

It’s time to analyze the symbols!

This is done through a series of logical steps:

  1. Query Binance for a list of symbols
  2. Iterate through the symbol list and check each one
  3. Return a True or False value for each symbol

Note. Binance has strict API Request limits, explained here.

Binance has strict request limits for its API. They are certainly generous but need to be respected. To see the latest updates on the limit, check this webpage out. At the time of writing, this is 1200 weighted requests per minute (reasonably generous).

To ensure that you stay below the request limit, I’ve implemented a time.sleep of 1 second per iteration. This doesn’t impact the performance of the algorithm, but stops your API Key from getting banned ❤

Here’s the initial code to analyze your symbols:

# Function to extract symbol list into an array
def analyze_symbols(symbol_dataframe, timeframe, percentage_rise):
# Iterate through the symbols
for ind in symbol_dataframe.index:
# Analyze symbol
analysis = determine_buy_event(symbol=symbol_dataframe['symbol'][ind], timeframe=timeframe,
percentage_rise=percentage_rise)
# Print analysis to screen. Future update
print(symbol_dataframe['symbol'][ind], analysis)
# Sleep for one second
time.sleep(1)
view rawstrategy.py hosted with ❤ by GitHub
Initial code for a function to analyze Binance symbols. Part of the series ‘How to Build a Crypto Trading Bot with Binance and Python’.

I’ll return to this function in a future episode.

If you’d like to play with what you’ve developed so far, update your main as below:

# 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!")
asset_list = binance_interaction.query_quote_asset_list("BUSD")
strategy.analyze_symbols(asset_list, "1h", 10)
view rawmain.py hosted with ❤ by GitHub
__main__ updated to incorporate the analysis functions described so far. Part of the series ‘How to Build a Crypto Trading Bot with Binance and Python’.

Make sure you’ve imported the functions we’ve developed import binance_interaction and import strategy then press Play on your IDE.

Here’s what mine looked like with a 10% setting:


Demonstration of strategy for ‘How to Build a Crypto Trading Bot with Binance and Python’