Creating Your First Crypto Trading Bot

Elucidate AI
Elucidate AI
Published in
6 min readNov 8, 2021
https://www.cryptoknowmics.com/news/best-crypto-trading-bots-in-2020

Disclaimer

The following article should not be considered as authoritative financial advice and only serves as a tutorial for implementing a trading bot.

Introduction

Technology is evolving at a rapid pace and has changed the way people work, communicate, purchase goods and services and pay for these goods and services. Modern payments can be made electronically in seconds without any money physically changing hands. This has made financial transactions possible at almost any time and virtually any place.

Historically, people have made use of various methods to acquire items of desire. These payment options included bartering for goods and services, and later paying via cash or cheque. More recently, debit cards and credit cards have been used by individuals; however, even these methods are becoming less popular. With the rapid take-up and adoption of smartphones, consumers can pay for items through the use of an application. Even more recently, a new payment system is emerging: cryptocurrency.

Almost everyone has heard the buzzword ‘Bitcoin’. Bitcoin was the first cryptocurrency to go mainstream and early holders of this crypto can take early retirement. However, other cryptos are growing in popularity. There are currently more than 6 000 different types of cryptocurrencies, and more are being developed every day.

Cryptocurrency Trading

A recent CNBC survey found that more than 10% of surveyed individuals invest in cryptocurrency. Cryptocurrency investments have become popularised for a number of reasons:

  • Cryptocurrency eliminates the role of central banks in managing the money supply. This function leads to banks tending to reduce the value of money via inflation.
  • The technology behind cryptos, the blockchain, may be considered preferable due to the decentralization of the processing and recording system as well as having enhanced security over other traditional payment systems.
  • Certain cryptocurrencies (such as Bitcoin and Ethereum) are considered potential currencies of the future. Investors are racing to purchase these cryptocurrencies now before they appreciate even further in value.
  • The price of certain popular cryptocurrencies tends to increase at a more rapid rate than other investment alternatives. This has led to cryptos becoming popular among speculative traders.

Creating a Crypto Trading Bot

Trading bots allow crypto investors to automate buying and selling of positions based on key technical indicators. I will take you through the steps to create your very own simple crypto trading bot using Python.

https://www.mqlsoft.net/position-size-calculator-v2-1-indicator-download/

Step 1: Identify the trading platform to use

There are many online crypto trading platforms to choose from: Binance, Coinbase, Kraken, Gemini, etc. After conducting much research, I have opted to use MetaTrader5 to conduct my trading. MetaTrader5, MT5 for short, is an electronic trading platform widely used by online retail foreign exchange and crypto speculative traders. I chose MT5 as it is relatively easy to use, it is a free-to-use platform that allows you to perform technical analysis on a large variety of instruments, and it is a platform that integrates easily with Python.

Step 2: Identify a broker (used in conjunction with the platform)

There are a handful of brokers that support both MT5 and cryptocurrency trading. You should consider your choice of broker in terms of two items: cryptocurrencies available to trade and the broker’s fee and commission structure. I chose XBTFX as it has the most cryptocurrency trading option on the MT5 platform and has a reasonably low fee structure.

Step 3: Define your crypto trading strategy

For this example, our trading bot will start by solely trading Bitcoin. We will define a trade signal by the price of Bitcoin increasing by more than 1% in the last 10 minutes. This will be accompanied by a stop loss of 4% and a take profit of 7%. Furthermore, the amount of Bitcoin we will trade at any given time is 4% of our total holding. A trade signal will trigger the purchase of Bitcoin.

Understanding the terminology:

  • A stop-loss strategy is necessary to cap the maximum loss you will make on a position on a cryptocurrency or stock.
  • At the other end of the spectrum, a take-profit order determines a specific value at which you are happy to close an open position on a cryptocurrency or stock for a profit.

By combining stop losses and take-profit orders, it is possible to put together a risk ratio formula that works for your investment strategy.

