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
1
0% / 0%
Overdue
1
1%
Working
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
14
14%
Free
6
Developer 6
Rating
(547)
Projects
630
33%
Arbitration
38
39% / 50%
Overdue
11
2%
Working
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
Hello! Objective Convert an existing MT4 Expert Advisor (MQL4) into MT5 (MQL5) with ABSOLUTELY IDENTICAL trading behavior . This is not a rewrite, enhancement, optimization, or refactor. This is a behavior-preserving port . If the MT5 version does anything different in live conditions, the job is considered failed . Core Requirement — Non-Negotiable The MT5 EA must produce the same results as the MT4 EA under
Specification Hi Free lancers, I need an EA which relates to Sure Fire Hedging EA base on Below parameters needed. Overview how it works: This EA will be able to open a trade with either Buy or Sell selection (manual- to be manually switch buy or sell selection ), another selection for automatic open trading can choose only buy. Once the EA already open trade (example -buy position) with starting lot size 0.01
Hedge Lot Plus EA Descriptions: (New EA) 1- The necessary explanations, documentation, and working principle details will be provided after the contract is signed. 2- The chart, button, and dashboard- template sample code will be provided. 3- There is no indicator. and work principle is easy. ** After the contract is signed,sampe code, a sample EA for "Hedge Lot Plus EA" and detailed information about the working
Experienced developer needed for a $100 project. I need to build three trading bots to copy signals from a Telegram channel and execute them on a trading account. The first bot will be used in the second and third bots as well, with some minor modifications. I will pay $40 for the first bot, $30 for the second, and $30 for the third. Contact me for details
1- Parts to Be Updated in Universal EA: 1- For Mode 2 (No Indicator Mode), a candle count parameter will be added for pivot breakout. The EA will determine how many candles after the pivot breakout it will add a position based on this parameter. 2- In Mode 1 (MA Mode), we will fix the error in one of the "Select Take Profit" modes called "Kill Position + Clean One by One." 3- We will fix the errors in Recovery Mode
I would manually draw one or more trendline or horizontal line in MT5. I would manually add description to each trendline or horizontal line for the desired action: Buy, Sell, Close buy orders, Close sell orders or Close all orders. When a candle touches the trendline or horizontal line, EA should execute the desired action. The desired action must be only once for a trendline or horizontal line. There should be some
Data Integrity 500 - 1000 USD
The trading bot is an automated software system designed to monitor financial markets, execute trades, and manage risk based on predefined strategies. The bot aims to maximize profits while minimizing human intervention and emotional decision-making. Scope: Supports automated trading on selected exchanges (e.g., Binance, Bitget, Coinbase). Executes trades based on technical indicators, signals, or AI models. Provides
1. General Objective Development of an Expert Advisor in MQL5 intended for Futures markets , based on an existing trading strategy that I will provide (described logic or precise rules). The main objectives are: Faithful implementation of the strategy , Full debugging of the EA, Validation of correct behavior through backtesting. 2. Markets and Instruments Markets: Futures Symbols: to be defined (e.g. indices
Subject: Major Upgrade Request: Auto Confluence of Signal/Trend/Momentum Scores with Multi-Timeframe SMC Hello, Your bot is excellent analytically, but I'm facing daily manual intervention due to the multiple indicators and timeframes. --- 📊 Current Situation: The bot uses: · Signal Score · Trend Score · Momentum Score · SMC Analysis · 3 Timeframes (Fast 5M, Medium 15M, Main 1H) · 4 Additional Indicators Currently
SMC Trading Bot 30 - 60 USD
1. The Core Idea: The "Liquidity-to-Liquidity" Engine Instead of just looking for a "Supply Zone," the bot must ask: "Whose money was just taken, and whose money are we targeting next?" The "Valid Move" Checklist A structure break or a zone is only "Real" if it meets the SMC Trinity: Inducement/Sweep: Price must take out a previous minor high/low (Retail Stop Loss) before the move. Displacement: The move must be

Project information

Budget
30 - 45 USD