ANN and SSO Algorithms for a Newly Developed Flexible Grid Trading Model

: In the modern era, the trading methods and strategies used in the ﬁnancial market have gradually changed from traditional on-site trading to electronic remote trading, and even online automatic trading performed by pre-programmed computer programs. This is due to the conduct of trading automatically and self-adjustment in ﬁnancial markets becoming a competitive development trend in the entire ﬁnancial market, with the continuous development of network and computer computing technology. Quantitative trading aims to automatically form a ﬁxed and quantiﬁable operational logic from people’s investment decisions and apply it to the ﬁnancial market, which has attracted the attention of the ﬁnancial market. The development of self-adjustment programming algorithms for automatically trading in ﬁnancial markets has transformed to being a top priority for academic research and ﬁnancial practice. Thus, a new ﬂexible grid trading model incorporating the Simpliﬁed Swarm Optimization (SSO) algorithm for optimizing parameters for various market situations as input values and the Fully Connected Neural Network (FNN) and Long Short-Term Memory (LSTM) model for training a quantitative trading model for automatically calculating and adjusting the optimal trading parameters for trading after inputting the existing market situation are developed and studied in this work. The proposed model provides a self-adjust model to reduce investors’ effort in the trading market, obtains outperformed Return of Investment (ROI) and model robustness, and can properly control the balance between risk and return.


Introduction
The formulation of financial market trading methods and strategies has changed with the continuous development of network and computer computing technology from the late 20th century to the present. Increasingly more financial institutions and major market trading are gradually changing from traditional on-site trading to electronic remote trading, and even automated trading can be performed in a pre-programmed computer program (algorithmic trading). According to statistics, the US stock market, with the most developed financial market, currently has as many as 60 to 70 percent of its trading automated by programmed programs. In this wave of application of computer computing technology and financial markets, the combination of quantitative trading and computer algorithm is particularly prosperous [1].
The main function of the financial market is to provide the current market price of traded commodities so that market participants can benefit from it. Quantitative trading emerged in the stock market in the late 20th century. In recent years, it has been widely applied in automated trading systems in the stock, currency, and futures markets. In order to receive excess returns, statistics and mathematical models are used to obtain the high 1.
Provide a new set of grid trading algorithms to improve the shortcomings of premature entry and exit of existing grid trading models in the market.

2.
Enable the trading algorithm to adapt to change in the external environment as time and market conditions change, and self-adjust the model to reduce investors' effort in the trading market. 3.
Reduce the irrational decisions brought about by investors' subjective trading decisions, through a set of training models with logical rules. 4.
Balance the relationship between risk and profit, and obtain an excellent reward under a certain reasonable risk.
The structures of the remaining sections of the article are organized as follows. An overview of grid trading, SSO, and DL are described in Section 2. Section 3 introduces the proposed approach, including operation mechanism of grid trading, concept, and architecture of flexible grid, SSO for optimal parameters, and training ANN to automatically adjust flexible grid parameters. The experimental results are analyzed in Section 4. Finally, the conclusions are discussed in Section 5.
After the setting of the grid model, the trading is based on this grid to buy and sell financial products with the rise and fall of prices. An example of the equal-distance grid is shown in Figure 1.
way, spot traders basically cannot have many profit opportunities but short futures buyers are more able to make profits. If the market goes up and down, the grid trading strategy has the greatest profitability. The more frequent the fluctuations, the greater the profit rate increases. In most markets, prices are highly fluctuating and often have a price mean reversion [39][40][41] so that grid trading strategies are now being used by more and more market players.
The other key aspect that determines the profit size of grid trading is its parameter setting, including grid average, upper bound of the grid, lower bound of the grid, number of grids, initial price, stop loss point, and stop profit point. The setting of the above parameters should be based on product price fluctuations, trading costs, risk tolerance, and the amount of principal as the setting considerations, which directly affect the final performance of grid trading.
Grid trading is mainly divided into two types: equal-distance grid and equal-ratio grid. At present, the grid that many people use in practice is the equal-distance grid.
The setting of the equal-distance grid is based on the initial price P0, and the setting of upper bound of the grid Gul, the lower bound of the grid Gll, the total number of grids n, and the calculation of the grid spacing Gs by Equation (1).
After the setting of the grid model, the trading is based on this grid to buy and sell financial products with the rise and fall of prices. An example of the equal-distance grid is shown in Figure 1. The grid spacing Gs of equal-ratio grid is a fixed ratio and the equal-ratio grid is calculated at this ratio. An example of the equal-ratio grid is shown in Figure 2. The grid spacing G s of equal-ratio grid is a fixed ratio and the equal-ratio grid is calculated at this ratio. An example of the equal-ratio grid is shown in Figure 2.  Figure 2. Schematic diagram of equal-ratio grid trading.

