#1
This function has a parameter called orderType, which represents the type of order for which you want to calculate the average price (OP_BUY or OP_SELL). The function uses a for loop to iterate through each order in the account, similar to the previous two functions. If the order type of the current order matches the orderType, the function calculates the total value of the orders and the total quantity of that order type. Finally, the function returns the average value of the specified order type by dividing the total value by the total quantity. If the total quantity is 0, the function returns a value of 0.

// Function to calculate the average price for Buy and Sell orders
// orderType = OP_BUY (Buy order) or OP_SELL (Sell order)
double GetAveragePrice(int orderType)
{
    // Get the total number of orders in the account
    int totalOrders = OrdersTotal();
    // If there are no orders, return a value of 0
    if (totalOrders < 1) 
    {
        Print("No orders in the account.");
        return 0;
    }
    
    // Initialize variables for total value and total quantity
    double totalOrderPrice = 0;
    double totalOrderLots = 0;
    
    // Iterate through each order in the account
    for (int i = 0; i < totalOrders; i++)
    {
        // Select the order at position i
        if (!OrderSelect(i, SELECT_BY_POS, MODE_TRADES)) continue;
        
        // If the order type matches the orderType
        if (OrderType() == orderType)
        {
            // Calculate the total value of the orders and the total quantity of that order type
            totalOrderPrice += OrderOpenPrice() * OrderLots();
            totalOrderLots += OrderLots();
        }
    }
    
    // If the total quantity is 0, return a value of 0
    if (totalOrderLots == 0) 
    {
        Print("No ", (orderType == OP_BUY ? "Buy" : "Sell"), " orders in the account.");
        return 0;
    }
    
    // Return the average value of the specified order type
    double averagePrice = totalOrderPrice / totalOrderLots;
    Print("Average price of ", (orderType == OP_BUY ? "Buy" : "Sell"), " orders is: ", DoubleToStr(averagePrice, Digits));
    return averagePrice;
}

image quote pre code
Xem hướng dẫn đăng nhập để đăng bình luận Tại Đây
Chia sẻ: