@

How to make a crypto trading bot with working examples

Thu Jan 18 2024

how to make a crypto trading bot

If you’re looking to learn how to make a crypto trading bot that automatically places trades for you and manages your portfolio, you’re in the right place. This article will provide you with all the necessary knowledge, and tools in order for you automate your trading.

In this guide we’ll be looking at some of the common tools that you’ll need to get comfortable with in order to make your own crypto trading bot as well as share working examples of some of the best crypto trading bots on the Internet.

What is a Crypto Trading bot?

A crypto trading bot is a computer program that executes trades on your behalf based on predefined criteria and algorithms. In essence, it’s a smart, automated assistant that monitors market conditions, analyzes data, and executes trades.

That’s not to say that a crypto trading bot will never require your intervention. That is the biggest misconception that some algotrading platforms out tqwhere will have you believe. As trading bots are based on predefined rules - which determine their strategy - you may need to make adjustments to your bot as market conditions change.

Making a crypto trading bot vs crypto trading bot platforms

Creating a custom crypto trading bot involves developing your own solution from scratch, tailoring it to meet your specific requirements and ensuring that you have access to a machine to continuously run it on. Of course, once you learn how to build a crypto trading bot, you have the added advantaged that you have full control to make it as custom tailored to you as you wish. Though many algo crypto trading platforms out there such as Aesir can automate most strategies based on technical indicators as well as other financial tools.

Both approaches have their own set of advantages and disadvantages, so it’s entirely up your own use case what approach you go for. A trading platform can get you started quickly, but learning how to build a crypto trading bot teaches you a lot about the inner workings of these tools.

How Do Crypto Trading Bots Work?

Crypto trading bots work by continuously monitoring market conditions and executing a user-defined strategy, when a certain criteria is met. These bots are able to automatically place buy and sell order on your behalf and manage your portfolio without human intervention.

This means that at the heart of every crypto trading bot, lies an algorithm, which is just a fancy word meaning a set of rules that the bot is supposed to follow. These rules dictate how the the bot behaves by outlining parameters such as: the amount of $ the bot is allowed to spend, the assets to continuously monitor, an exit strategy, and the trading logic itself, which is made up for additional rules.

For instance, if a bot is designed to follow a trend-following strategy, it may buy an asset when an uptrend is detected based on moving averages, and sell when a downtrend is identified.

Once the bot makes a decision to execute a trade, it interacts with the connected cryptocurrency exchange through APIs. APIs allow the bot to place orders, check account balances, and fetch real-time market data. This interaction enables the bot to execute trades swiftly and efficiently.

Because there is no human element involved in the Buying and Selling of assets, crypto trading bots tend to be a lot faster and can keep an eye on thousands of markets at once.

Prerequisites: How to make a crypto trading bot

As a general rule, when learning how to build a crypto trading bot, you should be able to explain, in a sentence or 2 what the overall strategy of the bot is. If you’re unable to condense what the bot does in a sentence or 2, you might need to review your strategy and ensure that it’s crystal clear before continuing.

Here’s a good example of a well defined strategy: My trading bot will buy any coin on Binance, whose price changes by more than 3% in the last 5 minutes. The bot sells at +20% profit or -10% loss.

Examples of Custom built cryptocurrency trading bots

The Binance Volatility Trading Bot

The Binance Volatility Trading bot does exactly what it says on the tin. It scans the Binance exchange, looking for volatile assets in an attempt to capitalize on this volatility. It uses very similar logic to our example above: buy any coin on Binance, whose price changes by more than 3% in the last 5 minutes. The bot sells at +20% profit or -10% loss.

Naturally, the user is able to define parameters such as:

In fact, the BVT bot layed out the foundation for our own algorithmic cryptocurrency trading platform Aesir. We’ve since developed this and added many other great features to our platform such as Copy Trading, Multi exchange support, and many more!

But the core logic is still available in the BVT bot itself. Sometimes the best way to understand how to build a tool like this is to look at what’s already been built. The cool thing about the BVT bot is that is 100% the kind of project that a single developer can build in a relatively short amount of time.

Because it has a relatively condensed codebase, it’s easy to understand how it works and the general approach that you will need to apply when learning how to make a crypto trading bot.

So open up the GitHub Repo and let’s go through some of the main files.

Take config.yml for example. This is where you would define the above parameters:


# These options apply to how the script will operate.
script_options:
  # Switch between testnet and mainnet
  # Setting this to False will use REAL funds, use at your own risk
  TEST_MODE: True
  LOG_TRADES: True
  LOG_FILE: 'trades.txt'

  # Set this to true if you are accessing binance from within the United States of America
  # Need to change TLD
  AMERICAN_USER: False


