How to Make a Low-Frequency Quantitative Crypto Trading Bot
Note: This article does not aim to provide any professional financial/investment advice. It is for educational purposes only.
I’ve had extensive experience creating algo trading bots for the spot and futures crypto market using my own strategies.
In most cases, creating a profitable trading bot is a complex and lengthy process of quantitative and mathematical analysis, finding chart patterns, and then accurately translating the trading strategy into an application.
In this article, I will show you one of the easiest ways to create your own trading bot using Freqtrade. Freqtrade (freqtrade.io )is an open-source trading software made in Python.
Quantitative trading actually does two things:
1. build a mathematical model (people)
2. according to the mathematical model, buy or sell at the right time (computer)
Before developing a bot, you first need a strategy(mathematical model). Creating a good strategy can be tricky. I use various tools to design my strategies, Neural Network Algorithms, linear/non-linear regression, Data Mining, and Fisher Linear Discriminant to name a few.
However, in this tutorial, I will make a very basic trader with a template strategy since I want to make this tutorial beginner-friendly.
Before we start
This approach has various limitations.
- One major limitation is that you cannot develop an options and futures trading bot. The options market is huge and the leverage provided by various exchanges such as Binance and Deribit makes it quite a lucrative arena to play in.
- You cannot open short positions with Freqtrade
- if your strategy requires extremely high-frequency trading where latency is key, I do not recommend using Freqtrade
With that said, let’s begin this tutorial!
Step 1: Install Freqtrade using Docker
For those who don’t know, Docker is an open-source platform for building, deploying, and managing containerized applications. You can read the docs here: https://docs.docker.com/
In your target directory:
mdkir ft_userdata
Once in ft_userdata:
curl https://raw.githubusercontent.com/freqtrade/freqtrade/stable/docker-compose.yml -o docker-compose.yml# Pull the freqtrade image
docker-compose pull # Create user directory structure
docker-compose run --rm freqtrade create-userdir --userdir user_data
Step 2: Bot configuration
Now that we’ve set up docker and the base repo, now we will enter the basic configuration for our bot. I’m going to go with a templated approach, however, these values would depend on your strategy.
Also, for this tutorial, we will stick to Binance exchange since it is one of the more popular ones.
# Create configuration - Requires answering interactive questions docker-compose run --rm freqtrade new-config --config user_data/config.json? Do you want to enable Dry-run (simulated trades)? (Y/n) Yes
? Please insert your stake currency: BTC
? Please insert your stake amount: unlimited
? Please insert max_open_trades (Integer or 'unlimited'): 10
? Please insert your desired timeframe (e.g. 5m): 15m
? Please insert your display Currency (for reporting): USD
? Select exchange binance
? Do you want to enable Telegram? No
? Do you want to enable the Rest API (includes FreqUI)? Yes
? Insert Api server Listen Address (best left untouched default!) 127.0.0.1
? Insert api-server username freqtrader
? Insert api-server password test123
Step 3: Implementing the Strategy
Now let's look at our basic config. Navigate to the config.js file as shown below:
ft_userdata
-config.js
In this config file, add the following under where it says dry_run: true
“dry_run_wallet": 1000
This lets us test and experiment in sandbox mode with a dry run wallet.
The main file we want to look at is in the “strategies” folder, sample_strategy.py.
The strategy workflow is quite simple. Based on the timeframe you provide in the configuration, you get OHLC dataframes which are then used as inputs for whichever indicators you’re using.
In our case, we configured a 15min timeframe, so that means we will get a new dataframe every 15 min from Binance.
Below I have explained the core components of a strategy config in Freqtrade:
- minimal_roi: this specifies when to sell a position (after ‘x’ minutes have elapsed), based on a specified ROI for that corresponding time
- stoploss: this is an overriding attribute that sells your position when you incur a specific loss (in percent). Ideally, for a risk-averse investor, this shouldn’t be less than -0.10 (-10%)
- order_types: This object defines the types of orders you want to allow
- def informative_pairs(self): Define additional, informative pair/interval combinations to be cached from the exchange. These pair/interval combinations are non-tradeable unless they are part of the whitelist as well.
- def populate_indicators(self, dataframe: DataFrame, metadata: dict): This is where you instantiate your indicators. Some popular indicators are RSI, Bollinger Bands, MACD etc. You can create your own indicators, use 3rd party libraries or use the libraries Freqtrade provides by default (Talib and qtypylib)
- def populate_buy_trend(self, dataframe: DataFrame, metadata: dict): This is where you specify the buying indicators. This method is called every time you get a new timeframe. The buying trend/indicator is created based on your prescribed indicator metrics. An example is shown below. This function returns a dataframe. This dataframe has a “buy” column which has the value of 1 when the buy trend is set. This will trigger a buy.
dataframe.loc[
(
# Signal: RSI crosses above 30(qtpylib.crossed_above(dataframe['rsi'], self.buy_rsi.value)) &(dataframe['tema'] <= dataframe['bb_middleband']) & # Guard: tema below BB middle(dataframe['tema'] > dataframe['tema'].shift(1)) & # Guard: tema is raising
(dataframe['volume'] > 0) # Make sure Volume is not 0),'buy'] = 1
- def populate_sell_trend(self, dataframe: DataFrame, metadata: dict): This is where you specify the selling trend. When the condition specified here is met, a sell is executed. An example is shown below:
dataframe.loc[
(
# Signal: RSI crosses above 70
(qtpylib.crossed_above(dataframe[‘rsi’], self.sell_rsi.value)) &(dataframe[‘tema’] > dataframe[‘bb_middleband’]) & # Guard: tema above BB middle
(dataframe[‘tema’] < dataframe[‘tema’].shift(1)) & # Guard: tema is falling
(dataframe[‘volume’] > 0) # Make sure Volume is not 0),‘sell’] = 1
Step 4: Run in Sandbox mode
To test the bot in sandbox, we need to spin it up as a daemon in Docker so it is continuously running. Before doing so, make sure the strategy name is correct. To verify check the command section in docker-compose.yml.
Now run the following command in your terminal.
docker-compose up -d
To check the logs,
docker-compose logs -f
When you check the logs, you should see the bot state as ‘RUNNING’ like shown below:
Step 5: Download historical OHLCV datasets
In your config file, specify the pairs you want to download data for in the “pair_whitelist” object. I will download data for these pairs:
"pair_whitelist": [
"ALGO/BTC",
"ATOM/BTC",
"BAT/BTC",
"BCH/BTC",
"BRD/BTC",
"EOS/BTC",
"ETH/BTC",
"IOTA/BTC",
"LINK/BTC",
"LTC/BTC",
"NEO/BTC",
"NXS/BTC",
"XMR/BTC",
"XRP/BTC",
"XTZ/BTC"
]
Now in a new terminal window, enter the following command which will download 15min candle data for your specified pairs on which we can then run a backtest.
docker-compose run --rm freqtrade download-data --exchange binance -t 15m
Step 6: Backtesting
To now run backtesting on our downloaded data, use the following command:
docker-compose run --rm freqtrade backtesting --strategy SampleStrategy --datadir user_data/data/binance
Our backtest shows the following results for each of our pairs:
We made a total profit of 2.95% (29.15 BTC) in one month! 😂
Now obviously, this is the templated strategy and will probably perform poorly in live mode. But, as I said before, the process of creating a well-performing strategy is a very complex one and beyond the scope of this tutorial.
Closing remarks
I only scratched the surface with the capabilities of Freqtrade. You can further plot your results, do further enhancements through the REST API, and you can also use HyperOpt which uses machine learning to further find optimal parameters for your strategy, a process called hyperparameter optimization.
Freqtrade is a great learning tool but it has its drawbacks. I personally don’t use Freqtrade or any other trading software for my algo traders because most of the time the need is for a high-frequency trader where efficiency is key.
If you’d like to build your own high-frequency algo trader or if you have any questions, feel free to reach out to me!
Join Coinmonks Telegram Channel and Youtube Channel learn about crypto trading and investing
Also, Read
- 3Commas Review | Pionex Review | Coinrule review
- Ledger vs Ngrave | Ledger nano s vs x | Binance Review
- Bybit Exchange Review | Bityard Review | Jet-Bot Review
- 3Commas vs Cryptohopper | Earn crypto interest
- The Best Bitcoin Hardware wallet | BitBox02 Review
- BlockFi vs Celsius | Hodlnaut Review | KuCoin Review
- Bitsgap review | Quadency Review | Bitbns Review