How to code your own crypto trading bot using Python

In the following article I will be showing you how to build your first automated cryptocurrency trading algorithm, as well as the resources that you will require. Before we jump into it, I would like to thank Reddit user flooberspatz for contributing to the improvement of this algorithm.

Edit 14/04/2021

The bot is now capable of placing sell positions as well, in order to experiment with opening an opposite position once a cryptocurrency has surged. Some people have expressed their interest in testing this strategy too, so I have updated the code to accommodate for that. See the code below for a step-by-step guide or check the GitHub repo at the end of the blog to see the whole code.

What is a cryptocurrency trading bot? 

Trading bots, or trading algorithms are programs designed to automatically place trading positions on your behalf, and operate on a series of pre-define parameters. These parameters can also be referred to as the logic which drives buy or sell signals of the bot. In the stock market world, the use of trading bots is referred to as High Frequency Trading and usually require access to low-latency data centres in order to compete in an already over-saturated  market.

By comparison, the Crypto market is much younger and due to the blockchain, there are less barriers to entry when it comes to creating a bot which can compete against the bigger players in the market.  

Why you should consider building one?

  • We are in a unique position to learn the early movements of the crypto-market with no barriers, and all of the tools at our disposal.
  • The crypto market never sleeps – it operates 24/7. A crypto trading algorithm can help fill in the gaps for you.
  • No emotions – personally the biggest reason for myself. I am all too familiar with buying high and selling low.
  • It’s a great learning experience and introduces you the world of algo trading.
  • It’s cool.

Making a start

Defining parameters

For this example, our bot will be trading Bitcoin automatically if the price has increased by more than 3% in the last 10 minutes. We will have a stop loss of 5% and take profit of 8%. Later on, you can choose to further optimise your bot and include additional features such as trailing stop loss and close signals – but for now we’ll keep it simple.

Identifying a test platform

Your next goal should be finding a platform that allows you to open a demo account. Demo accounts provide you with “fake” or virtual currency that you can use to test your bot with. You don’t want to give it your own money before you have a good understanding on how it performs. Most crypto trading algorithms will require multiple amends and testing phases before you can even consider backing it up with actual money, so it’s important to start off with a platform that enables you to test your bot in a safe environment.

My recommendation is to start with MetaTrader5. MT5 is a free-to-use platform that which allows you to perform technical analysis, trading operations and best of all – it integrates well with Python! It’s important to note that MT5 is not a broker, but a platform that allows you to chose which broker you would like to use.

Binance can also be used for algorithmic cryptocurrency trading, however the set-up process for the test environment is a task in and of itself and this will be covered this in a future blog post. For the purpose of building and testing your cryptocurrency bot, MT5 will serve you well, so long as you pick the right broker.

There are only a handful of Brokers that support both MT5 and cryptocurrency trading, but after some research I came across one that suited my needs quite well. XBTFX has the most crypto-currency trading pairs available on MT5, so it was naturally the best choice. As we will only be testing (at least in the beginning), we’re not too concerned with the fees and commissions. 

Once you’ve downloaded and installed MT5, head over to File and select “Open an Account”. Search for XBTFX, select it and press next.

If you’ve signed up to XBTFX using the referral link above, you will have to Connect with an existing trade account. Otherwise select “Open a demo account to trade virtual money without risk”. Take note of the user ID given to you – you will need this in Python.

Setting up your crypto bot environment

First you will need to install the MetaTrader5 module using pip.

In your Python file, you need to connect to your new demo account. You can do this by adding the following code in.

Have a look at the PRICE_THRESHOLD, STOP_LOSS, TAKE_PROFT and ORDER_TYPE variables. These are your configuration options that allow you to set different parameters for the bot. The ORDER_TYPE variable allows you to switch from a BUY order to a SELL order for additional testing. As mentioned the Edit above, some people wanted to test how the bot would perform if it sells right after a spike instead of buying.

Next, we want to store the account’s equity inside a global variable. This will enable you to specify later how much % of your equity should go in every trade. For this bot, we’ll stick to 5% of your available equity per trade.

Importing data

Now that the inital set-up is in place we need to import and store the dataset that we’ll be working from. As we’re only interested in price of the last two 10 minute candles, we’ll only import 1 day’s worth of data. Other crypto trading bots may require a much larger dataset to work from.

We’ll use 3 functions – one where we define the dates for our dataset, another where we import the data and a third function for the latest bid and ask prices.

def get_dates() contains several global variables that will need to be accessed in other functions.

def get_data() will import our data in 10 minute candle timeframes:

def get_prices()

Defining the logic and placing a BUY order

Now that our data is imported, we can check whether the price has increased by more than 3% in the last 10 minutes by defining a simple equation in the difference variable. Positions will inform our crypto trading algorithm if there is another active trade placed on BTCUSD.

This next block of code is longer than the previous ones and has thus been broken down into smaller chunks, to allow for explanations where relevant. Please note that it is part of the same function so please apply the name indentation when copying it over to your editor.

Defining the main variables and performing the logic check

Logic check

The logic check is quite straightforward – the crypto bot will check if the difference is greater than 3, sleep for 8 seconds and then check again. During my testing it turned out that sometimes there can be a temporary spike up, followed by an immediate correction. This in turn triggered the bot to open a trade and almost instantly hit the stop loss. Feel free to test and adjust the duration of the time.sleep(8).

Putting it all together

The script above will work yes – but it will only execute once! Which doesn’t help very much. Luckily, automating this is rather easy. Just add the snippet below and you’re good to go. 

You should now have a functioning cryptocurrency algorithmic trading bot that detects sharp spikes in Bitcoin price. Give it a test and, please comment with your results and ideas for improvements!


During my testing it turned out that the trading bot underperformed on bitcoin, however it actually performed quite well on XLM. The main limitation that I came across is the lack of a viable exit strategy, so if you can think one, please share it with me. The bot can also be improved by adding logic for SELL positions, as we’re only covering BUY orders in this guide.

Additional Resources

If you found this article useful subscribe to my newsletter for more awesome content.


16 thoughts on “How to code your own crypto trading bot using Python

  1. MetaTrader5 only works in windows ๐Ÿ™ Maybe you should mention this somewhere in the article.

    Btw, do you know a work around or an alternative?


    1. Hi, thanks for letting me know – I wasn’t aware of that. I will mention it in the article. What OS are you currently using? You may be able to use a virtual machine that runs windows and run it on that, or maybe even a raspberry pi!

  2. I like your program, but the whole automation idea even better.

    Some improvements I see:
    1. Auto-generate a log file (code this up once and reuse it in every program).
    2. Print all your output to the log file, first thing is a UTC timestamp. Put variable values inside double quotes “” so that you can see some variable returned “”, and know that var was empty. Maybe name your variables with the resulting value, such as (DateTime = “%d”, {DateTime}) [I don’t know the correct syntax, as I retired from coding 5 years ago, you lose those things].
    3. Always check the status return from a system, or sub-process, or a call to a server, and print those results to your log file.
    4. Once you have UTC, instead of making a slow system call, just subtract seconds: 60 per minute, 3600 per hour, 86400 per day. 10 minutes ago is UTC -600.

    1. Hey Dave, It was just a personal choice so that I can easily keep track of the results while testing. The bot can easily be adjusted to ignore any active trades.

  3. This is great! Any suggestions besides xbtfx for US residents? I get a message that it is not available for U.S.

Leave a Reply

Your email address will not be published. Required fields are marked *