Computer modeling of modern financial markets* Pavel Klimin and Sergey Bukunov Saint-Petersburg State University of Architecture and Civil Engineering, Saint-Petersburg, Russia sergeybukunov@yandex.ru Abstract. An algorithmic trading system based on popular indicators of techni- cal analysis has developed. The trading system was tested on historical data. The results of computer simulations allow us to conclude that it is possible to use a trading system to carry out transactions in modern financial markets automatically, i.e. without human participation. The system has implemented in the MetaTrader5 trading terminal using the built-in MQL programming lan- guage. Keywords: Financial markets, Automation, Programming, Technical analysis, Trade method, Trade system, Algorithmic trading. 1 Introduction A characteristic feature of our time is the widespread penetration of the Internet and information technology. Exchange trading via the Internet has become a common phenomenon today, accessible to almost anyone. The colossal capabilities of modern computers for processing huge amounts of data in combination with the high speed of their transmission over the Internet have recently led to the rapid development of the so-called algorithmic trading (high-frequency trading, algorithmic trading) [1-3]. High-frequency trading is actively used both in the foreign exchange market (Forex- market) [4] and in the Russian stock market [5]. A trading robot is a computer pro- gram that works according to an algorithm that implements a particular mathematical model or trading strategy. The variety of approaches used in the creation of such pro- grams can envy many areas of activity [4-7]. According to the Moscow Exchange, already in 2018, the share of exchange trans- actions made by trading robots amounted to 40-50% of the total number of transac- tions [8]. A similar figure in the United States for the same year was 80%. The Forex market is the largest market in terms of trading volume in the world, therefore the share of robots in this market is also extremely high. * Copyright © 2021 for this paper by its authors. Use permitted under Creative Commons License Attribu- tion 4.0 International (CC BY 4.0). 2 Materials and methods Currently, a fairly large number of trading robots are offered on the investment ser- vices market (in the Forex market, as a rule, the term "advisor" is used). However, the acquisition of such a robot-advisor is akin to the acquisition of a "black box" with the corresponding impossibility of adjusting the parameters of a mathematical or other model embedded in this robot. And the need to reconfigure the parameters of the ro- bot in today's constantly changing markets is extremely high. It is this strong volatility (volatility) of financial markets that leads to the fact that many acquired trading robots quickly enough begin to bring losses to their “lucky” owners [9]. Therefore, most investors who are familiar with the basics of mathematical and simulation modeling, technical analysis and programming, as a rule, develop their own trading robots. This is also facilitated by the fact that the most popular modern trading platforms provide all the necessary tools to create both your own market indi- cators for market analysis and to create your own trading robots. These platforms include the following: - MetaTrader is a product of MetaQuotes Software Corp [10]; - Quik is a product of ARQA Technologies [11]; - Transaq is a product of Screen Market Systems [12]. Today, one of the main innovations in trading on the financial market using trading robots is the ability to create a portfolio of advisors. To manage your investment, you need to take into account the risks that are inevitable when buying or selling any as- set. The more active trading is, the more likely strong price fluctuations are. It is often very difficult to establish rules for handling unforeseen situations when creating a mechanical trading system and then an automated trading system. To control risks when trading stocks, diversification is usually applied, which im- plies investing in several assets, rather than in one. In the case of the stock market, an investment portfolio is created that includes a variety of assets, investing in which can reduce risks [13]. To take into account the mutual influence of prices on various as- sets when managing an investment portfolio, as a rule, methods of correlation analysis and various visualization of correlation dependences are used [14]. In general, diversi- fication reduces the overall profitability of a trading system, offering a more stable yield curve in return. By analogy with an investment portfolio, in the case of automated trading, a port- folio of advisors is created, which includes several trading robots based on fundamen- tally different strategies. This approach allows you to allocate funds more rationally in terms of risk control. The purpose of this work is to computer simulate financial markets and create a trading robot that could be used as part of a portfolio of advisors to improve trading stability in conditions of high volatility in foreign exchange and stock markets. 3 Results Portfolio of advisors. One of the simple examples of risk diversification when trad- ing in financial markets can be the use of a portfolio of advisors, consisting of two robots, one of which shows the best results when the price moves in the corridor (i.e., in the absence of any trend), and the second is trending. , showing the best results when the price moves in one direction for a long time. While one strategy can be profitable, for example, because the market is currently in an uptrend, another can be profitable, averaging the final profitability. The number of robots in the portfolio, as well as their operating principles, is lim- ited only by the desire of the developer. However, you need to be very careful when choosing assets and types of advisors. Some currency pairs behave in a similar way, which means that such diversification will lead to an increase in risk. A similar effect can be observed when trying to use strategies of the same type on the same asset. With a competent approach, it is possible to create a balanced portfolio that will have a smooth yield curve, avoiding sharp drawdowns in the balance. These are the criteria that most investors are interested in when choosing an investment object. The advantages of a portfolio of advisors compared to using a single advisor are as follows: - Achievement of profitability acceptable for the investor; - More stable profitability; - The best ratio of average profitability to maximum drawdown (Kalmar coeffi- cient); - Achieving an optimal balance between profitability and risk; - Better risk diversification. Various methods are used to achieve optimal results. Using a combination of these methods, the main goals of creating a portfolio are achieved: - Preservation of the initially invested funds; - Achieving the maximum possible level of profitability; - Reducing the level of risk. Computer modeling of financial markets. Computer modeling of financial markets consists of several stages. At the first stage, mathematical modeling is carried out on a computer, which is designed to describe the behavior of a financial asset. For these purposes, as a rule, various mathematical models are used, using statistical analysis [15], machine learning [15-16], technical analysis [17], text mining [18], etc. The second stage is to create rules (trading method, decision-making system), according to which transactions of purchase and sale of financial assets will be made, with the subsequent automation of the developed algorithm [19]. And finally, at the third stage, the developed algorithm is tested on historical data on the quotes of selected financial assets in order to verify both the used model and the developed trading method. Upon receipt of unsatisfactory test results, the model parameters are adjusted and / or the trading method is edited (or replaced). The main criteria for assessing the adequacy of a trading system are the resulting profitability and the maximum draw- down of the investment account (decrease in the size of the account relative to its initial value). Figure 1 shows a general diagram of the process of building a computer model [20]. Fig. 1. The process of building a computer model. In the case of the foreign exchange market, the behavior of a certain currency pair is modeled, followed by checking the correctness of the model on real data. Trading method. The trading method proposed in this paper is based on several indi- cators of technical analysis. Directional movement indicator. The indicator of the directional movement (ADX, Average Directional Movement Index) was first introduced in 1978 by Wells Wilder [20] and has since been repeatedly modernized. The ADX indicator allows you not only to determine if a financial asset is in a trend, but also makes it possible to assess its strength. It should be borne in mind that ADX measures the strength of a trend, not its direction. Therefore, it is absolutely normal for him to grow during a fall in prices, reflecting the increasing strength of a downtrend. To display the direction of the trend, two other directional oscillators are used: + DI and -DI. The calculation of the direc- tional movement (DI, Direct Indicator) is based on the assumption that in the event of a growing trend, today's high of prices should be higher than yesterday's. Conversely, in a downtrend, today's price low should be lower than yesterday's. This technical indicator is built into the MetaTrader trading terminal. It consists of three lines in a separate indicator window under the chart with a scale from 0 to 100. To filter the significance of the ADX line value, use the boundaries of 20, 40 and 50. If the ADX line is below 20, then there is no clearly pronounced trend (the price moves in a range). As soon as the indicator crosses level 20, a trend of medium strength begins. Readings above 40 indicate a strong trend, be it a downtrend or an uptrend. Often, when the indicator is above 50, the trend starts to fade. With a de- crease in activity, the distance between + DI and –DI begins to decrease, and the ADX itself decreases. Thus, if the ADX line is growing, then this indicates the existence of a trend. In this case, a signal to open a long position occurs if the + DI line crosses the –DI line upward. A stop order (an order to forcedly close a position) can be placed below the low of the candlestick where the crossing took place. A decline in the ADX line means that the current trend is weakening and it is time to take profits. When the ADX line goes down, the + DI and –DI lines begin to approach each other. A signal to open a short position occurs when the ADX line turns up, and the – DI line is above the + DI line. A stop order can be placed above the high of the can- dlestick where the crossing took place. And again the moment of closing the position comes when the ADX line begins to decline, that is, the downtrend begins to fade. Figure 2 shows the typical signals of the ADX indicator. Fig. 2. ADX indicator trading signals. The ADX indicator works best after a period of consolidation, but is erratic after a sharp trend reversal. In addition, like all trend indicators, trend detection is delayed. ADX is a configurable indicator based on the used averaging period. By default, a period of 14 bars is used, but it can be configured (as a rule, periods from 7 to 30 bars are used). The longer the period, the better the trend direction will be tracked. How- ever, as the length of the period increases, the risk of missing a significant part of the trend increases. On the other hand, too short a period can give a large number of false signals [17]. Thus, the ADX is a useful indicator, and even a kind of indicator system, for de- termining the direction of the trend and its strength. Despite the lag, which can be reduced by using various oscillators, this indicator gives a large number of true sig- nals. Simple moving average. The SMA (Simple Moving Average) indicator is used quite often when trading in any financial markets. This indicator displays the arithme- tic average of prices on the chart, excluding fluctuations and demonstrating the pre- vailing sentiment. In the process of performing technical analysis, the moving average can act both as a support line and as a resistance line [17]. The indicator works with a lag, allowing the trader to make informed decisions, is part of many popular strategies. The main purposes of using SMA: - Detection of the current trend and its direction; - Confirmation of the presence of a trend to check the signals of other instruments. Among the main properties of the indicator, it is worth noting the ability to smooth out local market noises and determine the main market trend with a good indicator of accuracy. If the SMA line is directed upwards - there is an upward trend (prices rise on average), if the SMA line is directed downwards - there is a downward trend (prices decline on average). Standard Deviation. The Standard Deviation (StdDev) indicator shows the range of the instrument's price spread, characterizing its volatility. Usually, the indicator value is expressed in units of the price of the analyzed asset. Standard Deviation is not even so much an indicator as a function of the standard deviation of the price, which is quite actively used both in mathematical statistics and in compiling a portfolio of securities. The indicator is used both to calculate the risk of each individual security, and the total risk of the portfolio. The following formula is used to calculate the indicator: StdDev   Pc  SMA(n)) , 2 (1) n Where Pc is the closing price of the period, SMA is the simple moving average, n is the number of averaging periods. Thus, the standard deviation is calculated not just from the price, but from the price vector, i.e. from the moving average. We can say that the price fluctuates around its SMA, as well as around its axis of rotation. Moreover, the probability of finding the price at a shorter distance from the SMA is higher than at a greater price distance. Therefore, if the price moves away from its SMA by the amount of Standard Deviation, then it is more likely to expect the price to return to its SMA. Those in this situation, Standard Deviation begin to perform an oscillatory function. But it is worth considering that when the trend changes, then the vector also changes its direction (SMA changes direction) and Stan- dard Deviation at this time, as a rule, increases, showing that the price goes beyond its previous normality, already performing the function of trend indication. In the MetaTrader trading terminal, the Standard Deviation indicator is displayed under the price chart in a new area as a red curved line. The graphical representation of the Standart Deviation indicator in the MetaTrader trading terminal is shown in Figure 3. The vertical axis in Figure 3 shows the price of a financial asset in the form of Japanese candlesticks [17] (upper chart) and the indicator value (lower chart), along the horizontal axis - time. Fig. 3. Graphical display of the Standard Deviation indicator. It should be noted that in the classical sense, the StdDev indicator is rarely used, but it can be used as a basis for building more complex indicators, for example, Bollinger bands, or in combination with other indicators. Based on the fact that volatility is usually weak in the absence of a trend, Standard Deviation has low values during these periods, and often duplicating price extremes with its extremes. At the moment of the formation of a new trend, Standard Deviation breaks through its extremes and begins to grow. A signal to open a position is re- ceived at the moment the indicator line leaves its range with a stop order being placed behind the last price extremum. The Standard Deviation indicator can be used as a trend filter in combination with oscillators. Bollinger Bands. Bollinger Bands are a type of trading band or envelope [17]. Trading tapes and envelopes serve the same purpose - they provide relative defini- tions of highs and lows that can be used to create rigorous trading approaches, to rec- ognize patterns in market behavior, and for many other purposes. Typically, a band is drawn using a central moving average as the basis, while envelopes cover the price structure without a well-defined central focus, such as calculating through highs and lows or through cyclical analysis. A typical view of the indicator is shown in Figure 4. Fig. 4. Graphical representation of the Bollinger Band indicator. Implementation of a trading advisor. The main idea of the developed advisor con- sists of crossing a simple moving average (SMA) support and resistance levels using additional indicators to filter signals and maximize profits. Two variants of SMA are used, Bollinger Bands indicator, ADX indicator and StdDev standard deviation indi- cator. All program code consists of blocks; this simplifies the work with the program, its debugging, as well as further modification. Each block is a separate function, in each function a certain fixed action is per- formed, for example, calculating the value of the last resistance line or checking the user's balance, a block for opening positions, etc. The trailing stop function is implemented in the created Expert Advisor, which transfers the stop order as the position profit grows. This function allows you to re- duce drawdowns on the account, and also protects it from sudden surges in volatility. The EA opens a sell position when the support line of the Simple Moving Average, built at the lowest prices (SMA with the Low parameter) is broken. Similarly, the Expert Advisor opens a buy position when the resistance line of the moving average, built at the highest prices (SMA with the High parameter) is broken. ADX and Bollinger Bands are used as additional filters for incoming signals. An open position can be forcibly closed if a signal is received to open a reverse po- sition. For the implementation of the Expert Advisor, the MQL programming language was chosen, which is built into the MetaTrader trading terminal [10] and has a C- shaped syntax. The language has many built-in functions that allow you to get infor- mation about the properties of a traded instrument, the state of the market, the number of open positions, etc. The main difficulties for the implementation of a trading robot are technical features of the interaction of the trading terminal with the server; in par- ticular, any written program must follow some rules for correct operation. Testing an Expert Advisor. To check the performance of a trading method, as a rule, it is tested on historical data. At the testing stage, a possible need to modernize the trading method used before its subsequent application on the market is identified, to adjust the parameters of the indicators used to search for optimal values, or a decision is made to abandon the chosen trading strategy as ineffective. Using the strategy tester built into the trading terminal, you can test on data that is already present in the trad- ing terminal, or load data from other external sources. For an objective assessment, it is necessary to test on different financial instru- ments and on different time frames. This allows you to identify the conditions in which the EA works best and avoid over-optimization and adjustment of the parame- ters of the trading method for the same or similar financial instruments. By default, testing in the trading terminal is performed on data that is freely avail- able. Such data is limited by the scale of the one-minute time frame M1, which gives an extremely low accuracy in assessing the performance and modeling the behavior of an advisor. Using the Quant Data Manager software, you can get tick data on some trading in- struments, then export these data to the trading terminal, and then test the EA on these data. 4 Discussion Below are the results of testing the developed advisor for the euro / US dollar (EURUSD) currency pair. The time range of testing was ten years (from 07/01/2003 to 02/28/2013) the time frame was - one minute. The optimal parameters of the averaging periods for the indicators used were se- lected experimentally and based on the logic of the advisor's operation: for the ADX indicator - 10, for Bollinger Bands - 20, for SMA - 7 and for StdDev - 30. Figure 5 shows the balance curve for the test performed. The vertical axis in Figure 6 shows the account size in US dollars, the horizontal axis is time. Fig. 5. Balance curve for the conducted testing of the EUR/USD pair. From the data obtained, it can be seen that the developed advisor is capable of gen- erating profit (the mathematical expectation of a win is a positive value), while show- ing a large percentage (~ 80%) of profitable trades and an acceptable size of the maximum account drawdown (~ 17%). For 10 years, the advisor was able to increase the account size by 35%, which is 3.5% per annum. 5 Conclusion In this paper, we have developed an algorithmic trading system based on popular technical analysis indicators. The system is implemented on the basis of the Meta- Trader trading platform and is capable of making transactions for the purchase and sale of exchange-traded financial assets in automatic mode. To verify the proposed trading advisor, a computer simulation of financial assets in the Forex market was carried out, which showed low drawdown’s and stability, which makes this advisor an excellent addition to the portfolio of advisors. The trading strategy used, based on the breakout of important levels and the rapid transfer of stop orders to the breakeven zone, allows obtaining stable trading results, which, in turn, allows us to conclude that it can be applied in real exchange trading. References 1. Cartea A., Jaimungal S., Penalva J.: Algorithmic and High-Frequency Trading. Cam- bridge: Cambridge University Press, 356 (2015). 2. Chan E.P.: Machine Trading: Deploying Computer Algorithms to Conquer the Markets. New Jersey: Wiley, 254 (2017). 3. Durenard E.A.: Professional Automated Trading. Theory and Practice. New Jersey: Wiley, 382 (2013). 4. Kuteinikov I.: What is an exchange robot: operating principle, types, pros and cons, top 5 best, https://greedisgood.one/robot-dlya-torgovli-na-birzhe, last accessed 2020/10/28. 5. Chebotarev Yu.A.: Trading robots on the Russian stock market. Moscow: SmartBook, 160 (2011). 6. Bukunov S.V., Klimin P.Yu. Automated trading system for working in financial markets Engineering Bulletin of Don, www.ivdon.ru/magazine/archive/n4y2019/5950/, last ac- cessed 2020/10/27. 7. Chan E.P.: Algorithmic Trading: Winning Strategies and Their Rationale. New Jersey: Wiley, 255 (2013). 8. Banks and brokers are increasingly introducing robotic consultants, https://www.vedomosti.ru/personal_finance/articles/2020/01/30/821885-banki-brokeri, last accessed 2020/10/28. 9. The whole truth about Forex robots, which many will not like, https://zen.yandex.ru/media/id/5c9f0fe41bb26c00b31c2bda/vsia-pravda-o-foreks-robotah- kotoraia-mnogim-ne-ponravitsia-5d93691a32335400ae5fe9b9, last accessed 2020/10/27. 10. Trading platform Metatrader, https://metatrader5.com/ru/trading-platform, accessed 2020/10/28. 11. QUIK software package, https://arqatech.com/ru/products/quik, last accessed 2020/10/27. 12. Transaq brokerage system, https://transaq.ru, last accessed 2020/10/28. 13. Sharpe W.F., Alexander G.J., Bailey J.V.: Investments. New Jersey: Prentice Hall, 990 (1998). 14. Bukunov S.V., Bukunova O.V.: Development of a business application for processing and analyzing data on financial markets using the R language // Bulletin of the Russian New University. Series "Complex systems: models, analysis and control", 1, 182 – 195 (2020). 15. Davey K.J.: Building Winning Algorithmic Trading System: A Trader`s Journey from Data Mining to Monte Carlo Simulation to Live Trading. New Jersey: Wiley, 284, (2014). 16. Kudryavtsev O.E., Mamedzadeh Kh.M., Rodochenko V.V., Chivchyan A.A.: Analysis of the effectiveness of strategies for trading options on the Moscow Exchange using machine learning methods. Engineering Bulletin of the Don, 2017, 1, www.ivdon.ru/magazine/archive/n1y2017/4069/ last accessed 2020/10/27. 17. Schwager J. D.: Technical analysis. New York: John Wiley & Sons, Inc.,768 (1996). 18. Andrianova E.G., Novikova O.A.: The role of text mining methods in the automation of forecasting the securities market. Cloud of Science, 5, 1, https://cloudofscience.ru/publications/archive/cos_5_1/ last accessed 2020/10/27. 19. Solabuto N.V.: Trading: trading systems and methods. SPb.: Peter, 336 (2010). 20. Wilder J.W.: New concepts in Technical Trading Systems. Trend Research, 141 (1978).