SSO
SSO was proposed by Yeh [17] in 2009 based on the concepts of personal best (pbest) and global best (gbest) and adds random numbers resulting in the solution owning the opportunity to escape from the local optimal solution and improve the diversity of the solution.
The major difference between SSO and other heuristic algorithms is its special update mechanism. There are three particularly important parameter settings: Cg, Cp, and Cw, where Cg > Cp > Cw. The update mechanism is shown in Equation (2). According to the correspondence between the random number ρ and Cg, Cp, and Cw, the next generation solution t i,j x is determined, which may be gbest, pbest, the current solution or a random number, respectively. , ,..., = be the ith solution with j variables in the tth generation; ρ is a random number subject to uniform distribution between [0, 1].
The update method is that when ρ is between [0, Cg), the variable t+ i,j x 1 is replaced by the global best solution gj that is the best performing solution among all the solutions at present; when ρ is between [Cg, Cp), it is replaced by the best solution in the region pi,j that is the optimal solution in the past generations of the variable; when it is between [Cp, Cw), it maintains the solution of the previous generation t i,j x ; when it is between [Cw, 1), it is replaced by x that is a random number generated in the upper and lower bounds of the variable. The purpose is to reduce the chance of becoming trapped in local optimal solutions, while also increasing the diversity of solutions.

SSO
SSO was proposed by Yeh [17] in 2009 based on the concepts of personal best (pbest) and global best (gbest) and adds random numbers resulting in the solution owning the opportunity to escape from the local optimal solution and improve the diversity of the solution.
The major difference between SSO and other heuristic algorithms is its special update mechanism. There are three particularly important parameter settings: C g , C p , and C w , where C g > C p > C w . The update mechanism is shown in Equation (2). According to the correspondence between the random number ρ and C g , C p , and C w , the next generation solution x t i,j is determined, which may be gbest, pbest, the current solution or a random number, respectively.
. , x t i,j be the ith solution with j variables in the tth generation; ρ is a random number subject to uniform distribution between [0, 1].
The update method is that when ρ is between [0, C g ), the variable x t+1 i,j is replaced by the global best solution g j that is the best performing solution among all the solutions at present; when ρ is between [C g , C p ), it is replaced by the best solution in the region p i,j that is the optimal solution in the past generations of the variable; when it is between [C p , C w ), it maintains the solution of the previous generation x t i,j ; when it is between [C w , 1), it is replaced by x that is a random number generated in the upper and lower bounds of the variable. The purpose is to reduce the chance of becoming trapped in local optimal solutions, while also increasing the diversity of solutions.

DL
This section provides an overview of the ANN, back-propagating method, and LSTM adopted in this study. In recent years, DL has been widely used in medicine, industry, transportation, and other fields, which can help the completion of speech recognition and machine vision. It is a Machine Learning (ML) algorithm based on ANN, which learns through data features.
The computing architecture of ANN was first proposed by McCulloch and Pitts [42], and subsequently, it has been continuously improved by many outstanding scholars [43,44], and it has become a famous ML model in Artificial Intelligence (AI).
The basic structure of ANN is divided into three parts including input layer, hidden layer, and output layer. Each node of the input layer corresponds to the input predictor variable, each node of the output layer corresponds to the objective variable, and the hidden layer is sandwiched between input layer and output layer.
Except for the nodes in the input layer, each node in the ANN is connected to several nodes in front of it and each node has a corresponding weight that is called FNN.

Back-Propagating Method
In DL, the back-propagating method [45] is an extremely important key to make the model complete and is often used to train and optimize ANN. Using the back-propagation, the gradient of the loss function to the weight can be efficiently found, and then the gradient descent method [46] is used to solve each weight. The "loss" in the loss function refers to the error of the actual value and the predicted value. The main concept of back-propagation is to return the error resulting that the weight can use the error size to perform the gradient descent method to obtain and update the more suitable weight, further reduce the error, and optimize the weight.

