Why Automate Your Strategy?

To succeed in the forex market, a trader needs a trading system with clear rules, filters, and limitations. At the same time, quite often fairly profitable trading strategies have only a few basic rules that can be written down as an algorithm. Such systems are often called mechanical, and these are exactly the ones algo traders love to translate into program code. Today I will share an algorithm for how to develop your own trading robot.
Why Do People Automate Their Trading Strategies?

The first reason is testing on historical data. In principle, everything is logical. You have your own trading strategy that is currently bringing you profit, but you want to know how it worked in the past and whether it will work in the future. Even if you are not going to install a robot in your place, this knowledge will give you additional confidence, especially during periods of prolonged drawdown.
The second reason is selecting optimal money management and quantitatively evaluating the system's effectiveness. Even if your strategy works and brings profit, without testing it is quite difficult to say which risks and ways of managing them will be optimal for it. Testing a system on historical data provides such useful information as maximum drawdowns, minimum and maximum profits over a given time interval. Testing also makes it possible to compare several trading systems with each other.
The third reason is objectivity. When trading on real accounts, a trader is burdened with a huge load of emotions and has to fight them. Sometimes a trader with a good profitable trading system cannot make money because they cannot control their emotions. Automating trading solves this issue quite easily.
The fourth reason is consistency. Testing a trading system gives knowledge of all the details and factors affecting the system, its strengths and weaknesses. When a risk is set for every trade and there are clear entry and exit rules, acting becomes much easier. You will also gain knowledge of how you need to act in a given situation, and more flexibly adapt your trading system and trading risks to the current market situation.
The fifth reason is freedom. Most people come to forex precisely for this. They want to earn enough money not to work five days a week for eight hours a day and at the same time not be financially constrained. Automated trading systems provide exactly this opportunity. The author of an expert advisor will think about its code only once, and receive profits from its work for years. Of course, writing an expert advisor is not a matter of minutes; sometimes it takes several weeks or even months. In addition, from time to time the author has to adjust its operation, retuning the expert advisor's parameters to the current market situation or making minor changes to the code. And yet this is already far from work in the usual sense of the word: you are not tied to a specific workplace and are not limited in time.
Developing a Trading System

Writing any trading expert advisor begins with some kind of idea. It could be a ready-made strategy found on some website or read somewhere on a forex forum, or simply an abstract idea that came to you while taking a smoke break on the balcony of your penthouse. It does not matter how it came to your mind; what matters is what you will do with it next.
And further, in a few words, the algorithm is as follows:
- Clearly formulate the trading idea. As I already said, the source of inspiration can be anything. But there are two minimum requirements that must be considered in your idea: the point of entry into the market (one rule or several rules) and the point of exit from it (as well). A strategy can even consist of completely different conditions for buying and selling; it may have several variants of entry or exit rules. The only rule is that both entries and exits must be considered. A trading strategy also contains rules for managing capital, profit, and loss. Capital management can be developed later, while profit and loss management relate to the entry rules.
- Select the tools best suited for implementing it. Decide what they will be: indicators, price patterns, some data from websites on the internet, or something else. The rules must be clear and leave no room for alternatives. An example of clear rules is to place a sell stop order at the opening of a new candle 5 points below the lower shadow of the previous candle if the previous candle broke through the EMA55 moving average but closed below it, while the price has not closed above EMA55 for the last 10 candles, and EMA55 on the previous candle is lower than it was 20 candles ago. An example of vague rules is: enter sells if the stochastic is overbought and EMA55 is falling.
- Write its rules in the form of an algorithm. The algorithm of the future expert advisor will help you not get lost in all the logical twists of its operation and will help you create clean and logical code. Programs for building flowcharts, such as yED from yworks.com, are well suited for this. Programs for creating mind maps, such as Xmind or Freemind, are also suitable.
- Write your expert advisor according to the algorithm. If possible, try to optimize your code so that testing and optimization proceed as quickly as possible. Our course "MQL Programming" will help with the writing.
- Test and optimize your expert advisor. Check the journal for errors. Error codes are listed in the journal, and their descriptions can be found on the mql4.com website. I also recommend getting a special function, an error handler, before putting the expert advisor on a real account. Or at least add a function with descriptions of errors in Russian so that when an error appears in the journal, in addition to its code there is also a description; this will save you time. Select the optimal timeframe for the expert advisor to operate on and optimize it on the largest possible number of pairs.
- Put your new expert advisor on a demo account. Review the terminal journal daily for errors. Some of them may not have appeared during the testing stage. You will also see your expert advisor's real operation and be able to roughly assess its effectiveness without losing real money.
- Install the expert advisor on a small real account. After obtaining enough data for analysis, analyze the expert advisor's performance and compare it with the results obtained during testing and tests on a demo account. When evaluating, pay attention to such parameters as trade frequency and duration, maximum account drawdown, maximum profit per trade, the size and duration of the average losing and winning trade, the total number of trades, the ratio of losing trades to profitable ones, the number of consecutive winning and losing trades and their magnitude.
- Periodically monitor and coordinate the operation of the expert advisor, making changes to the code if necessary or if you have ideas for improving its performance (after testing, of course).
The success of each subsequent step depends on the previous one. If a mistake or miscalculation was made at any of them, you will have to start over. That is why you need to be very attentive to what you are doing.
Suppose that during real-time testing you received losses exceeding the maximum ones during testing on historical data. Do not immediately remove the expert advisor and write it off. There may be three reasons for this event: the system is weak and the idea is flawed, the system is good but the optimization was done poorly, or exceptionally unfavorable conditions arose that had not occurred on historical data. As you can see, two out of three reasons say that it is too early to remove the expert advisor. If the optimization was carried out incorrectly, simply do it again. If the losses are caused by the market, which is easy to verify by opening the charts, it is worth simply waiting out the unfavorable period and continuing the tests. But the first option cannot be fixed.
Risk Management

