How to Create a Binance Trading Bot with Python

Sun, Oct 22, 2023

Fancy building your own Binance trading bot? It only takes a few minutes with Python!

If you’re here, that means you’re thinking about building an algorithmic auto-trading bot. Maybe you’ve been to sites like CryptoHopper or CoinRule but fancy building your very own trading bot instead. Building a basic trading bot with Python only takes a few minutes. And you won’t need to pay a small fortune to get it up and running with whatever strategy you choose.

Algorithmic trading has revolutionized the world of finance, and with the advent of cryptocurrencies, it has opened up new opportunities for retail traders. A trading bot can automate the trading process, making it easier to capitalize on market movements and execute trades more efficiently and without emotion. I will tell you right now, it takes the stress out of trading. No more sitting in front of charts and manually analyzing data in TradingView. Just a strategy that does exactly what you want every time.

In this article, I will show you exactly how easy it is to build a Python crypto trading bot for Binance (or Binance.us) that trades the Bitcoin / USDT symbol pair. We will first set up a PAPER trading app and then at the end, we will switch it to a LIVE trading app. You will also learn how to set up a basic Moving Average strategy.

Step 1: Set Up Binance or Binance.us Account

Before you begin, you will need to have an account on Binance or Binance.us, one of the world’s leading cryptocurrency exchanges. After creating an account, click Settings > API Management to generate an API key and secret key, which will be used to access the Binance API.

Step 2: Install Python and Required Libraries

The next step is to install Python on your computer if you haven’t already. See the Readme here if you need instructions on installing Python for Windows or MacOS.

Once Python is installed, you can use the pip command to install the necessary libraries. For this tutorial, you will need the following libraries:

  • ccxt - A library that provides a unified way to access cryptocurrency trading data and execute trades.
  • pandas - A data analysis library.
  • numpy - A numerical computing library.

From your terminal, install the libraries using pip or pip3

pip install ccxt
pip install pandas
pip install numpy

Step 3: Write the Trading Bot Code

Now that you have set up your Binance account and installed the necessary libraries, you can start writing the code for your trading bot. Here is a sample code that shows how to create a simple trading bot that buys and sells Bitcoin based on the moving average of its price.

We’ll begin with PAPER trading logic to test out our strategy. Open up a new file in VSCode or your favorite code editor and save it as app.py:

import ccxt
import pandas as pd
import numpy as np

# Binance API credentials
api_key = 'YOUR_API_KEY'
api_secret = 'YOUR_API_SECRET'

# Create Binance exchange object
## Switch to binanceus if needed
exchange = ccxt.binance({
    'apiKey': api_key,
    'secret': api_secret,
})

# Define trading pair and timeframe
symbol = 'BTC/USDT'
timeframe = '1h'

# Fetch historical data
data = exchange.fetch_ohlcv(symbol, timeframe)
df = pd.DataFrame(data, columns=['timestamp', 'open', 'high', 'low', 'close', 'volume'])

# Calculate moving average
df['ma'] = df['close'].rolling(window=20).mean()

# Paper trading logic
if df['close'].iloc[-1] > df['ma'].iloc[-1]:
    # Print fake buy order if the price is above the moving average
    print('Paper trade: Buy 0.01 BTC at price', df['close'].iloc[-1])
elif df['close'].iloc[-1] < df['ma'].iloc[-1]:
    # Print fake sell order if the price is below the moving average
    print('Paper trade: Sell 0.01 BTC at price', df['close'].iloc[-1])
else:
    print('No trade executed')

4. Run App From Terminal

To run the app, you’ll use the Python command in terminal:

python app.py

or

python3 app.py

Step 5: Switching To Real Orders

For LIVE trading real orders, you’ll use create_market_buy_order and create_market_sell_order:

import ccxt
import pandas as pd
import numpy as np

# Binance API credentials
api_key = 'YOUR_API_KEY'
api_secret = 'YOUR_API_SECRET'

# Create Binance exchange object
## Switch to binanceus if needed
exchange = ccxt.binance({
    'apiKey': api_key,
    'secret': api_secret,
})

# Define trading pair and timeframe
symbol = 'BTC/USDT'
timeframe = '1h'

# Fetch historical data
data = exchange.fetch_ohlcv(symbol, timeframe)
df = pd.DataFrame(data, columns=['timestamp', 'open', 'high', 'low', 'close', 'volume'])

# Calculate moving average
df['ma'] = df['close'].rolling(window=20).mean()

# Trading logic
if df['close'].iloc[-1] > df['ma'].iloc[-1]:
    # Buy Bitcoin if the price is above the moving average
    order = exchange.create_market_buy_order(symbol, 0.0005)
    print('Buy order executed:', order)
elif df['close'].iloc[-1] < df['ma'].iloc[-1]:
    # Sell Bitcoin if the price is below the moving average
    order = exchange.create_market_sell_order(symbol, 0.0005)
    print('Sell order executed:', order)
else:
    print('No trade executed')

Creating a trading bot for cryptocurrency can be a rewarding project, especially if you are interested in algorithmic trading. It’s a great way to learn about trading indicators, too. Check out our Strategy Library for ready-to-use Python code. I hope you have found this article valuable and that you’ve been able to create a simple Binance trading bot using Python that can execute trades based on a moving average strategy. However, keep in mind that trading cryptocurrencies involves risk, and you should always test your bot with small amounts before deploying it with larger sums and consider backtesting your strategy whenever possible.

Ready to take the next step?

If you're serious about creating a trading bot, consider accessing our tutorials and downloads to learn how to build your own trading bot, platorm or data viewer.

Sign up for a membership today for only $9

Get Full Access

Topics discussed in this article:

Technical / Code
by Nick DeRose

Nick DeRose is the owner of ManicDream. His mission is to teach others about automated trading, python, market trends, and host a platform where people can share their experiences and learn from other traders. His holdings include BTC, ETH, XRP, LINK, DOGE, ADA, and SHIB.