LSTM
LSTM is a model generated to improve the short-term memory of Recurrent Neural Network (RNN). It is mainly composed of four units including memory cell, input gate, output gate and forget gate.
The input gate controls whether it is input into the memory unit this time, the memory unit is responsible for storing the calculated value, the forget gate controls to clear the memory, and the output gate controls whether to output the operation result.

Proposed Approach
The approach proposed in this study is presented in sequence. The initial setting and operation mechanism of grid trading is introduced in Section 3.1. Section 3.2 presents the concept and setting method of flexible grid. The use of SSO to obtain the optimal flexible grid parameters in different situations is shown in Section 3.3. As the training basis for DL, a neural network is finally trained that can automatically output the suitable grid parameters for trading by inputting recent market information to obtain excess returns from market fluctuations is represented in Section 3.4.

Operation Mechanism of Grid Trading
This section presents the grid trading practices in this study, including initial parameter setting and calculation, and subsequent operation mechanisms and processes, in detail.

Initial Parameter Setting of Grid Trading
A total of five basic parameters need to be set, namely the total investment capital F 0 , the initial price P 0 , the upper bound of the grid G ul , the lower bound of the grid G ll , and the total number of grids n, before operating a grid trading model. The total investment capital and initial price are set as control variables in this study, i.e., when comparing the results, the total investment capital and initial price used in any method will be set to the same fixed value, and compared on the same standard.
Before the grid trading model runs, the unit price difference G s , which is the grid spacing, needs to be calculated using Equation (1) in Section 2 if the grid is an equal-distance grid. G s is a certain value in equal-distance grid. However, it is a fixed ratio in equal-ratio grid, for example, the value of the next grid is P 0 ·G 1 s = 110 and the next grid is P 0 ·G 2 s = 121 when P 0 = 100 and G s = 1.1, and this ratio can be calculated from Equation (3) below.
In addition, it is also necessary to calculate how much funds should be used to purchase the spot before grid trading, i.e., the initial purchase of spot S 0 , so as to sell for profit when the price rises, and how many funds must be kept on hand to buy spots when the price falls; here, C 0 means to start holding cash. Hence, the total investment funds are divided into two parts that is represented by the following Equation (4). The spot and funds held in each subsequent period are represented by S j and C j , where j represents the jth period.
In order to calculate the initial purchase of spot S 0 and the initial holding of cash C 0 , it is necessary to first calculate the number of upper grids n u and the number of lower grids n l , the sum of which is equivalent to the total number of grids n such as shown in Equation (5). The values of n u and n l can be obtained by Equations (6) and (7), respectively. Here, the equal-distance grid is used as an example. n = n u + n l (5) After calculating the number of upper grids n u and the number of lower grids n l , and then further use Equations (8) and (9) to calculate the initial purchase of spot S 0 and the initial holding of cash C 0 . At this time, the single-cell trading volume G v is still an unknown value.
Finally, calculate the price of each grid cell g i , i from 1 to n using Equation (11) (equaldistance grid) or Equation (12) (equal-ratio grid).

Operation Mechanism of grid Trading
The following Figure 3a-e illustrate in detail how the grid trading model updates and adjusts with the market price after the initial parameters are set, and how to settle at the end. 1. When the grid is initially running, the current price is used as the benchmark, and the above grid price is placed on a sell order, and the following grid price is placed on a buy order as shown in Figure 3a  1. When the grid is initially running, the current price is used as the benchmark, and the above grid price is placed on a sell order, and the following grid price is placed on a buy order as shown in Figure 3a.

2.
If the price rises until it hits the first grid line, make a sell action, update the spot volume and funds held, and place a buy order at the original grid position as shown in Figure 3b.

3.
If the price falls back to the initial grid line, make a buy action, update the spot volume and funds held, and place a sell order at the original grid position as shown in Figure 3c.

4.
If the price continues to drop to a grid line, make a buy action, update the spot volume and funds held, and place a sell order at the original grid position as shown in Figure 3d.

5.
Continue to trade with the above mechanism. Although the price has returned to the original point of grid trading, it has successfully arbitraged seven times, which is equivalent to seven grids of grid spread profits as shown in Figure 3e. 6.
When the grid trading model is to be closed, there are two ways to end it. One is to directly keep the current spot and funds held, and the other is to sell the spot at the current price and convert it into cash. The former is recommended to be used when the market price is low, and the latter is not recommended. In this study, the grid is closed and settled in the second method.
The overall process of the grid trading operation is shown by the grid trading operation flow chart in Figure 4.