# These options apply to the trading methods the script executes
trading_options:
 
  # select your base currency to use for trading (trade for example USDT pairs)
  PAIR_WITH: USDT

  # Total amount per trade (your base currency balance must be at least MAX_COINS * QUANTITY)
  # Binance uses a minimum of 10 USDT per trade, add a bit extra to enable selling if the price drops.
  # Recommended: no less than 12 USDT. Suggested: 15 or more.
  QUANTITY: 15

  # List of trading pairs to exclude
  # by default we're excluding the most popular fiat pairs
  FIATS:
    - EURUSDT
    - GBPUSDT
    - JPYUSDT
    - USDUSDT
    - DOWN
    - UP

  # Maximum number of trade 'slots' at any time (your USDT balance must be at least MAX_COINS * QUANTITY)
  MAX_COINS: 7

  # the amount of time in MINUTES to calculate the difference from the current price (minimum: 1).
  TIME_DIFFERENCE: 2

  # Number of times to check for TP/SL during each TIME_DIFFERENCE (minimum: 1).
  # Don't spam the Binance API, you will be banned (max 1200 requests per minute per IP).
  RECHECK_INTERVAL: 10

  # the difference in % between the first and second checks for the price.
  CHANGE_IN_PRICE: 10

  # define in % when to sell a coin that's not making a profit.
  STOP_LOSS: 5

  # define in % when to take profit on a profitable coin.
  TAKE_PROFIT: .8

  # Use custom tickers.txt list for filtering pairs.
  CUSTOM_LIST: True
   
  # Name of custom tickers list
  TICKERS_LIST: 'tickers.txt'
   
  # whether to use trailing stop loss or not; default is True
  USE_TRAILING_STOP_LOSS: True

  # when hit TAKE_PROFIT, move STOP_LOSS to TRAILING_STOP_LOSS percentage points below TAKE_PROFIT hence locking in profit
  # when hit TAKE_PROFIT, move TAKE_PROFIT up by TRAILING_TAKE_PROFIT percentage points
  TRAILING_STOP_LOSS: .4
  TRAILING_TAKE_PROFIT: .1
  
  # Trading fee in % per trade.
  # If using 0.75% (using BNB for fees) you must have BNB in your account to cover trading fees.
  # If using BNB for fees, it MUST be enabled in your Binance 'Dashboard' page (checkbox).
  TRADING_FEE: .075
  
  SIGNALLING_MODULES:
    - pausebotmod
    - signalsamplemod 




Another important file is Binance Detect Moonings.py which is basically the equivalent of main.py - or the entry point of the application.

You don’t have to go through this code line by line, but take note of some of the main functions being called. such as: buy(), update_portfolio(orders, last_price, volume), sell_coins() and remove_from_portfolio(coins_sold)


