//+------------------------------------------------------------------+ //| CloseOrders.mq4 | //| Copyright 2023, MetaQuotes Software Corp. | //|
https://www.mql5.com | //+------------------------------------------------------------------+ #property copyright "Copyright 2023, MetaQuotes Software Corp." #property link "https://www.mql5.com" #property version "1.00" #property strict //+------------------------------------------------------------------+ //| Expert initialization function | //+------------------------------------------------------------------+ int OnInit() { //--- create timer EventSetTimer(1); // 1 second return(INIT_SUCCEEDED); } //+------------------------------------------------------------------+ //| Expert deinitialization function | //+------------------------------------------------------------------+ void OnDeinit(const int reason) { //--- destroy timer EventKillTimer(); } //+------------------------------------------------------------------+ //| Expert start function | //+------------------------------------------------------------------+ void OnTimer() { double totalProfit = CalculateTotalProfit(); if(totalProfit >= 50.0) // If total profit reaches 50 USD { CloseAllOrders(); } } //+------------------------------------------------------------------+ //| CalculateTotalProfit function | //+------------------------------------------------------------------+ double CalculateTotalProfit() { double totalProfit = 0.0; for(int i = OrdersTotal() - 1; i >= 0; i--) { if(OrderSelect(i, SELECT_BY_POS, MODE_TRADES)) { if(OrderSymbol() == Symbol() && OrderMagicNumber() == MagicNumber) { totalProfit += OrderProfit(); } } } return totalProfit; } //+------------------------------------------------------------------+ //| CloseAllOrders function | //+------------------------------------------------------------------+ void CloseAllOrders() { for(int i = OrdersTotal() - 1; i >= 0; i--) { if(OrderSelect(i, SELECT_BY_POS, MODE_TRADES)) { if(OrderSymbol() == Symbol() && OrderMagicNumber() == MagicNumber) { if(OrderType() == OP_BUY) { OrderClose(OrderTicket(), OrderLots(), Bid, 3, clrNONE); } else if(OrderType() == OP_SELL) { OrderClose(OrderTicket(), OrderLots(), Ask, 3, clrNONE); } } } } } //+------------------------------------------------------------------+