Concept and Architecture of Flexible Grid
Based on the equal-distance and equal-ratio grid trading models used in the financial market today, this study proposes a new and adaptive grid trading model: flexible grid. Through a more flexible grid structure combined with the SSO algorithm and DL, a grid trading model that can adjust parameters according to market changes and adapt to var-

Concept and Architecture of Flexible Grid
Based on the equal-distance and equal-ratio grid trading models used in the financial market today, this study proposes a new and adaptive grid trading model: flexible grid. Through a more flexible grid structure combined with the SSO algorithm and DL, a grid trading model that can adjust parameters according to market changes and adapt to various external conditions is constructed.
Under the framework of the equal-distance grid trading model, it can exert its maximum model benefits when the market fluctuates. Even if the price returns to the original point, it is still possible to arbitrage from the volatile market situation based on the adoption of the mean reversion strategy in quantitative trading [47]. On the other hand, equal-ratio grid trading can obtain better returns in the volatile rise based on the combination of the two strategies of mean reversion and trend following [48].
The flexible grid proposed in this study captures the advantages of the equal-distance grid and the equal-ratio grid at the same time. It can outperform the traditional grid trading structure of the past whether the market is sideways, rising, or even falling.
When the flexible grid is initially set, it also needs to set its total investment capital F 0 , the initial price P 0 , the upper bound of the grid G ul , the lower bound of the grid G ll , the number of upper grids n u , and the number of lower grids n l . There are two main differences compared with other models in the initial setting: 1.
The number of upper grids n u and the number of lower grids n l in Equation (5) are no longer calculated with Equations (6) and (7) but can be initially set.

2.
The grid is divided into upper and lower parts with the initial price P 0 as the boundary. The upper part and the lower part can set the number of the grids and have their own grid spacing ratio. The ratio of the upper grid spacing is G su and the lower grid spacing is G sl . It should be noted here that G su must be a number greater than 0 and less than 1, and G sl must be a number greater than 1. The feature of this is that the upper grid spacing becomes smaller and smaller as the price is higher, i.e., the trading frequency becomes more and more frequent. Similarly, the lower grid spacing becomes smaller and denser when the price is lower.
The specific calculation method of the grid value is shown in Equations (13) and (14) and the over structure is shown in Figure 5.
The core concept in the design process of the flexible grid is to perform more frequent sell actions when the price is high, and buy the cheaper spot more frequently when the price is lower. The flexible grid has a similar structure to the equal-distance grid in the middle section of the model, while the lower half of the model is more similar to the equal-ratio grid, and the upper half of the model is different from the current common equal-distance grid and equal-ratio grid trading model with higher mesh density at higher prices. The main purpose of this model is to capture the advantages of the equal-distance grid and equal-ratio grid, and can have better performance than the current existing model whether the market trend is volatile, or a continuous rise or fall.
However, in order to truly take advantage of the flexible grid model architecture, the optimal parameter setting and self-adjustment in line with the market situation are crucial determinants for the success or failure of the model. Therefore, this study uses an SSO algorithm to determine the appropriate parameters of the flexible grid in different situations that is described in Section 3.3, and inputs the calculated parameter combination and the corresponding market situation into the artificial neural network (ANN) for model training that is presented in Section 3.4. Finally, this study produces a trained DL model, which can automatically adjust to the grid parameters most suitable for the current market situation by simply inputting the current market situation.
The specific calculation method of the grid value is shown in Equations (13) and (14) and the over structure is shown in Figure 5.  The core concept in the design process of the flexible grid is to perform more frequent sell actions when the price is high, and buy the cheaper spot more frequently when the price is lower. The flexible grid has a similar structure to the equal-distance grid in the middle section of the model, while the lower half of the model is more similar to the equalratio grid, and the upper half of the model is different from the current common equal-

SSO for Optimal Parameters
In this subsection, the SSO algorithm is adopted to adjust the optimal solution of the flexible grid under different market conditions based on the flexible grid constructed in the previous subsection. The market situation and the optimal parameters are input into the ANN as the training set for model training in Section 3.4.

