Creating Your First Crypto Trading Bot
Create a crypto trading bot by leveraging free online trading platforms and python.
Create a crypto trading bot by leveraging free online trading platforms and python.
The following article should not be considered as authoritative financial advice and only serves as a tutorial for implementing a trading bot.
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.
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:
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.
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.
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.
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:
By combining stop losses and take-profit orders, it is possible to put together a risk ratio formula that works for your investment strategy.
We will use the following Python code to install the required module:
!pip install MetaTrader5
!pip install --upgrade MetaTrader5
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)
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])
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
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)
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()
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).
Stay up to date with the latest AI news, strategies, and insights sent straight to your inbox!