A function to loop through open positions and make pairs of arrays of tickets then close each pair of array if greater than target profit

MQL4 Experts

Trabalho concluído

Tempo de execução 6 minutos
Comentário do cliente
very good!
Comentário do desenvolvedor
Great customer! Thank you for the order!

Termos de Referência

This is for an MT4 EA.

I need a function to loop through all open positions and store them in arrays based on price levels.
Then from these arrays (i.e. @ price 1760 there are open orders and @ price 1770 there are open orders and so on).
I want to calculate the ongoing profit of pairs of 2 arrays (i.e. sell array i with buy array i+1     AND    buy array i with sell array i-1).
And if profit is greater than target, close orders of these pairs of arrays. Each array may contain more than 1 ticket and can go up to x tickets, and the function will close the arrays only if the pairs contain minimally an array in each level.
The function will loop through all the arrays crawling from initial price up and down.
An optional function can also close the pairs of arrays if the total tickets in these pairs are x (can be input).
Code is already written, but i currently have problem with :

void CalculateAndCloseOrderGroupsForBuyAndSell() {
    // Loop from the initial_index down to 1 (since i-1 sell for i=0 doesn't exist)
    for (int i = initial_index; i > 0; i--) {
        double totalProfit = 0.0;
        
        if (buyTicketCounts[i] > 0 && sellTicketCounts[i-1] > 0){
           // Calculate profit for all buy tickets at index i
           for (int j = 0; j < buyTicketCounts[i]; j++) {
               int ticket = buyTickets[i][j];
               totalProfit += ComputeProfitForOrder(ticket);
           }
   
           // Calculate profit for all sell tickets at index i-1
           for (int j = 0; j < sellTicketCounts[i - 1]; j++) {
               int ticket = sellTickets[i - 1][j];
               totalProfit += ComputeProfitForOrder(ticket);
           }
          }

        // If the combined profit meets or exceeds the target, close the tickets and remove them from arrays
        if (totalProfit >= profit_target) {
            // Close and remove buy tickets at index i
            for (int j = buyTicketCounts[i] - 1; j >= 0; j--) {
                CloseOrder(buyTickets[i][j]);
                // Shift tickets to remove the closed ticket from the array
                for (int k = j; k < buyTicketCounts[i] - 1; k++) {
                    buyTickets[i][k] = buyTickets[i][k + 1];
                }
                buyTicketCounts[i]--;
            }

            // Close and remove sell tickets at index i-1
            for (int j = sellTicketCounts[i - 1] - 1; j >= 0; j--) {
                CloseOrder(sellTickets[i - 1][j]);
                // Shift tickets to remove the closed ticket from the array
                for (int k = j; k < sellTicketCounts[i - 1] - 1; k++) {
                    sellTickets[i - 1][k] = sellTickets[i - 1][k + 1];
                }
                sellTicketCounts[i - 1]--;
            }

            Print("Closed and removed orders for buy zone ", i, " and sell zone ", i - 1, " with total profit: ", totalProfit);
        }
    }
}


it always gives me "out of array" error. I will give the whole set of code. the focus is to fix this part to overcome the "out of array" issue/ error.


Thank you.




Respondido

1
Desenvolvedor 1
Classificação
(100)
Projetos
125
23%
Arbitragem
12
0% / 75%
Expirado
22
18%
Livre
2
Desenvolvedor 2
Classificação
(68)
Projetos
77
8%
Arbitragem
33
9% / 55%
Expirado
6
8%
Trabalhando
3
Desenvolvedor 3
Classificação
(45)
Projetos
74
49%
Arbitragem
1
0% / 0%
Expirado
1
1%
Trabalhando
4
Desenvolvedor 4
Classificação
(23)
Projetos
45
20%
Arbitragem
24
29% / 46%
Expirado
12
27%
Livre
5
Desenvolvedor 5
Classificação
(64)
Projetos
93
37%
Arbitragem
11
27% / 45%
Expirado
14
15%
Livre
6
Desenvolvedor 6
Classificação
(451)
Projetos
510
33%
Arbitragem
25
40% / 48%
Expirado
7
1%
Ocupado
7
Desenvolvedor 7
Classificação
(6)
Projetos
10
10%
Arbitragem
8
0% / 88%
Expirado
1
10%
Trabalhando
8
Desenvolvedor 8
Classificação
(66)
Projetos
143
34%
Arbitragem
10
10% / 60%
Expirado
26
18%
Livre
9
Desenvolvedor 9
Classificação
(568)
Projetos
641
41%
Arbitragem
21
57% / 29%
Expirado
47
7%
Trabalhando
Pedidos semelhantes
I am looking to develop an automated trading bot based on a strategy involving the crossing of four Simple Moving Averages (SMA). The bot should be capable of entering trades based on this strategy. Additionally, I would like to incorporate some custom diversions tailored for NinjaTrader
Seeking an experienced MQL5 developer to create a sophisticated Expert Advisor focused on harmonic pattern trading . The EA will be designed to identify and trade based on popular harmonic patterns in the forex market. Entry and Exit Logic: Develop smart entry and exit rules based on pattern completions and price action confirmations. Risk Management: Incorporate adjustable risk-per-trade settings and position sizing
preciso de um robô com duas médias móveis, uma exponencial high e uma exponencial low. preciso também ter a opção de utilizar e todos os tempos gráficos e alterar os parâmetros das médias. entrada de compra será feita quando um candle de alta romper e fechar a cima da média high e fechará a posição quando um candle de baixa romper e fechar a baixo da média low. a venda será feita quando o candle de baixa romper e
Description - An expert advisor(s), placing sell trades in EUR/USD, based on the close price of the previous two candles, as shown in the figure below. The trades would be made in the 5 minute, 1 hour, and 1 day timeframes. In the 5 minute and 1 hour timeframes the market orders would be placed at the start of a new candle, at specific times EST. The order would be cancelled at the close of that candle, i.e after 5
Hi, I have an indicator from my friend, I want to copy it to my own Traidingview or MT5 can you do that for me. Here is the link
Develop a simple trading robot from rainbow oscillator Additional features Include timeframe specification in rainbow oscillator trailing features moving average filter TP (true/false) SL (true/false) Fixed lot Risk percentage Percentage profit lock
Hi, I have an indicator from my friend, I want to copy it to my own Traidingview or MT5 can you do that for me. Here is the link
I need a dashboard that shows my various accounts that shows balance, equity, number of trades open, drawdown and some more information. I want to use it to monitor my accounts in one screen or chart. If there is anyone who can do it please show me the screenshot of your sample
Hi, I need a robot, which wil get instructions to trade in 3 symbols at the same time based on few parameters and calculations. Example: There is 1 symbol called Gold-Near and the rate for it is 1000-1002 If i specify that when the rate reaches 1050, it should sell 1 lot Upon execution it will have to sell 1 lot of cme gold, buy 3 lots of mcx gold and buy currently (lots will be based on calculation). All the
Trading bot 300+ USD
We need bot that trades when medium and low impact news hits It will release pending order both directions few min prior to news impact And will have certain risk management strategy attached Example If Monday and Tuesday news successful clears profits It will reduce risk for next news events until new week starts each week message on tg: Dstatewealthtrading NOTE: 4 YAERS OF EXPERIENCE UPWORD, YOU MUST BE A

Informações sobre o projeto

Orçamento
30 - 45 USD
IVA (19%): 5.7 - 8.55 USD
Total: 35.7 - 53.55 USD
Desenvolvedor
27 - 40.5 USD