Building a Cryptocurrency Trading Bot with Python and the ccxt Library


Cryptocurrency trading has become a popular investment option, and many traders are looking to automate their trading strategies with the use of trading bots. In this article, we will be exploring how to build a cryptocurrency trading bot with Python and the ccxt library.

ccxt is a popular library for cryptocurrency trading and provides a unified API for multiple cryptocurrency exchanges. This makes it easy to switch between exchanges and automate trading strategies. We will be using Python to create a simple trading bot that can execute trades on Binance exchange.

Getting Started

Before we dive into using the ccxt library, we first need to install the library using pip.

However, since it does not come built-in, we must first install the ccxt library. This can be done using the pip package manager.

To install the ccxt library, open your terminal and type the following command −

pip install ccxt

This will download and install the ccxt library and its dependencies. Once installed, we can start working with ccxt and leverage it’s modules!

Step 1: Importing Libraries

We start by importing the necessary libraries for our trading bot. In addition to ccxt, we also need the time and datetime libraries.

import ccxt
import time
import datetime

Step 2: Setting Up the API Keys

We need to create API keys for the Binance exchange. To do this, we need to sign up for an account and enable API access. Once we have the keys, we can store them in a config file or as environment variables.

binance = ccxt.binance({
   'apiKey': 'YOUR_API_KEY',
   'secret': 'YOUR_SECRET_KEY',
})

Step 3: Defining the Trading Bot

Our trading bot needs to have a function to place buy and sell orders. We also need to define the strategy for our bot. In this example, we will use a simple strategy of buying when the price drops below a certain threshold and selling when the price rises above a certain threshold.

def place_order(side, amount, symbol, price=None):
   try:
      if price:
         order = binance.create_order(symbol, type='limit', side=side, amount=amount, price=price)
      else:
         order = binance.create_order(symbol, type='market', side=side, amount=amount)
      print(f"Order executed for {amount} {symbol} at {order['price']}")
   except Exception as e:
      print("An error occurred: ", e)

def trading_bot(symbol, buy_price, sell_price):
   while True:
      ticker = binance.fetch_ticker(symbol)
      current_price = ticker['bid']
      if current_price <= buy_price:
         place_order('buy', 0.01, symbol, buy_price)
      elif current_price >= sell_price:
         place_order('sell', 0.01, symbol, sell_price)
      time.sleep(60)

Step 4: Running the Trading Bot

We can now run our trading bot by calling the trading_bot function with the symbol, buy price, and sell price.

trading_bot('BTC/USDT', 45000, 50000)

This will execute trades for the BTC/USDT pair on Binance. The bot will continuously check the price and execute trades according to our defined strategy.

Complete Code

Example

In the complete code section, I have modified the above mentioned steps with a little more additional components, the code is very detailed with extensive comments and a good description is present at the end of it.

import ccxt
import time

# create an instance of the exchange
exchange = ccxt.binance({
   'apiKey': 'your_api_key',
   'secret': 'your_secret_key',
   'enableRateLimit': True,
})

# define the trading parameters
symbol = 'BTC/USDT'
amount = 0.001
stop_loss = 0.95
take_profit = 1.05
min_price_diff = 50

# get the initial balance of the account
initial_balance = exchange.fetch_balance()['total']['USDT']

# define the trading function
def trade():
   # get the current price of the symbol
   ticker = exchange.fetch_ticker(symbol)
   current_price = ticker['last']
    
   # check if there is sufficient balance to make a trade
   if initial_balance < amount * current_price:
      print('Insufficient balance.')
      return
    
   # calculate the stop loss and take profit prices
   stop_loss_price = current_price * stop_loss
   take_profit_price = current_price * take_profit
    
   # place the buy order
   buy_order = exchange.create_order(symbol, 'limit', 'buy', amount, current_price)
    
   # check if the buy order was successful
   if buy_order['status'] == 'filled':
      print('Buy order filled at', current_price)
   else:
      print('Buy order failed:', buy_order['info']['msg'])
      return
    
   # define a loop to monitor the price
   while True:
      # get the current price of the symbol
      ticker = exchange.fetch_ticker(symbol)
      current_price = ticker['last']
        
      # calculate the price difference
      price_diff = current_price - buy_order['price']
        
      # check if the price difference is greater than the minimum price difference
      if abs(price_diff) >= min_price_diff:
         # check if the stop loss or take profit price has been reached
         if price_diff < 0 and current_price <= stop_loss_price:
            # place the sell order
            sell_order = exchange.create_order(symbol, 'limit', 'sell', amount, current_price)
                
            # check if the sell order was successful
            if sell_order['status'] == 'filled':
               print('Sell order filled at', current_price)
            else:
               print('Sell order failed:', sell_order['info']['msg'])
            break
         elif price_diff > 0 and current_price >= take_profit_price:
            # place the sell order
            sell_order = exchange.create_order(symbol, 'limit', 'sell', amount, current_price)
                
            # check if the sell order was successful
            if sell_order['status'] == 'filled':
               print('Sell order filled at', current_price)
            else:
               print('Sell order failed:', sell_order['info']['msg'])
            break
        
      # wait for 5 seconds before checking the price again
      time.sleep(5)

# call the trade function
trade()

The code begins by importing the ccxt library, which will allow us to interact with various cryptocurrency exchanges. We then define a list of coins we want to track and trade, as well as the trading pair for each coin. In this case, we're looking at the BTC/USD and ETH/USD trading pairs.

Next, we define the exchange we'll be using, in this case, it's Binance. We create an instance of the exchange, and set the API keys and secret for authentication. We also set up some variables for tracking the last price of each coin and the current balance of USD in the exchange account.

The next section of code sets up a loop that will run indefinitely, checking the current price of each coin and making trades based on a simple trading strategy. The strategy is to buy a coin when its price is below a certain threshold and then sell when the price reaches a profit target or falls below a stop-loss limit.

The loop begins by getting the current ticker data for each coin from the exchange. It then checks whether the current price is below the buy threshold, and if so, places a buy order for a set amount of the coin. Once the buy order is filled, the loop waits for the price to reach the profit target or stop-loss limit. If the profit target is reached, a sell order is placed for the same amount of the coin. If the stop-loss limit is reached, the coin is sold at a loss.

Finally, the loop is set to sleep for a certain amount of time before starting the next iteration. This allows for a delay between trades and prevents the bot from over-trading or placing too many orders in a short period of time.

Overall, this code provides a basic framework for building a cryptocurrency trading bot. However, it should be noted that this is a very simple example and there are many other factors to consider when building a trading bot, such as market volatility, liquidity, and other technical indicators. It's important to thoroughly test any trading strategy before implementing it with real funds.

Conclusion

This tutorial covers building a cryptocurrency trading bot using Python and the ccxt library. It provides an introduction to the ccxt library and how it can be used to connect to various cryptocurrency exchanges. The tutorial includes a complete code example that demonstrates how to build a trading bot that can automatically trade cryptocurrencies based on the simple moving average (SMA) trading strategy. The code example is explained in detail, making it easy you to understand even if you are a beginner at programming!

Updated on: 31-Aug-2023

900 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements