Sitemap
Pedro R. Mendonça

Pedro R. Mendonça

Data Scientist in formation, RJ Brazil mendonca.super.site

Trading Bot in Python

Part 1 — The Bot Class

4 min readApr 11, 2023

--

Overview

This project has been on my mind for quite some time. Indeed, it has been the main motivation guiding my studies:

  • What do I need to know to build profitable automated trading algorithms, deploy them to a cloud, and monitor them while they operate?

Components

The project is comprised of 3 essential components:

  • The Bot Class
    - Refreshes current portfolio balances
    - Refreshes market data
    - Computes new prediction based on new data
    - Calculates new “ideal portfolio” based on prediction
    - Executes orders to achieve such portfolio
    - Saves what happened to .csv files (data, portfolio value, prediction, orders, etc)
  • The Streamlit Dashboard
    - Reads data from the .csv files the bot is constantly updating
    - Shows all information in a neat UI
  • The Model
    - The most modular component in the project
    - In this first article, we will be using a placeholder model

This article delineates the bot class. Note that it has not yet been factored for production.

You can explore the code of this project by visiting this repository.

The bot class

As the predictions are made by the model, and the gathering and processing of data isn’t very exciting in this case (concatenating rows to existing DataFrame, saving to .csv, simple operations), the juice of the bot class consists of:

  • Enforcing the timing of operations correctly
  • Translating model predictions into orders to the exchange
  • Placing valid orders to the exchange as to achieve such desired portfolio
    - This involves rounding numbers, verifying available balances, and checking minimal order value
  • Being stable as to not interrupt trading at crucial moments

It’s good to have a quick bot, however, we are dealing with Python, and not really optimizing for speed. The bot is designed to run its routine every 1 minute, which is quick enough to detect trends early.

Running the bot

  • “modelName” is used to locate the model folder, which contains its scalers and parameters. More on these parameters later.
  • “symbol” determines which Binance market will be traded.
  • “minPctChange” limits the size of adjustments the bot is allowed to make in its portfolio (avoids spamming orders)
  • “exposureMultiplier” goes into the equation that translates a prediction into an ideal exposure to the asset
  • API key and secret to connect to exchange

This code section is located at the end of “liveBotClass.py”, which defines the bot class, so the bot can be initialized by typing in the terminal from root folder:

python scripts/liveBotClass.py

Bot inicialization

Once the bot is instantiated, it runs the __init__ function:

Inside self.initializeBot() are all the initialization functions which are called only when the bot is initialized. They check if there is already a folder for this bot, if so, it loads all past data the bot saved before it shut down. Else, it creates the folder and the files. This way, the bot can pick up from where it left off if anything goes wrong.

Get Pedro R. Mendonça’s stories in your inbox

Join Medium for free to get updates from this writer.

If you paid attention, maybe you noticed that self.mainTradeLoop() was called inside the async function to get the bot running

This function calls refreshAll(), smartSignals() and saveFinish(), respectively, at the start of every minute. Before calling smartSignals() and saveFinish(), it checks if the data is up to date by comparing the current minute with the most recent minute in the market data (lastMarketDataTS).

Most of the code in this main loop serves the purpose enforcing this timing correctly.

Refresh functions

refreshAll() is a short function, but it calls a bunch of other functions:

Though it is a bit longer, this code should not be hard to understand. To make it clearer, here is a mindmap of refreshAll():

Press enter or click to view image in full size

Green rectangles represent updates in class attributes, and yellow rectangles represent update in .csv files.

saveFinish() is not used in refreshAll(), it is called after smartSignals().

Once refreshAll() ran, the bot is updated and ready to make a decision.

Trading functions

All trading computations derive from smartSignals(), just like all data refreshing is done by calling refreshAll(). These functions sum up to a fair amount of code, but are the last piece of the bot class.

To make it clearer, here is a map of smartSignals():

Press enter or click to view image in full size

As you can see by reading the code, there are a couple of operations to verify minimum notional, round the decimals of orders, double check available balances, etc. It is very important that the bot is stable as to not interrupt trading in key moments.

Finally, the bot calls saveFinish() at the end of the routine. saveFinish() saves the timestamp, portfolio value, asset exposure, and current prediction to preds.csv. This data is later used to display the UI.

Does it work?

You can clone this repository to test the bot. If everything goes well, you should be able to do this:

In the next article, we’ll look into the UI of the bot, which was done using streamlit.

--

--