Step 4: Install the MetaTrader5 module using pip

We will use the following Python code to install the required module:

!pip install MetaTrader5
!pip install --upgrade MetaTrader5

Step 5: Set up and connect to your MT5 account

You will need to create an MT5 account. You can download the platform using this link and follow the steps to create your account. You can then connect to your account using the following code:

from datetime import datetime
from itertools import count
import time
import MetaTrader5 as mt5

user_login = 12345
server = "XBTFX-MetaTrader5"
user_password = 12345

mt5.initialize(login= user_login, server= server, password= user_password)

Step 6: Define our trading parameters

These global trade parameters are defined in accordance with our defined trading strategy. We can use the following code:

CRYPTO = 'BTCUSD'
PRICE_THRESHOLD = 1
STOP_LOSS = 4
TAKE_PROFIT = 7

BUY = mt5.ORDER_TYPE_BUY
ORDER_TYPE = BUY

We also need to obtain our total Bitcoin holding. This can be obtained from our MT5 account information:

account_info = mt5.account_info()
TOTAL_HOLDING = float(account_info[10])

Step 7: Defining a few helper functions

The get_dates() function uses dates to define the range of our dataset in the function get_data(). We are only interested in the price of the last two 10-minute candles and so we will only import 1 days’ worth of data.

def get_dates():
today = datetime.today()
start_date = datetime(year=today.year, month=today.month, day=today.day - 1)
return start_date, datetime.now()

The get_data() function downloads one day of 10-minute candles, along with the buy and sell prices for Bitcoin for these candles.

def get_data():
start_date, end_date = get_dates()
return mt5.copy_rates_range('BTCUSD', mt5.TIMEFRAME_M10, start _date, end_date)

The get_current_prices() function returns the current buy and sell prices of Bitcoin.

def get_ prices():
buy_price = mt5.symbol_info_tick("BTCUSD")[2]
sell_price = mt5.symbol_info_tick("BTCUSD")[1]
return buy_price, sell_price

Step 8: Defining the logic to place a buy order for Bitcoin

The below trade() function determines if we should place a buy order (based on our chosen trading strategy) and, if so, sends the trade request to MT5 to action the trade:

def trade():
start_date, end_date = get_dates()
candles = get_data()
buy_price, sell_price = get_prices()
bid_price = mt5.symbol_info_tick(CRYPTO).bid
lot = float(round(((equity / 25) / buy_price), 2))

difference = (candles['close'][-1] / candles['close'][-2]) - 1

if difference > PRICE_THRESHOLD:
if ORDER_TYPE == BUY:
stop_loss = bid_price - (bid_price * STOP_LOSS) / 100
take_profit = bid_price + (bid_price * TAKE_PROFIT) / 100
else:
stop_loss = bid_price + (bid_price * STOP_LOSS) / 100
take_profit = bid_price - (bid_price * TAKE_PROFIT) / 100

request = {
'action': mt5.TRADE_ACTION_DEAL,
'symbol': CRYPTO,
'volume': lot,
'type': ORDER_TYPE,
'price': bid_price,
'sl': stop_loss,
'tp': take_profit,
'magic': 66,
'comment': 'buy-order',
'type_time': mt5.ORDER_TIME_GTC,
'type_filling': mt5.ORDER_FILLING_IOC,
}

result = mt5.order_send(request)

Step 9: Execute the trade function

We can use the below code to execute the trade function by sending the trade request to MT5:

if __name__ == '__main__':
for i in count():
trade()

Conclusion

You have now created your first crypto trading bot. You can now modify your existing algorithm to incorporate alternative instruments (e.g., Forex or alternative cryptocurrencies) or trading strategies (e.g., moving average crossover, mean reversion, or pairs trading).

--

--

Elucidate AI
Elucidate AI

Elucidate AI is a machine learning solutions provider specialising in marketing & sales and financial services. Powering 3 million decisions daily.