Algorithmic Trading with Python and MT5: Building a Statistical Trading Robot Part I

Sebastian Ospina Valencia
4 min readJul 6, 2023

--

RISK DISCLAIMER: USE THE CODE AT YOUR OWN RISK. I WILL BE NOT RESPONSIBLE FOR YOUR FINANCIAL DECISIONS. DO NOT TRADE ON THINGS YOU DO NOT UNDERSTAND WELL. TRADE ONLY WITH MONEY THAT YOU CAN AFFORD TO LOSE.

Do you have a strategy and want to automatize it while learning how to become an algorithmic trader? Contact me on Instagram @elospi18

If you have read all the series of articles I have written till now, you probably want to see how to build from scratch a true trading robot that works. I will be honest with you, this is not the holy grail of trading, you will not become a millionaire with a free idea on the internet but this could be your first step to making a profitable trading algorithm so I hope you enjoy this series of publications where we will explore how to get from a statistical idea to a functional trading robot.

So the first step is to formulate the idea and this idea came when I was teaching algorithmic trading to one of my students. We were discussing momentum strategies particularly how to measure the strength of the momentum in the market. After a long walk at a park in my city, I realized that a simple linear regression could solve the problem because it has a component that measures the direction of the market (direction of the slope) and has a measure that we can interpret as the strength (significance level of the slope). I will try to explain this a little bit more in the next lines before developing the pseudo-algorithm of this strategy.

Getting back to the idea I had about the measure of the strength of the market, I remember my university lessons on statistics that we could resume on the next figure:

Imagine you have two graphs (a and b) you can note that the direction of the market, given by the closing price of the asset, in both graphs, is upwards but the difference between these two graphs is in the distance between each of the points so in the a) graph you can notice how they are closer to each other while in graph b) they are more dispersed and thus have a direct impact on what the significance level of the regression slope and thus in the measure of the strength of the market.

First, if we got more dispersed closing prices, we can say that there is a lot of volatility and despite the average price is growing, this growth is more volatile and we will have less confidence in the future market direction. In the other case, where there is less dispersion of the closing price, we can have more confidence about the short-term direction of the market. This way of thinking leads us to the concept of the confidence level that depends on the volatility of the data points with more volatility less confidence level of the slope and with less volatility more confidence over the slope ( if you want to learn more about linear regression I strongly recommend you this video https://www.youtube.com/watch?v=7ArmBVF2dCs ).

The Pseudo-Algorithm

Until here we have the idea but we don’t have anything about the functionality of the trading robot and this is why the pseudo-code of the trading robot is an important step to build your own algorithm. The pseudo-code should contain:

  1. The opening trade conditions
  2. The trade modification conditions
  3. The closing trade conditions

Then, after defining these conditions you will realize the other functionalities you have to develop in order to automatize the strategy for example you could realize that you will need to develop a function that compares the current market price with some predefined levels or for example, that you have to build a function that checks how many trades are opened.

Resuming the idea, the pseudo-code could be a text, a schema, or a drawing that describes the condition and functionalities of your trading algorithm.

The Linear Regression Pseudo-Code

The best way to make a pseudo-code is to graph it like a flow process:

Here we have the pseudo-code of the linear regression robot. Note that the first step is to get the symbol data (see my previous article How to get the market info https://medium.com/@elospieconomics/algorithmic-trading-with-python-and-mt5-introduction-ii-the-basics-45e7ae3991e2). Then, we have to make the linear regression to obtain the coefficient and its significance level (value) (we will see how to do that in the next part of this series). Next, having these two values calculated, we will make the decision like this:

  • If we have a positive coefficient and it is significative at a certain value, we will see later how to determine that value, we buy because there is a “strong” bullish momentum
  • If we have a negative coefficient and it is significative at a certain value we sell because there is a “strong” bearish momentum

If you have already read my previous stories, you will know how to send market execution orders, if you don’t know yet I invite you to read this post (https://medium.com/@elospieconomics/algorithmic-trading-with-python-and-mt5-creating-a-very-simple-martingale-system-cff848ccf9e5). The last element of the strategy is the exit condition but, in order to keep it simple, we will just send each trade with an Stop Loss and a Take profit.

We have now the elements to start coding this strategy. We will do this in the next post! Hope you have enjoyed it!

--

--

Sebastian Ospina Valencia

Chief Developer Officer at InUp. Data Scientist with 5 years of experience in Banking. Teacher of Algorithmic Trading at Universidad del Rosario