How to code your own crypto trading bot using Python

In this article I’m going to share the source code and walk you through the setup of a simple crypto trading bot written in Python, which can be used in Test and Live modes as well. It’s one of the very first algo trading bots that I have built.

What is a cryptocurrency trading bot? 

Trading bots, or crypto 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.  

EDIT: Revisiting this article one year after it was posted, it looks like the cryptocurrency market is not as devoid of bots as initially believed. If anything, the algo trading community of cryptocurrency seems to be evolving much quicker than it has been historically for stocks. That being said, there is plenty of opportunity out there, but this means we have to get a little creative with the strategies.

What are the advantaged of crypto trading algorithms?

  • 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.

Starting up with algo trading

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 local 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() will give us the current buy and sell price.

Defining the logic and placing a BUY order

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). If the logic check passes, we then place a buy position.

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!

Considerations

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

Update 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.

Update 28/04/2021

Since I have open sourced this crypto trading bot, it has been tested using different configurations. One Reddit user has managed to create a profitable configuration for the bot using the settings below.

Timeframe: 10 minute candles (TIMEFRAME_M10)

PRICE_THRESHOLD 0.6% (0.6)

STOP_LOSS 0.8% (0.8)

TAKE_PROFIT 1.8% (0.1)

Lot size 0.1

I have personally not tested this configuration, but I will post a report once I get a chance to do so.

Did you like this article? Subscribe to my newsletter for more crypto trading bot projects and guides!

If you appreciate my content and would like to see more, you can support me by donating here or via the Brave Browser. This is much appreciated as it helps me to keep the content free and open source. Thank you!

24 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?

    Thanks

    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.

  4. I’m in the usa. I’m using CryptoAltum client through MT5 using your python bot. Ran it last night with $100 of bitcoin and keep getting following error:
    1. order_send(): by BTCUSD 0.0 lots at 54462.32
    2. order_send failed, retcode=10030

    I did go into MT5 to allow outside algo trading.
    Any idea of the issue here?

      1. had to change mt5.order_filling_ioc to fok then the script worked fine…until this morning. without any other changes to the code, i’m suddenly getting ValueError: day is out of range for the month.
        I tried replacing utc_from with arrow shift but when I did that, I get TypeError: ‘NoneType’ object is not subscriptable for the difference/candles definition.

        Issues with the first day of the month (being today is 1 May?)

  5. Had an issue with the date – 1 calculation when new month rolled over. 1st may – 1 in the same month doesn’t go:

    Changed : utc_from = datetime(year=today.year, month=today.month, day=today.day – 1)

    To : utc_from = datetime.today() – timedelta(days=1)

    Only now, instead of utc_from being a rounded date, i.e. 01/05/2021 00:00:00, its now a rolling 24 hours between utc_from and utc_to. eg:

    utc_from : 30/04/2021 00:34:11
    utc_to : 01/05/2021 00:34:11

    Not sure if this will have a negative impact or not. Thinking a rolling 24 months is perhaps better?

    1. Hello, this is very good code for traiding but i got error ‘failed to connect at account , error code:(-2, ‘terminal: invalid params’ )’ any solution for this error?

  6. Hello, I’m having trouble logging in to Meta Trader5 from the bot i get an error message:,
    failed to connect at account # ******, error code:(-2, ‘terminal: invalid params’ )

    I even canceled my account and started a new one, changed details in the code and ran it same error came up.

    any ideas???.

Leave a Reply

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