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 Эксперты

Работа завершена

Время выполнения 6 минут
Отзыв от заказчика
very good!
Отзыв от исполнителя
Great customer! Thank you for the order!

Техническое задание

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.




Откликнулись

1
Разработчик 1
Оценка
(100)
Проекты
125
23%
Арбитраж
12
0% / 75%
Просрочено
22
18%
Свободен
2
Разработчик 2
Оценка
(72)
Проекты
80
10%
Арбитраж
38
8% / 58%
Просрочено
6
8%
Свободен
3
Разработчик 3
Оценка
(53)
Проекты
91
52%
Арбитраж
2
0% / 50%
Просрочено
1
1%
Свободен
4
Разработчик 4
Оценка
(23)
Проекты
45
20%
Арбитраж
25
28% / 48%
Просрочено
12
27%
Свободен
5
Разработчик 5
Оценка
(67)
Проекты
97
35%
Арбитраж
11
27% / 45%
Просрочено
13
13%
Свободен
6
Разработчик 6
Оценка
(550)
Проекты
637
33%
Арбитраж
41
41% / 46%
Просрочено
11
2%
Занят
7
Разработчик 7
Оценка
(6)
Проекты
10
10%
Арбитраж
9
0% / 89%
Просрочено
1
10%
Свободен
8
Разработчик 8
Оценка
(69)
Проекты
146
34%
Арбитраж
13
8% / 62%
Просрочено
26
18%
Свободен
Опубликовал: 6 примеров
9
Разработчик 9
Оценка
(568)
Проекты
641
41%
Арбитраж
25
48% / 36%
Просрочено
46
7%
Работает
Похожие заказы
Hi coders, I am looking for profitable ea which can generate 4-5% a month with stable drawdown ✅ Demo version for testing (few days is fine) ⚠️ Backtest alone is NOT enough 💰 I am ready to pay a strong price for the right professional-grade Thank you, and I look forward to reviewing serious offers
Key Requirements: Source Account: Connect to a Master account using Investor (Read-only) Password. Destination Account: Execute trades on a Live Slave account with full trading access. Currency Focus: The system must handle Currency Pairs accurately, including symbol mapping (e.g., EURUSD to EURUSD.m) between different brokers. Stealth Features: Remove/Disable all trade comments. Assign custom Magic Numbers to the
I need a developer to start robot from scratch based on existing EA that is running live. I do not have the source file as my previous coder did not give it to me. What I do have is the investor password which is running the EA from the coder side but not from my end. I like someone to monitor the account and re create the same system for me
I am looking to purchase a professional MT5 Expert Advisor that can trade multiple currency pairs at the same time . I am not looking for a custom-built EA . I want to buy an already existing, fully developed EA with the complete source code (.mq5) . Important Conditions Please contact me only if : • You own the EA • You can provide the full source code (.mq5) • The EA is already developed and tested • You are
Project Overview: I am looking for a highly experienced MetaTrader 4 (MQL4) developer to build a sophisticated automated trading system. This is not a standard grid bot; it requires complex trade management, dynamic exposure rebalancing, and a custom "Salami" liquidation module for partial loss mitigation . Key Features to Implement: Virtual Grid & Dynamic Trend: Price-action-based grid triggers without pending
Spread filter: Do not trade if spread > 35 points Retest tolerance: 5 pips from breakout level Break structure defined as recent swing high / swing low on M5 Project Description: Project Description: I am looking for an experienced MT5 developer to build a professional Expert Advisor for XAUUSD based on a structured trend-following breakout strategy. This EA must be built with strict risk management rules (no
ищу разработчика для создания мультивалютного сетевого советника (желательно говорить на руском языке - для лучшего понимания моих технических задач) прошу обратить внимание я не торгуюсь в тех задание будет всё указанно и оговоренная сумма подразумевает выполнение задание а не торговля
hi i am looking for profitable ea which can generate 4-5% a month with stable drawdown . no martingales or grid or dca method will be used ,should be based on price action with tp and sl
We are looking for a professional developer or trader who already has a proven profitable EA or strategy based mainly on price action logic. Important requirements: No Martingale No Grid No Micro-scalping Avoid heavy indicator-based strategies Strategy should be based mainly on price behavior / market structure We are not looking for aggressive systems that promise unrealistic returns. Our focus is on stable
I run an ea it makes good profits bit that one bad grid blows up the account. I want an EA which runs parallel to it which can intelligently close bad trades or grids. It shouldn't close recoverable trades but close very bad entries and grids. It can even close with hedging. The goal recover max and also not blow up the account

Информация о проекте

Бюджет
30 - 45 USD