In general, risk management makes it possible to limit the amount of capital that can be lost as a result of a trade or a series of trades, or in general when trading with an expert advisor.
Risk on entering a position
The risk on entering a position can be limited by a certain amount of money or a percentage of the deposit. Accordingly, when entering a position, a stop loss is set, which limits the maximum losses of the position.
Overnight risk
With regard to forex, this is the risk when carrying a position over the weekend. This risk cannot be limited by anything; as a result of a gap (a break in quotes between the price values at Friday's close and Monday's open), the trader may suffer significant losses that cannot be limited by a regular stop loss: the price can easily jump over your stop-loss level, taking with it a significant part of your capital. The only option possible for controlling this risk is deciding whether to leave the position over the weekend, and if so, whether to leave all of it or only part.
Trading risk
This is the minimum amount of capital that is exposed to risk in the long term while trading according to the trading system. It is measured in several different ways, and here are the three main ones: maximum losing streak (the amount of losses from a series of consecutive losing trades in the deposit currency), maximum drawdown (the largest drawdown of the account from the previous maximum to the current minimum), and required capital (the sum of the maximum drawdown, margin, reserve, and other things necessary for trading according to the strategy).
Non-trading risk
Quite recently, we all witnessed how easily and quickly many brokerage firms can disappear from the market. By and large, none of us is insured against the possibility of handing our money over to a dishonest broker or a broker on the verge of bankruptcy. Therefore my advice to you is always to take the choice of a broker seriously. Nowadays, any information can be found without getting up from your favorite computer. Check out the broker to whom you are going to trust your money, stop replenishing the ranks of suckers, there are plenty of them as it is! See the Brokers section on our forum.
Choosing the period, the segment for the test

The segment of historical data allocated for testing an expert advisor is called the test window. When determining the size of this window, it is necessary to achieve the statistical representativeness of the test result and cover periods suitable for the trading system being tested and unsuitable ones. We need reliable statistical results, that is, the number of trades should be large enough.
In the general case, a result of at least one hundred trades is considered statistically significant. If you want a more scientific approach, here is a very simple formula for determining the standard error: 1/sqrt(N+1), where N is the number of trades. Judging by the formula, the greater the number of trades, the smaller the standard error. This error indicates the degree of accuracy of the results obtained. In the recommendation above (no fewer than 100 trades), the standard error will be about 10%. What is this figure needed for? Very simply, let us take for example the average profit from the test result, say, 1000$. Then in real trading one should expect the average profit after the same number of trades (100) to be within +- 10%, that is, from 900 to 1100$. In the event that we were satisfied with ten trades in the test, in real trading it would be worth expecting the average profit per trade within +-30%, that is, from 700 to 1300$. As you can see, acceptable accuracy is achieved precisely with 100 trades.
System stability

System stability is nothing other than the steadiness of trading with it. The more steady a system is, the more stable it is, and, consequently, the more reliable. When testing, you need to look at the ratio of profitable trades to losing ones and at (most importantly) the standard deviation of the size and duration of profitable and losing trades. The smaller the standard deviations of these values, the steadier the system, the smoother the profitability curve turns out. The greater the deviations, the more unstable and "jumpy" the system's profitability curve. A steady system should generate profit across a wide range of variables, across a wide range of markets and market conditions. In other words, if a system works only on one currency pair, such a system is unstable.
System shelf life

It is no secret that after being released for sale, scalping robots rather quickly stop working at a profit and the creators begin releasing new set files with settings for their offspring. Right now I mean responsible sellers, not charlatans selling various trash. This happens because markets change over time and the old robot settings cease to be effective.
Besides that, the smaller the test window, the shorter the system's shelf life. I strive to create robots that are as steady as possible and with an unlimited shelf life, but there are very few such systems that can work for years without adjustment to the market. Hence one more criterion for a robot during testing: shelf life. A system requiring optimization every three months is certainly not the most convenient in operation, but it has a right to exist. The empirical rule is this: the system should be stable over an interval from 1/8 to 1/4 of the test window, at a minimum. That is, if you used 24 months for optimization, the system should remain effective for at least the next 3-6 months. The system's shelf life must be remembered and optimization should be carried out when it ends, preferably a little in advance. The larger the test window, the longer the system's shelf life, the less often optimization needs to be carried out, the steadier the system and the more stable its behavior when market conditions change. Nevertheless, the smaller the window, the greater the efficiency and, accordingly, the profit that can be achieved from the trading system, but the more sensitive it will be to changes in the market. In other words, the system, for example, will bring very good profit while the global trend lasts, but as soon as it stumbles, the system will lose it all, if of course you do not manage to optimize it in time.
Now, I hope, you have begun to better understand why traders learn the mql language and try to automate their trading systems. You also now know what steps need to be taken in order to create and launch an expert advisor trading according to your system and understand what risks you may encounter in the process of trading. Algo trading is a very exciting process, and the more you succeed, the greater the desire will be to invent new systems, test them and launch them on real accounts. In the end, I look at every new expert advisor as one more trader trading personally for me. I wish you a hundred such traders, gradually increasing your capital.
Respectfully, Dmitriy aka Silentspec TradeLikeaPro.ru

To succeed in the forex market, a trader needs a trading system with clear rules, filters, and limitations.