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
Projects
125
23%
Arbitration
12
0% / 75%
Overdue
22
18%
Free
2
Developer 2
Rating
Projects
80
10%
Arbitration
38
8% / 58%
Overdue
6
8%
Free
3
Developer 3
Rating
Projects
91
52%
Arbitration
2
0% / 50%
Overdue
1
1%
Free
4
Developer 4
Rating
Projects
45
20%
Arbitration
25
28% / 48%
Overdue
12
27%
Free
5
Developer 5
Rating
Projects
97
35%
Arbitration
11
27% / 45%
Overdue
13
13%
Free
6
Developer 6
Rating
Projects
711
33%
Arbitration
45
49% / 42%
Overdue
14
2%
Working
7
Developer 7
Rating
Projects
10
10%
Arbitration
9
0% / 89%
Overdue
1
10%
Free
8
Developer 8
Rating
Projects
146
34%
Arbitration
13
8% / 62%
Overdue
26
18%
Free
9
Developer 9
Rating
Projects
641
41%
Arbitration
25
48% / 36%
Overdue
46
7%
Working
Similar orders
I need a developer that can make my trading strategies into a working perfect EA Robot working on Mt5. Candlestick pattern confirmation through PDH, PDL, PWH, PWL, Liquidities, HTF OB
I need a trading bot specially for XAU, high profit gain. Requirements bot analyzes the market places trades closes with 2 to 3 profit per trades daily profit should be 50 to 100 dollars
We are looking for an experienced MQL5 developer to provide a stable, consistently profitable Forex Expert Advisor (EA) capable of generating 10–15% average monthly returns while maintaining the lowest possible drawdown . Our Requirements The EA must have a proven track record of consistent performance. A long-term trading history (live or verified) will be considered a significant advantage. Before final selection
I am looking for a professional MQL5/MT5 Expert Advisor developer to build a fully automated trading bot based on my custom strategy. Requirements: Strong experience in MQL5 (MetaTrader 5) Previous experience developing Forex/Gold Expert Advisors Ability to convert a trading strategy into a fully automated EA Clean, well-structured, and optimized code Good communication and willingness to provide updates during
Forex Growth 60 - 100 USD
Customer Information Name: John Smith Email: john.smith@example.com Company: ABC Trading Ltd. Platform MetaTrader 5 (MT5) Market Forex Trading Instruments EURUSD GBPUSD XAUUSD Trading Strategy The robot should trade based on a trend-following strategy: Buy: When the 50 EMA crosses above the 200 EMA and RSI is above 55. Sell: When the 50 EMA crosses below the 200 EMA and RSI is below 45. Close trades when Take Profit
Only programmers with experience with orderflow please, it's not the easiest project, I don't want to have arbitration etc. I am not expert in orderflow yet, if you have suggestion about strategy it would be very nice. Source of code required, I am searching a programmer for a longer co-operation
Please create an simple EA in mql5 based on RSI indicator with e-mail, sounds and push notification alerts, of course can't be any bugs, errors, but I think it's obvious. I am searching a programmer for longer co-operation. Thank you for your attention, Have a nice day
Hi, I am looking for an already made profitable EA. It can be an indicator but then it must be possible to make an EA from the indicator. Will need to test before payment (this can be in demo or limited time test). I will pay up to $6000. Do not apply if you want an upfront payment. I need to test for a few times first. Mostly only pips matters. I look much the risk safety, money management, risk reward, and overall
Привіт. Шукаю когось, хто б застосував мій код як бота . Я торгую індексом Aus_200 SFE (не XJO). Бот базується на MACD входу/виходу, RSI, стохастиці та vwap. Як тільки роботу приймуть, мені потрібно внести кілька коректив; однак, нічого суттєвого. Дякую
SMC Martingale Pro is an advanced MetaTrader 5 Expert Advisor designed for high-volatility markets like XAU/USD. It combines institutional Smart Money Concepts with a dynamic risk recovery system. Key Features Dual FVG Engine: Automatically identifies and renders both bullish and bearish Fair Value Gaps in real time. Multi-Timeframe Flexibility: Operates independently of the active chart timeframe to target

Project information

Budget
30 - 45 USD