if __name__ == '__main__':

    # Load arguments then parse settings
    args = parse_args()
    mymodule = {}

    # set to false at Start
    global bot_paused
    bot_paused = False

    DEFAULT_CONFIG_FILE = 'config.yml'
    DEFAULT_CREDS_FILE = 'creds.yml'

    config_file = args.config if args.config else DEFAULT_CONFIG_FILE
    creds_file = args.creds if args.creds else DEFAULT_CREDS_FILE
    parsed_config = load_config(config_file)
    parsed_creds = load_config(creds_file)

    # Default no debugging
    DEBUG = False

    if DEBUG_SETTING or args.debug:
        DEBUG = True

    # Load creds for correct environment
    access_key, secret_key = load_correct_creds(parsed_creds)

    if DEBUG:
        print(f'loaded config below\n{json.dumps(parsed_config, indent=4)}')
        print(f'Your credentials have been loaded from {creds_file}')


    # Authenticate with the client, Ensure API key is good before continuing
    if AMERICAN_USER:
        client = Client(access_key, secret_key, tld='us')
    else:
        client = Client(access_key, secret_key)
        
    # If the users has a bad / incorrect API key.
    # this will stop the script from starting, and display a helpful error.
    api_ready, msg = test_api_key(client, BinanceAPIException)
    if api_ready is not True:
       exit(f'{txcolors.SELL_LOSS}{msg}{txcolors.DEFAULT}')

    # Use CUSTOM_LIST symbols if CUSTOM_LIST is set to True
    if CUSTOM_LIST: tickers=[line.strip() for line in open(TICKERS_LIST)]

    # try to load all the coins bought by the bot if the file exists and is not empty
    coins_bought = {}

    # path to the saved coins_bought file
    coins_bought_file_path = 'coins_bought.json'

    # rolling window of prices; cyclical queue
    historical_prices = [None] * (TIME_DIFFERENCE * RECHECK_INTERVAL)
    hsp_head = -1

    # prevent including a coin in volatile_coins if it has already appeared there less than TIME_DIFFERENCE minutes ago
    volatility_cooloff = {}

    # use separate files for testing and live trading
    if TEST_MODE:
        coins_bought_file_path = 'test_' + coins_bought_file_path

    # if saved coins_bought json file exists and it's not empty then load it
    if os.path.isfile(coins_bought_file_path) and os.stat(coins_bought_file_path).st_size!= 0:
        with open(coins_bought_file_path) as file:
                coins_bought = json.load(file)

    print('Press Ctrl-Q to stop the script')

    if not TEST_MODE:
        if not args.notimeout: # if notimeout skip this (fast for dev tests)
            print('WARNING: You are using the Mainnet and live funds. Waiting 30 seconds as a security measure')
            time.sleep(30)

    signals = glob.glob("signals/*.exs")
    for filename in signals:
        for line in open(filename):
            try:
                os.remove(filename)
            except:
                if DEBUG: print(f'{txcolors.WARNING}Could not remove external signalling file {filename}{txcolors.DEFAULT}')

    if os.path.isfile("signals/paused.exc"):
        try:
            os.remove("signals/paused.exc")
        except:
            if DEBUG: print(f'{txcolors.WARNING}Could not remove external signalling file {filename}{txcolors.DEFAULT}')

    # load signalling modules
    try:
        if len(SIGNALLING_MODULES) > 0:
            for module in SIGNALLING_MODULES:
                print(f'Starting {module}')
                mymodule[module] = importlib.import_module(module)
                t = threading.Thread(target=mymodule[module].do_work, args=())
                t.daemon = True
                t.start()
                time.sleep(2)
        else:
            print(f'No modules to load {SIGNALLING_MODULES}')
    except Exception as e:
        print(e)

    # seed initial prices
    get_price()
    READ_TIMEOUT_COUNT=0
    CONNECTION_ERROR_COUNT = 0
    while True:
        try:
            orders, last_price, volume = buy()
            update_portfolio(orders, last_price, volume)
            coins_sold = sell_coins()
            remove_from_portfolio(coins_sold)
        except ReadTimeout as rt:
            READ_TIMEOUT_COUNT += 1
            print(f'{txcolors.WARNING}We got a timeout error from from binance. Going to re-loop. Current Count: {READ_TIMEOUT_COUNT}\n{rt}{txcolors.DEFAULT}')
        except ConnectionError as ce:
            CONNECTION_ERROR_COUNT +=1 
            print(f'{txcolors.WARNING}We got a timeout error from from binance. Going to re-loop. Current Count: {CONNECTION_ERROR_COUNT}\n{ce}{txcolors.DEFAULT}')

In fact, you could clone this open source repository and run the bot yourself, step through the code and look the various different files in more detail in order to have a clear understanding of how it works.

But in essence, your bot will require the following methods:

Freqtrade

Another more robust Open Source solution that you can explore is Freqtrade. Freqtrade supports multiple exchanges and can be controlled directly through a user interface. This does mean that the codebase is a lot more complex and would take a longer time for you to get accustomed to it.

Should you make your own trading bot from scratch?

Deciding whether to build your own trading bot from scratch is a crucial consideration that depends on various factors, including your technical expertise, time commitment, and specific trading goals.

A few things are certain though. It’s not the kind of project that you can bash out within a day or two and then start balling like a Rockefeller. Learning how to make a crypto trading bot can take months and that doesn’t include the rigorous testing to ensure that there are no bugs and no edge case scenarios that can trip up your bot.

And then there’s the computing resource. You’d need to ensure that you have a Raspberry pi or an AWS account to deploy to in order to ensure that your bot runs 24/7.

I’ve built plenty of trading bots, including the BVT bot and I can tell you that it is a rather time consuming task - but at the end of it you’ll gain some extremely valuable skills, and can be a challenging yet rewarding journey. If that’s what you’re shooting for, by all means, dive straight in, learn how to make a trading bot, and enjoy the ride, I know I did.

But if what you’re looking for is a robust solution that has all of these angles covered, runs in the cloud, and doesn’t require any coding skills to run, test and deploy trading bots, then you’re better off signing up to Aesir and building your first trading bot using our easy to use visual builder.



The choice is yours, but in any case you should join our Discord for more conversations around algotrading and crypto.

@SIR

©DEM Group 2022