Objective and Constraint
The main objective pursued by this study is to maximize the investment return. Therefore, the market investment commodity price is set by the SSO algorithm after the j period of update. The objective model is shown in Equation (15).
where S j , P j , and C j represent the spot quantity, the commodity market price, and the funds held in the last period after the initial purchase of spot S 0 and initial holding of funds C 0 are inputted through the price of a total j-periods. In addition, in the flexible grid model, it is necessary to ensure that the profit of each trading is greater than the trading cost h% (usually the trading fee rate) so that the following constraint Equation (16) is set, where i is from 0 to n.
The calculation of g i can refer to Equations (11) and (12). After substitution, it can be found that this constraint is actually a constraint on the grid parameters G ul , G ll , n u , and n l .
On the other hand, additional constraints are placed on the grid upper and lower bounds G ul , G ll , n u , and n l for experiment 1 and experiment 2 as shown in Equations (17)- (19), where x is from 0 to j.
According to the upper and lower bound conditions, each data set is divided into two groups for experiments in Section 4. The first group uses 1.3 times the initial price as the upper bound of the grid, and 0.7 times the initial price as the lower bound of the grid; while the second group uses 1.5 times the initial price as the upper bound of the grid, and 0.5 times the initial price as the lower bound of the grid. Namely, (G ul , G ll ) = (P 0 × 1.3, P 0 × 0.7) and (G ul , G ll ) = (P 0 × 1.5, P 0 × 0.5).
10 < n l < The above four constraints are to keep the error space and avoid the overfitting of subsequent ANN training, which cause the price to easily exceed the upper and lower limits of the grid resulting in losing arbitrage opportunities, and control the parameters within a reasonable range.

Solution Encoding
According to Section 3.3.1, the construction of a grid trading model must be set by the total investment F 0 , initial price P 0 , grid upper bound G ul , grid lower bound G ll and total number of grids n. In this study, F 0 and P 0 are control variables, hence, the parameters to be solved by SSO are G ul , G ll and n. In flexible grid, the total number of grids n can be divided into the number of upper grids n u and the number of lower grids n l .
The solution range is shown in Table 1.
In common use Number of upper grids n u [P 0 × 100/(maximum P x × 1.
3)] − 10 10 Number of lower grids n l [P 0 × 100/(maximum P x × 1. 3)] − 10 10 The solution encoding in this study is shown in Figure 6, for which x 1 , x 2 , x 3 , and x 4 are set as the grid upper bound G ul , the grid lower bound G ll , the number of upper grids n u , and the number of lower grids n l , respectively. lectronics 2022, 11, 3259 13 The above four constraints are to keep the error space and avoid the overfittin subsequent ANN training, which cause the price to easily exceed the upper and l limits of the grid resulting in losing arbitrage opportunities, and control the param within a reasonable range.

Solution Encoding
According to Subsection 3.3.1, the construction of a grid trading model must b by the total investment F0, initial price P0, grid upper bound Gul, grid lower bound G total number of grids n. In this study, F0 and P0 are control variables, hence, the param to be solved by SSO are Gul, Gll and n. In flexible grid, the total number of grids n ca divided into the number of upper grids nu and the number of lower grids nl.
The solution range is shown in Table 1. The solution encoding in this study is shown in Figure 6, for which x1, x2, x3, a are set as the grid upper bound Gul, the grid lower bound Gll, the number of upper nu, and the number of lower grids nl, respectively.

Gul
Gll nu nl X: x1 x2 x3 x4 For example, when X = (150, 100, 10, 30), it means the grid upper bound is 150 grid lower bound is 100, the number of upper grids is 10, the number of lower grids and the total number of grids is 40.

Parameter Setting and Scope of Update Mechanism
This study adopts SSO algorithm to solve the studied problem, where ρ is a ran number subjects to uniform distribution between [0, 1], and the solution of the proble updated according to this random number: when ρ is between [0, Cg), the variable x replaced by the global best solution gj that is the best performing solution among a For example, when X = (150, 100, 10, 30), it means the grid upper bound is 150, the grid lower bound is 100, the number of upper grids is 10, the number of lower grids is 30, and the total number of grids is 40.

Parameter Setting and Scope of Update Mechanism
This study adopts SSO algorithm to solve the studied problem, where ρ is a random number subjects to uniform distribution between [0, 1], and the solution of the problem is updated according to this random number: when ρ is between [0, C g ), the variable x t+1 i,j is replaced by the global best solution g j that is the best performing solution among all the solutions at present; when ρ is between [C g , C p ), it is replaced by the best solution in the region p i,j that is the optimal solution in the past generations of the variable; when is between [C p , C w ), it maintains the solution of the previous generation x t i,j ; when is between [C w , 1), it is replaced by x that is a random number generated in the upper and lower bounds of the variable. The update mechanism can refer to Equation (2).
The symbols and definitions used in the SSO operation are shown in Table 2. Table 2. Symbols and definitions of SSO.

