Using Python libraries to develop a crypto bot trading strategy

4 June 2024

next article
Vitalik Babaevsky

Backend Developer

Vitalik Babaevsky
Using Python libraries to develop a crypto bot trading strategy

About the author: Vitaly Babaevsky, backend Python developer. One of the youngest members of our team, who, however, stands out for his creative approach to tasks and unconventional thinking. This enables us to participate in complex projects and effectively solve any problems of our clients.


Preface

Trading strategies for crypto bots is a matter of principle for every trader. Everyone contributes their own knowledge and skills to the development, uses "tricks" and teaches the machine to buy and sell as if they were doing it themselves. However, unlike a person, a bot works thousands of times faster and operates with large arrays of data, which gives an unprecedented boost.

One of the tasks for our development team was to develop a crypto bot with an interesting trading strategy based on the analysis of historical data about market conditions and transactions at this time. No analyst can simultaneously take into account millions of numbers and values, but an automated system can. So I was tasked with implementing a client's trading strategy. And the Backtrader library is best suited for this.

Practical use

Before using the trading systems in the real market, you need to make sure that they are configured correctly. The Python language is great for such tasks because it is a powerful enough programming language for working with large sets of data. Backtrader is an open source Python library that allows you to test trading systems based on methodical analysis of historical data.

Although there are many other libraries out there, I personally prefer Backtrader. And now I want to give examples of some of the main capabilities of this library:

  • Testing on historical data;

  • Optimization, which allows you to find the best parameters for your strategies;

  • Building graphs that can be customized according to your needs;

  • Extensibility, which allows you to develop your own indicators, analyzers, observers and other functions;

  • Open source code, which gives all the advantages of using a free and open solution;

  • Ability to trade in real time by connecting backtrader to some brokers for automatic trading according to your strategies;

  • A large community that is always ready to help if you have any problems with this library.

With Backtrader, you can analyze historical data to reproduce trades using signals generated by the trading system. To improve computing performance, Backtrader has the ability to use parallel computing that uses multiple processor cores. In addition, it provides integration with matplotlib to visualize data in the form of attractive graphs.

Getting Started

Before we move on to creating and testing the trading strategy, we need to install the necessary libraries and import them into our project: 

  • pip install backtrader;

  • pip install yfinance.

After successfully installing the libraries, we can move on to creating a trading strategy. For our example, we will use a simple strategy of crossing averages with SMA (simple moving average) indicators.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
from datetime import datetime
import backtrader as bt


class SmaCross(bt.Strategy):
    params = dict(
        pfast=10,
        pslow=30
    )

    def init(self):
        sma1 = bt.ind.SMA(period=self.p.pfast)
        sma2 = bt.ind.SMA(period=self.p.pslow)
        self.crossover = bt.ind.CrossOver(sma1, sma2)

    def next(self):
        if not self.position:
            if self.crossover > 0:
                self.buy()

        elif self.crossover < 0:
            self.close()


cerebro = bt.Cerebro()

data = bt.feeds.YahooFinanceData(dataname='BTC-USD',
                                 fromdate=datetime(2020, 1, 1),
                                 todate=datetime(2024, 1, 1))

cerebro.adddata(data)

cerebro.addstrategy(SmaCross)
cerebro.run()
cerebro.plot()

In this code, we first import the required libraries. We then define a class SmaCross that inherits from bt.Strategy, which allows us to implement our trading strategy. We use two simple moving averages and set conditions for entering and exiting a market position.

After that, we create an instance of Cerebro , which is the "brain" of our Backtrader trading system. We load historical data using yfinance , specifying the symbol, start and end dates. The data is added to Cerebro , after which we add our strategy and run it with cerebro.run (). Finally, we visualize the results using cerebro.plot ().

graph.png

Conclusions

As you can see, it doesn't take much effort to start using the Backtrader library directly in your project. However, installation and rendering are just the beginning. In the future, it is necessary to perform many more operations so that the crypto bot can competently use the received historical data and draw the correct conclusions for its own transactions. But these are different questions for Avivi developers. So if you have your own trading strategy, we are always ready to translate it into a custom solution. Do not waste time, contact us for consultation.

Baner articles 2023 bch.png


Similar articles
Apply for a consultation

We will reach out to within 10 minutes