@

How to Build Your First Algorithmic Cryptocurrency Trading Bot in Python

Sun Jul 02 2023

Build your own crypto trading bot in Python

Algorithmic cryptocurrency trading has gained substantial popularity among traders as it automates the trading process, reduces human errors, and potentially increases profits. An integral part of this system is the trading bot---a piece of software designed to analyze and execute trades according to predefined rules. In this article, we’re going to discuss how you can build your first algorithmic cryptocurrency trading bot using Python, and demonstrate how to use it to connect to Binance, and place orders based on pre-determined logic.

Understanding Algorithmic Trading

Algorithmic trading uses a series of logic-based conditions, combined with mathematical models and human oversight, to make decisions. A trading bot operates on these principles; it follows a specific algorithm, which might be based on timing, pricing, quantity, and other market factors. The bot eliminates the impact of human emotions on trading, thus potentially increasing profit margins.

There are several strategies for algorithmic trading, like arbitrage, scalping, trend-following, and mean reversion. For instance, a mean reversion bot enters trades when prices deviate significantly from the mean average. Once the price returns to the mean, the bot closes the trade, potentially locking in profits. In this guide, we’ll be using python to build a minimal example of a crypto trading bot that uses a mean reversion strategy to place orders on the Binance exchange.

Before we start, here are some requirements if you wish to follow along:

All the resources you need are linked above, so once you got your environment sorted, you’re good to proceed. If coding your own strategy is not for you, we’ve got you covered with out easy yet powerful strategy builder. Aesir lets you create hundreds of different trading strategies and manage your risk with no code at all.

Coding your first cryptocurrency trading bot using Python and the Binance API

The first you want to do is make sure that you have a working environment. This means creating a new project directory, a virtual python environment and installing the appropriate dependencies for your crypto trading bot.

Create your project environment

The first thing you’ll want to do is create an empty directory on your machine and create a python Environment. It’s best practice that you always set up an environment for each project you create, this will install the Python packages that you need for that project in the project directory itself.

To get started, open your CMD/ Terminal and create a new environment in the newly created directory:
python -m venv env

Now activate the environment:
env/scripts/activate

With the python environment activated, we can now safely install the required packages.

pip install python-binance
pip install pandas

Connect to the Binance API

Now go ahead and create your main executable file in your new directory. We’ll call it main.py. The next step is connect to the Binance exchange using Python. Let’s start by importing the libraries that we will be using for this project, and create an API_KEY and API_SECRET variable that we’ll be passing to the Binance Client.

from binance.client import Client
import pandas as pd

API_KEY = 'YOUR_API_KEY'
API_SECRET = 'YOUR_API_SECRET'

client = Client(API_KEY, API_SECRET)

Fetch Historical data and store it in a Pandas Dataframe

We now need to fetch some data for our crypto trading bot. We’ll be implementing a simple mean reversion strategy on Bitcoin so we’ll need access to some BTCUSDT price data. In the same file, let’s fetch the last 500 1-minute candles for the BTCUSDT asset:

# Fetch historical candlestick data
candles = client.get_klines(symbol='BTCUSDT', interval=Client.KLINE_INTERVAL_1MINUTE, limit=500)

# Prepare a pandas dataframe
df = pd.DataFrame(candles, columns=['time', 'open', 'high', 'low', 'close', 'volume', 'close_time', 'quote_asset_volume', 'num_trades', 'taker_buy_base_asset_volume', 'taker_buy_quote_asset_volume', 'ignore'])

# Convert the time and prices to float
df['time'] = pd.to_datetime(df['time'], unit='ms')
df['open'] = pd.to_numeric(df['open'])
df['close'] = pd.to_numeric(df['close'])

df.set_index('time', inplace=True, drop=False)




Strong the price data in a pandas data frame makes it easy for us to apply specific mathematical methods without having to re-write the method from scratch. It also makes it easy to plot the data if we need a visual representation of the signal or indicator we’re working with.

