Aminbhr 发表于 2024-10-10 20:58:15

CloseTradesMaxOpenDuration() Closes trades active longer than a duration.

function name
//+------------------------------------------------------------------+
<font _mstmutation="1" _msttexthash="566925125" _msthash="403">//| Function to close open trades based on duration                   |
//| input: maxOpenHours - maximum duration for open trades in hours|
//+------------------------------------------------------------------+
void CloseTradesIfOpenLongerThan(int maxOpenHours) {
    double maxOpenTime = maxOpenHours * 3600; // Convert hours to seconds
    int totalOrders = OrdersTotal(); // Get the total number of open trades

    for (int i = totalOrders - 1; i >= 0; i--) {
      if (OrderSelect(i, SELECT_BY_POS)) { // Select the trade by position
            // Check if the trade is open
            if (OrderType() == OP_BUY || OrderType() == OP_SELL) {
                // Calculate the duration the trade has been open
                datetime openTime = OrderOpenTime(); // Get the open time of the trade
                double elapsedTime = TimeCurrent() - openTime; // Calculate elapsed time since the trade opened

                // If the elapsed time exceeds the maximum allowed time, close the trade
                if (elapsedTime > maxOpenTime) {
                  if (OrderType() == OP_BUY) {
                        OrderClose(OrderTicket(), OrderLots(), Bid, 3, clrRed); // Close buy trade
                  } else if (OrderType() == OP_SELL) {
                        OrderClose(OrderTicket(), OrderLots(), Ask, 3, clrRed); // Close sell trade</font>
                  }
                }
            }
      }
    }
}

//+------------------------------------------------------------------+

页: [1]
查看完整版本: CloseTradesMaxOpenDuration() Closes trades active longer than a duration.