N var
The number of variables: the grid upper bound G ul , grid lower bound G ll and total number of grids n in this study.
N sol Total number of solutions.

Training ANN to Automatically Adjust Flexible Grid Parameters
After using SSO to obtain the optimal grid configuration under various market conditions, the market conditions and the calculated grid parameters are used as the questions and answers for training ANN training. The market situation is interpreted in terms of the following values and is inputted into the input layer of ANN including the highest price during the period, the lowest price during the period, the average market price, the average trading quantity, the price change (initial price minus final price), the trading quantity change (initial quantity minus final quantity), price standard deviation, and trading quantity standard deviation as shown in Figure 7.
The output layer of the ANN outputs the relevant parameters required to construct a grid trading model including upper bound of the grid, lower bound of the grid, the number of upper grids, and the number of lower grids. The specific ANN architecture is shown in Figure 7.
In the neural network training process, the weights in the ANN nodes continuously adjust themselves through the error value calculated by the loss function until the training is completed when it converges to a state with the smallest error. Afterwards, through this trained neural network, the optimal parameters of the grid trading model can be generated by inputting the recent market state and trend, and a flexible grid model can be automatically constructed for market trading activities.
In this study, two kinds of neural networks are used for training, namely, the FNN and LSTM neural network, which is often used for time series prediction in recent years, to observe and compare which neural networks perform better in learning grid parameters.

Training ANN to Automatically Adjust Flexible Grid Parameters
After using SSO to obtain the optimal grid configuration under various market conditions, the market conditions and the calculated grid parameters are used as the questions and answers for training ANN training. The market situation is interpreted in terms of the following values and is inputted into the input layer of ANN including the highest price during the period, the lowest price during the period, the average market price, the average trading quantity, the price change (initial price minus final price), the trading quantity change (initial quantity minus final quantity), price standard deviation, and trading quantity standard deviation as shown in Figure 7.

Experimental Results
The data sets used for validation and comparison in this study are Standard & Poor's 500 (S&P 500), NASDAQ Composite, Dow Jones Industrial Average (DJIA), Eu-ro Stoxx 50, and Shanghai Composite, a total of five large-cap indices from 2011 to 2022.

Verification of Flexible Grid Performance with Fixed Parameters
First, the performance of flexible grid is compared with equal-distance grid and equalratio grid based on the same grid number and upper and lower bounds. The results that the best results are marked in bold can be found in Tables 3-5. The number of grids is calculated by Equation (20) to be close to the real investment situation and to ensure the adequacy of the use of funds. According to the upper and lower bound conditions, each data set is divided into two groups for experiments. The first group uses 1.3 times the initial price as the upper bound of the grid, and 0.7 times the initial price as the lower bound of grid; while the second group uses 1.5 times the initial price as the upper bound of the grid, and 0.5 times the initial price as the lower bound of grid. Table 3. ROI obtained by flexible grid, equal-distance grid, and equal-ratio grid.

Grid Type Flexible Grid Equal-Distance Equal-Ratio
S&P 500 (G ul ,G ll ) = (P 0 × 1.3,P 0 × 0.7) (G ul ,G ll ) = (P 0 × 1.5,P 0 × 0.5)  Table 5. Sharpe ratio obtained by flexible grid, equal-distance grid, and equal-ratio grid.  Tables 3-5, it can be verified that the flexible grid obviously obtains the best ROI, accumulated wealth, and Sharpe ratio through trading with the same grid parameters under 10-year fluctuations of five different composite indices. Overall, flexible grid appropriately delays the entry and exit timing due to its trading structure, and obtains a relatively high ROI and Sharpe ratio.

