Building a Simple Crypto Trading Bot with Python

InvestirHubInvestirHub
4 min read

In the world of fintech, one of the most exciting areas for developers is crypto trading. With the rise of cryptocurrencies, developers are increasingly creating automated bots to trade on various exchanges. In this tutorial, we’ll walk through how to build a basic crypto trading bot using Python and the InvestirHub Trading API to get real-time market data and execute trades.

Prerequisites

Before we begin, make sure you have the following installed:

  • Python 3.x

  • requests library (for API calls)

  • pandas (for data manipulation)

  • A InvestirHub account and access to their API (you can sign up and get API keys from InvestirHub Crypto Trading).

Step 1: Setting Up the API

First, you need to set up the InvestirHub API to get real-time cryptocurrency data. You’ll need to register for an API key, which will be used to authenticate your requests. Once you’ve registered, you’ll receive your API key.

Here's an example of how to access the crypto data using Python:

pythonCopyimport requests

# Replace with your API key
API_KEY = 'your_api_key'
BASE_URL = 'https://api.investirhub.com/crypto'

def get_crypto_data(symbol='BTCUSD'):
    url = f"{BASE_URL}/ticker/{symbol}?apikey={API_KEY}"
    response = requests.get(url)
    data = response.json()
    return data

# Example: Get Bitcoin (BTC) to USD data
data = get_crypto_data('BTCUSD')
print(data)

This script will return the latest market data for Bitcoin (BTC) paired with USD (you can modify this for any cryptocurrency). The response contains valuable data like price, volume, and market trends.

Step 2: Building the Trading Logic

Next, we’ll create a simple trading logic that will allow us to buy or sell cryptocurrency based on certain conditions, such as when the price hits a specific threshold.

For simplicity, let’s assume you want the bot to buy when the price of Bitcoin goes below $30,000 and sell when it goes above $40,000.

Here’s the code:

pythonCopydef trade_crypto(symbol='BTCUSD', buy_threshold=30000, sell_threshold=40000):
    data = get_crypto_data(symbol)
    current_price = float(data['ticker']['last'])

    # Buy condition
    if current_price < buy_threshold:
        print(f"Buying {symbol} at {current_price}!")
        # Call buy function (pseudo-code)
        # place_buy_order(symbol, current_price)

    # Sell condition
    elif current_price > sell_threshold:
        print(f"Selling {symbol} at {current_price}!")
        # Call sell function (pseudo-code)
        # place_sell_order(symbol, current_price)

    else:
        print(f"Current price is {current_price}, no action taken.")

This simple bot checks the price of Bitcoin and places buy or sell orders based on the predefined thresholds. Note that the actual buying and selling logic should be integrated with the exchange's API, but the example demonstrates how the bot could react to price changes.

Step 3: Automating the Bot

To make the bot run continuously and check prices at regular intervals, we can use Python’s time.sleep() function to pause the bot for a set amount of time before it checks again.

Here’s an example of how you can run the bot every 10 seconds:

pythonCopyimport time

while True:
    trade_crypto('BTCUSD', buy_threshold=30000, sell_threshold=40000)
    time.sleep(10)

This will check the price every 10 seconds and execute the trading logic accordingly. You can adjust the frequency based on your needs, but keep in mind that too many requests can be problematic with some APIs, so be sure to check the API rate limits.

Step 4: Adding Logging

For debugging and tracking purposes, it’s a good idea to log the bot’s activity. You can use Python’s built-in logging library to track actions and results.

pythonCopyimport logging

# Set up logging configuration
logging.basicConfig(filename='crypto_trading_bot.log', level=logging.INFO)

def trade_crypto(symbol='BTCUSD', buy_threshold=30000, sell_threshold=40000):
    data = get_crypto_data(symbol)
    current_price = float(data['ticker']['last'])

    # Logging the current price
    logging.info(f"Current price of {symbol}: {current_price}")

    if current_price < buy_threshold:
        logging.info(f"Buying {symbol} at {current_price}!")
        # place_buy_order(symbol, current_price)
    elif current_price > sell_threshold:
        logging.info(f"Selling {symbol} at {current_price}!")
        # place_sell_order(symbol, current_price)
    else:
        logging.info(f"No trade executed at {current_price}.")

This logs every price check and trading action to a file, so you can review the bot’s activity and adjust your strategy as needed.

Conclusion

You’ve now built a simple crypto trading bot that uses the InvestirHub Crypto Trading API to get real-time market data and trade based on price conditions. While this is just a basic bot, you can improve and expand it with more sophisticated strategies, such as using technical indicators (RSI, MACD), backtesting, or even integrating machine learning models for predictive analysis.

If you’re interested in diving deeper into crypto trading automation, be sure to check out more advanced resources and tutorials. Happy coding, and may your crypto trades be profitable!


Disclaimer: This tutorial is for educational purposes only. Be sure to test your code thoroughly and understand the risks involved in automated trading before deploying any bots in live markets.

0
Subscribe to my newsletter

Read articles from InvestirHub directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

InvestirHub
InvestirHub