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 Asesores Expertos

Trabajo finalizado

Plazo de ejecución 6 minutos
Comentario del Cliente
very good!
Comentario del Ejecutor
Great customer! Thank you for the order!

Tarea técnica

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.




Han respondido

1
Desarrollador 1
Evaluación
(100)
Proyectos
125
23%
Arbitraje
12
0% / 75%
Caducado
22
18%
Libre
2
Desarrollador 2
Evaluación
(71)
Proyectos
80
10%
Arbitraje
35
9% / 54%
Caducado
6
8%
Trabaja
3
Desarrollador 3
Evaluación
(46)
Proyectos
75
49%
Arbitraje
1
0% / 0%
Caducado
1
1%
Trabaja
4
Desarrollador 4
Evaluación
(23)
Proyectos
45
20%
Arbitraje
24
29% / 46%
Caducado
12
27%
Libre
5
Desarrollador 5
Evaluación
(65)
Proyectos
95
36%
Arbitraje
11
27% / 45%
Caducado
15
16%
Libre
6
Desarrollador 6
Evaluación
(463)
Proyectos
524
33%
Arbitraje
28
39% / 43%
Caducado
7
1%
Ocupado
7
Desarrollador 7
Evaluación
(6)
Proyectos
10
10%
Arbitraje
9
0% / 78%
Caducado
1
10%
Trabaja
8
Desarrollador 8
Evaluación
(66)
Proyectos
143
34%
Arbitraje
10
10% / 60%
Caducado
26
18%
Libre
9
Desarrollador 9
Evaluación
(568)
Proyectos
641
41%
Arbitraje
21
57% / 29%
Caducado
47
7%
Trabaja
Solicitudes similares
I need a simple panel to execute both buy and sell operations with very basic things like stopp loss take profit that functions for both market orders such as buy stop sell stop buy limit sell limit I don't care about colors or design I just want how you can do it what interests me most are the functions
I want to create an EA that can take bids according to information of a logic I have developed to give indication of a BUY or SELL opportunity. The EA will then be able to activate the BUY at the lowest possible position once the indicator clears it for a BUY and take bid upwards or identify the highest point and clears it for a SELL and take bids downwards. As you can see from example of JULY 2024 data to see how
We are seeking a skilled developer who can convert a Tradingview indicator written in Pinescript to a NinjaTrader indicator written in C#. The goal is to create a profitable trading strategy using this indicator. The successful candidate will have expertise in both Pinescript and C# programming languages, as well as a strong understanding of trading indicators and strategies. The main responsibilities will include
I am seeking an experienced MQL5 developer to create a user-friendly manual Grid Trading Expert Advisor (EA) with the following key features: Dynamic Grid Trading: Adjustable Grid Distance: Traders can manually input grid distance in pips via an intuitive, movable table. Take Profit Management: Fixed TP for the initial positions (e.g., first 5 trades). Stop-Loss (Optional): Traders can choose to use a stop-loss with
I want have the possibility to increase lotsize not alone by Lot-multiplier rather I want add a fix-lot increase for excample for 0,05 lot. I want have this for buy / sell and hedge-buy and hedge sell
Develop EA to track performance metrics of strategies I would like to develop an EA that will track the performance metrics of the strategies I have running on a terminal, If any of the metrics start to under perform then the EA/Indictor should alert me with a pop up alert that specify's the metric that has triggered the alert. The EA should also display the metrics in a dashboard - please see my example screen shot
I would like to modify the RSI Epert Avisor with a developer. I would like to use the RSI Expert on the inverse mode and the base setting doesnt conatain this strategy mode
Profitable EA HFT 50 - 300 USD
From a long time i am searching for a profitable EA i have lost a lot , and now i have only 300$ to buy a profitable EA , i wish to say with 0 losses but some or most traders they don't want to hear this i am really tired of searching for a programmer to just create me a profitable EA with the least losses or zero losses maybe nearly 1 year i am searching i just need an HFT EA that can work very well on MT4,MT5
I need help fixing my EA for MT5. It’s a very simple EA, and I currently cannot solve an issue where webrequest communicates with OpenAi API without error. Please only apply if you can help solve this issue
у нас есть стратегия, нам нужно написать mql5-код ​​для тестера стратегий МТ5,Цена договорная. Мой контакт @abbosaliyev из Telegram Программист должен знать РУССКИЙ ИЛИ УЗБЕКСКИЙ язык. Задание: разработать тестер, который использует шаблон условий на открытие и проверит весь исторический график на всех доступных таймфреймах. Остальная информация будет предоставлена ​​после согласования цены

Información sobre el proyecto

Presupuesto
30 - 45 USD
IVA (19%): 5.7 - 8.55 USD
Total: 35.7 - 53.55 USD
Para el ejecutor
27 - 40.5 USD