How to get the ticket ID for the most negative position?

 

Hello there! 

Is there a way to get the ticket ID of the most negative position?

Theoretically this would be the first opened position in grid system. I thought storing all position tickets in an array would do but this seems like a mountain of a task. So i thought looping through all open positions would be the path of least resistance but it seems the shortcut is actually the longer way.

Any advice is much appreciated thanks!  

 
// Define the function to get the ticket ID of the most negative position
ulong GetMostNegativePositionTicket()
{
    ulong mostNegativeTicket = 0;
    double mostNegativeProfit = 0;

    // Loop through all open positions
    for (int i = 0; i < PositionsTotal(); i++)
    {
        // Get the position by index
        if (PositionSelectByIndex(i))
        {
            // Check if the position's profit is less than the current most negative profit
            if (PositionGetDouble(POSITION_PROFIT) < mostNegativeProfit)
            {
                mostNegativeProfit = PositionGetDouble(POSITION_PROFIT);
                mostNegativeTicket = PositionGetInteger(POSITION_TICKET);
            }
        }
    }

    return mostNegativeTicket;
}

// Example usage
void OnStart()
{
    ulong mostNegativeTicket = GetMostNegativePositionTicket();
    Print("Most negative position ticket ID: ", mostNegativeTicket);
}
 
Oleksandr Medviediev #:

Thank you!!!