SSO Parameter Setting
Part of the dataset is then used to select appropriate SSO parameters for all subsequent experiments.
In the first set of experiments, C g , C p , C w are configured as shown in Table 6, which the best results are marked in bold. The meaning is to divide the range of random number ρ into four parts according to 7:1:1:1, and the part with this ratio is assigned to gbest, pbest, x t+1 i,j and a proposed solution in turn in the experiment to detect what kind of the solution has more critical influence on producing better quality solutions. From Table 6, a better quality solution can be found when gbest is the largest and robust at the same time. Therefore, the probability of gbest is set to the maximum in the final parameter configuration.
After it is determined that gbest is set as the maximum probability, the range of random number ρ is then divided into four parts according to 5:3:1:1. Among them, the probability of taking gbest as the solution is set to the maximum 0.5 because gbest has been determined in the previous step as the key factor to generate a good quality solution, and the probability of 0.3 is assigned to pbest, x t+1 i,j and a new solution in turn. According to the experimental results, the solution that is the second key factor in producing a better solution, is shown in Table 7, which the best results are marked in bold.  Table 7 shows that it can produce a better quality solution when the new random solution is larger, and it is robust at the same time. Therefore, the probability of the new random solution is set to the next largest in the final parameter configuration.
After it is determined that the new random solution is set as the next largest probability, the range of random number ρ is then divided into four parts according to 3:3:3:1. The subsequent steps are analogous to the first two steps, and Table 8 that the best results are marked in bold is obtained as follows. It can be found that x t+1 i,j and pbest have little difference in the quality of the solution, thus, both probabilities are set to the minimum.

Verification of Flexible Grid Performance with Parameters Selected by SSO
After setting the SSO parameters, the flexible grid, the equal-distance grid, and the equal-ratio grid are connected to the parameters selected by SSO, respectively. Additionally, solutions with 10 runs, 20 generations per run, and 100 sets of solutions per generation are found. Two sets of experiments, which is same as the previous verification of flexible grid architecture, are also conducted with the upper and lower bounds of different risk levels. The results that the best results are marked in bold are shown in Tables 9-11. Table 9. ROI obtained by flexible grid, equal-distance grid, and equal-ratio grid with SSO parameters.

Grid Type Flexible Grid Equal-Distance EQUAL-RATIO
S&P 500 (G ul ,G ll ) = (P 0 × 1.3,P 0 × 0.7) (G ul ,G ll ) = (P 0 × 1.5,P 0 × 0.5) From the results in Tables 9-11, it can be verified that in the application of SSO to solve the grid trading parameters, the flexible grid is still the best model in terms of ROI, accumulated wealth, and Sharpe ratio compared with the equal-distance grid and equal-ratio grid. In addition, comparing the grid trading results connected with the SSO parameters and the fixed parameter version, it can be found that the ROI has increased significantly. The overall ROI results reveal that the flexible grid is the best, the equaldistance grid is the second, and the equal-ratio grid is the worst.