Implement your mean reversion crypto trading strategy

Now that we are able to connect and get historical data from Binance for our algorithmic trading strategy, we need to build the actual logic. We need to tell our bot how to trade. Remember, we are in control of the algorithm and the way it trades. In many ways, your trading bot is just an extension of your own trading acumen. So in a real-life scenario, you’ll need to ensure that the strategy you’re building works, before taking it to the market, so testing it in paper trading mode is absolutely vital. Luckily, we offer paper trading on our algorithmic cryptocurrency trading platform, so you can test your bots risk free.

A simple mean reversion strategy could be to buy when the price drops a certain percentage below the average and sell when the price increases a certain percentage above the average. We’ll use 1% as an example:

# Calculate the mean price and the buy/sell thresholds
mean_price = df['close'].mean()
buy_threshold = mean_price * 0.99
sell_threshold = mean_price * 1.01

# Fetch the current price
current_price = client.get_symbol_ticker(symbol='BTCUSDT')['price']

# Place a buy order if the price drops below the buy threshold, 
# and a sell order if it rises above the sell threshold
if current_price <= buy_threshold:
    order = client.order_market_buy(symbol='BTCUSDT', quantity=0.001)
elif current_price >= sell_threshold:
    order = client.order_market_sell(symbol='BTCUSDT', quantity=0.001)

Run your crypto trading bot

Although the code above is technically functional, if you run this python file (Ctrl + F5 on Windows) it will only run once and stop. So what we want to do is add the trading logic under a function and make it run every minute using a loop.

from binance.client import Client
import pandas as pd
import time

API_KEY = 'YOUR_API_KEY'
API_SECRET = 'YOUR_API_SECRET'

client = Client(API_KEY, API_SECRET)

def main():
    # Fetch historical candlestick data
    candles = client.get_klines(symbol='BTCUSDT', interval=Client.KLINE_INTERVAL_1MINUTE, limit=500)

    # Prepare a pandas dataframe
    df = pd.DataFrame(candles, columns=['time', 'open', 'high', 'low', 'close', 'volume', 'close_time', 'quote_asset_volume', 'num_trades', 'taker_buy_base_asset_volume', 'taker_buy_quote_asset_volume', 'ignore'])

    # Convert the time and prices to float
    df['time'] = pd.to_datetime(df['time'], unit='ms')
    df['open'] = pd.to_numeric(df['open'])
    df['close'] = pd.to_numeric(df['close'])

    df.set_index('time', inplace=True, drop=False)

    # Calculate the mean price and the buy/sell thresholds
    mean_price = df['close'].mean()
    buy_threshold = mean_price * 0.99
    sell_threshold = mean_price * 1.01

    # Fetch the current price
    current_price = float(client.get_symbol_ticker(symbol='BTCUSDT')['price'])

    # Place a buy order if the price drops below the buy threshold, and a sell order if it rises above the sell threshold
    if current_price <= buy_threshold:
        order = client.order_market_buy(symbol='BTCUSDT', quantity=0.001)
        print(order)
    elif current_price >= sell_threshold:
        order = client.order_market_sell(symbol='BTCUSDT', quantity=0.001)
        print(order)

if __name__ == "__main__":
    while True:
        main()
        time.sleep(60)  # waits 60 seconds




This is just a minimal example so you can see the entire picture at a glance, however, for better readability of your code you’ll want to create multiple single-purpose methods instead of a single monolithic function as presented above.

Congratulations, you have successfully created your very first trading bot! Naturally this is just a minimal example on how to implement a simple mean-reversion strategy and it doesn’t include features such as stop loss, take profit, portfolio management and paper trading. Building a robust trading bot is not a small task, and patience is key. All of this and more is already built into our algorithmic cryptocurrency trading platform, so you can create your trading strategy in just a couple of minutes instead.

Don’t forget to join our discord to stay up to date with our trading bot tutorials!

@SIR

©DEM Group 2022