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
(72)
Proyectos
80
10%
Arbitraje
38
8% / 58%
Caducado
6
8%
Libre
3
Desarrollador 3
Evaluación
(53)
Proyectos
91
52%
Arbitraje
2
0% / 50%
Caducado
1
1%
Libre
4
Desarrollador 4
Evaluación
(23)
Proyectos
45
20%
Arbitraje
25
28% / 48%
Caducado
12
27%
Libre
5
Desarrollador 5
Evaluación
(67)
Proyectos
97
35%
Arbitraje
11
27% / 45%
Caducado
13
13%
Libre
6
Desarrollador 6
Evaluación
(550)
Proyectos
637
33%
Arbitraje
41
41% / 46%
Caducado
11
2%
Ocupado
7
Desarrollador 7
Evaluación
(6)
Proyectos
10
10%
Arbitraje
9
0% / 89%
Caducado
1
10%
Libre
8
Desarrollador 8
Evaluación
(69)
Proyectos
146
34%
Arbitraje
13
8% / 62%
Caducado
26
18%
Libre
Ha publicado: 6 ejemplos
9
Desarrollador 9
Evaluación
(568)
Proyectos
641
41%
Arbitraje
25
48% / 36%
Caducado
46
7%
Trabaja
Solicitudes similares
I am looking for an experienced quant developer, data engineer, or market data specialist who can help me obtain long historical NASDAQ data for systematic trading research. The goal is to retrieve a clean, continuous dataset covering 2011 to 2026 (minimum) for the NASDAQ index. The dataset will be used for algorithmic backtesting, so data quality and continuity are critical. My trading system is already built and
Descripción del trabajo: Estoy buscando un desarrollador con experiencia en programación de Expert Advisors para MetaTrader 4. Tenía un robot de trading que utilizaba anteriormente, pero actualmente no funciona debido a un problema de licencia. Necesito un desarrollador que pueda crear un robot nuevo lo más parecido posible al que yo tenía, utilizando la misma lógica y parámetros de trading. El trabajo sería: •
Lucky Mpedi 50+ USD
To help with simple requirements and strategy to trade in metotrade 5 and to win or earn much money so that i can live better live. I hope i can get the robot for helping to trade
Job Title: Expert Pine Script → MQL5 Conversion (Exact Strategy Replication Required) Project Overview I am looking for a highly experienced MQL5 developer to convert my TradingView Pine Script strategy into a MetaTrader 5 Expert Advisor (EA) . This must be a 100% exact conversion of the strategy logic. The goal is to have matching trading behaviour and nearly identical backtest results between TradingView and MT5
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

Información sobre el proyecto

Presupuesto
30 - 45 USD