Training ANN to Automatically Adjust Flexible Grid Parameters
After confirming the excellent performance of the flexible grid using SSO to search for trading parameters, the flexible grid and SSO are adopted to record the best trading parameters of each index in 10 years, and obtain a set of trading parameters every 30 days. In order to expand the follow-up training and data, the moving pace of the model is set to 5. In each index, about 500 pieces of parameter data are obtained for the training and verification of ANN, in which the data of the first nine years is used as the training set and the data of the last year is used as the validation set.
Because the data of the training set in this study have temporal continuity, the data are re-randomly ordered before training in the FNN in order to avoid affecting the training results of the model. In the LSTM neural network, the input training data must be sequential because the model design, and thus the training data, do not need to be re-ordered randomly.
The architecture of the FNN and the LSTM neural network has undergone many experiments, and the final architecture and hyper-parameter settings are shown in Tables 12 and 13. The input parameters are eight variables which describe a market situation: the highest price during the period, the lowest price during the period, the average market price, the average trading quantity, the price change, the trading quantity change, price standard deviation, and trading quantity standard deviation. In addition, the output variables are set to upper bound of the grid, lower bound of the grid, the number of upper grids, and the number of lower grids for grid trading.
The number of hidden layers is set to three. The optimizer is set to adam, which has been common in recent years, with a fast convergence speed and excellent performance in searching solution. The excitation function uses sigmoid and relu, and the loss function adopts a mean squared error, which is commonly used in regression problems.
After the neural network training set above, the training and comparison results are presented in Tables 14 and 15, which the best results are marked in bold. Results of the mean square error of values for the output layer including upper bound of the grid G ul , lower bound of the grid G ll , number of upper grids n u , and number of lower grids n l (shown in Equation (20)) are shown in Table 14. With the exception of the upper and lower bound of the grid in the Nasdaq 100 index, LSTM has a smaller mean square error. All four output variables in the other indices have a smaller mean square error; the mean square errors of the four output variables in other indices are all FNN, which perform better. The coefficient of determination (R square) of the two models, which is an index to measure the fitness of the regression model and can also be interpreted as the degree of interpretation of the model, as shown in Table 15 is calculated based on Equation (21). For example, the meaning of 90.490% in the second row of Table 15 means the coefficient of determination (R square) of the upper bound of the grid G ul for S&P 500 obtained by LSTM equals 90.490%, i.e., the fitness of the regression model of upper bound of the grid G ul for S&P 500 obtained by LSTM equals 90.490% and can also be interpreted as the degree of interpretation of upper bound of the grid G ul for S&P 500 obtained by LSTM equals 90.490%. And the best results are marked in bold in Table 15. In Table 15, it can be found that except for the Nasdaq 100 index, most of the time, FNN has a better fit for the four output variables.
Furthermore, the four values of ROI, Maximum Drawdown (MDD), volatility, and Sharpe ratio are used to examine the performance of the model in this study. In terms of methods include first Buy and last Sell (Buy and Sell, B&S), first Sell and last Buy (Sell and Buy, S&B), Grid Trading System Robot (GTSbot) [10], Ichimoku Equilibrium Figure (IK) [12], Flexible Grid trained with FNN (FG-FNN), Flexible Grid trained with LSTM (FG-LSTM), equal-distance grid, equal-ratio grid, and flexible grid; a total of nine methods for comparison.
First, the formula of ROI can refer to Equation (22), which is the most common indicator of quantitative investment performance in investment sciences. The calculation of the ratio of investment income to cost usually presents as an annualized return to total return. The trading costs, including handling fees, are included in the calculation results. The results that the best results are marked in bold are shown in Table 16. In terms of ROI, the FNN flexible grid achieves the top three returns in each index. In particular, the FNN flexible grid has the most ability to control the overall loss in the downward trend of prices.
Second, the comparison is the maximum drawdown, i.e., the amount of income that has fallen sharply in all periods, which is one of the indicators for evaluating investment risk. Results that the best results are marked in bold are shown in Table 17. In terms of the maximum drawdown, it can be found that the method with a larger return on investment has a relatively higher maximum drawdown, which verifies the theory of high risk and high return in investment science. There are two reasons for the performance of the FNN flexible grid on the MDD. The risk is relatively high in the case of a relatively high return on investment. In addition, the parameters of each period are calculated by the neural network. If the parameters predicted on one period are particularly poor, it is likely to cause a large drop in a single period. Whether this MDD condition can be regarded as a single condition of outliers is yet to be verified by volatility.
In quantitative trading, risk and model stability are assessed through its volatility. The calculation method refers to Equation (23) and the results that the best results are marked in bold are shown in Table 18.
It can be found from Table 18 that the performance of the FNN flexible grid on volatility is the top three in each index, i.e., the performance of FNN flexible grid is very stable compared with other methods. It can also be speculated that the poor performance on the MDD may be a single event, and it can be regarded as a robust investment model in most cases. The LSTM flexible grid is the best among all models in the S&P and Nasdaq data sets and is a less risky and more robust investment model. Finally, in terms of the Sharpe ratio, which is a model performance indicator that calculates the ratio between investment return and risk, it can also be interpreted as the reward that can be exchanged for each unit of risk. The calculation method refers to Equation (24) and the results that the best results are marked in bold are shown in Table 19. From Table 19, it can be found that the Sharpe ratio of FNN flexible grid is the best among all methods on the four indices. In the falling market situation, in addition to short selling, its Sharpe ratio is also the largest. From this, it can be found that the FNN flexible grid can obtain the highest reward for each unit of risk.

Conclusions
In addition to proposing a new grid trading architecture, this study effectively improves the ROI of the original model, improves the drawbacks of premature entry and exit, and utilizes SSO algorithm and ANN to assist grid trading for parameter selection and providing the model the ability to adapt to the market. In terms of model performance, five major market indices are used as verification data, which cover the United States, Europe, and China. The FNN flexible grid performs very well in Sharpe ratio. It has excellent investment return rate and model robustness, and can properly control the balance between risk and return.
This study proves that the technology combined with AI can bring breakthroughs to the original grid trading model in quantitative trading, and can adapt to various rapidly changing market situations. In the future, more related extended research is needed so that the grid trading model can more accurately be closer to human decision making or even better than human judgment when adjusting parameters to eliminate human impulses and market emotions, and make rational market trading decisions to obtain better investment benefits.