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

Job finished

Execution time 6 minutes
Feedback from customer
very good!
Feedback from employee
Great customer! Thank you for the order!

Specification

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.




Responded

1
Developer 1
Rating
(100)
Projects
125
23%
Arbitration
12
0% / 75%
Overdue
22
18%
Free
2
Developer 2
Rating
(72)
Projects
80
10%
Arbitration
38
8% / 58%
Overdue
6
8%
Free
3
Developer 3
Rating
(53)
Projects
91
52%
Arbitration
2
0% / 50%
Overdue
1
1%
Free
4
Developer 4
Rating
(23)
Projects
45
20%
Arbitration
25
28% / 48%
Overdue
12
27%
Free
5
Developer 5
Rating
(67)
Projects
97
35%
Arbitration
11
27% / 45%
Overdue
13
13%
Free
6
Developer 6
Rating
(555)
Projects
642
33%
Arbitration
41
41% / 46%
Overdue
11
2%
Loaded
7
Developer 7
Rating
(6)
Projects
10
10%
Arbitration
9
0% / 89%
Overdue
1
10%
Free
8
Developer 8
Rating
(69)
Projects
146
34%
Arbitration
13
8% / 62%
Overdue
26
18%
Free
Published: 6 codes
9
Developer 9
Rating
(568)
Projects
641
41%
Arbitration
25
48% / 36%
Overdue
46
7%
Working
Similar orders
Logic: Healthy → no action Weak → reduce exposure Danger → strong protection Requirements: Equity tracking Basic trade management Simple dashboard Only apply if you understand risk-based EA logic
Mani 30 - 50 USD
Title: MT5 Martingale EA (Based on Stop Loss of Previous Trade) Description: Hello, I need a simple and efficient MT5 Expert Advisor based on a martingale logic. Main Logic: The EA should work with trades placed manually or by another EA (including limit orders). When a trade hits Stop Loss, the EA must automatically open a new trade in the same direction. The lot size of the new trade should be multiplied
Existing EA 30 USD
I’m looking to acquire an existing, profitable Expert Advisor (EA) with full source code to add to our client investment portfolio. To be clear, this is not a request to develop or design a new strategy. If you already have an EA that is proven, consistent, and production-ready, I’m open to reviewing it immediately. Please apply only if you meet all the requirements below. Submissions without a proper introduction or
Leonard Quantum FX 80 - 120 USD
I want the EA to be fully automated and capable of taking trades across multiple timeframes. It should be optimized for a starting account balance of $100 with proper risk management suitable for a small account, and it will be used with the broker ApexMarket.io. ⸻ Platform • Platform: MetaTrader 5 (MT5) • Type: Fully automated Expert Advisor • Operation: Hands-free (no manual trade management required) ⸻ 📈 Markets
Wealthy bot 50 - 200 USD
‎Build a mobile-based trading bot system integrated with MetaTrader 5 that specializes in high-frequency “machine gun” style trading on synthetic indices (crash 50 and Crash 300). ‎ ‎The bot must continuously scan the market in real-time using M1 and M5 timeframes and execute frequent trades based on probability, not prediction. Its core function is to detect early signs of potential reversals by analyzing combined
Preciso de um especialista completo, totalmente profissional, que trabalhe com o indicador Hull Moving Average. Que faça entradas exatamente na mudança de cores com base no Exp_ColorHma, de Nikolay e também com a opção de entrada exatamente no cruzamento de duas Hull Average Moving(não na próxima vela), uma lenta e outra rápida. O programador deverá fazer um trabalhado de profissional. Dispenso curiosos ou
Tebza ngwenya 30 - 100 USD
Just know your deal,if you don't know what you are up to I gotchu. This is my first time trying also so yeah, but otherwise if you looking for something grand I'm here, if you got offered me well you in for some great time
Looking to acquire an existing, profitable Expert Advisor (EA) with full source code to add to our client investment portfolio. To be clear, this is not a request to develop or design a new strategy. If you already have an EA that is proven, consistent, and production-ready, with at least 6 months of history performance I’m open to reviewing it immediately. Please apply only if you meet all the requirements below
EA Script editor 30 - 35 USD
I need someone who will help me with a script that supports / cancels out negative positions. So that with a deposit of 600 euros, it doesn't close 300 euros. More info on pv
Pips Muncher 30 - 35 USD
I need a good programmer to creat an ea that will open a trade once the parametres i set are met on the chat that i place it on. The Ea will not need to do any analyses as i would do that manually. It only needs to execute a trade when all the conditions that i will be sending meets. The ea will add stop loss an Tp

Project information

Budget
30 - 45 USD