Managing trading risk often requires closing all positions at a specific hour (e.g., before news events) or when a daily profit goal is hit. This MT4 auto close script automates both scenarios. It’s lightweight, easy to modify, and ideal for traders who need a reliable automatic close tool without running a full EA.
Core Features
Complete MQL4 Source Code
```cpp
//+------------------------------------------------------------------+
//| Auto_Close_Profit_V1.mq4 |
//| Generated by AutoCompile AI |
//| |
//+------------------------------------------------------------------+
#property copyright "AutoCompile AI"
#property link ""
#property version "1.00"
#property script_show_inputs
//--- Mode selection
enum ENUM_CLOSE_MODE
{
CLOSE_BY_TIME, // Close at specific time
CLOSE_BY_PROFIT // Close at profit target
};
//--- Input parameters
input ENUM_CLOSE_MODE CloseMode = CLOSE_BY_TIME; // Closing mode
input int CloseHour = 22; // Hour to close (0-23, broker time)
input int CloseMinute = 0; // Minute to close (0-59)
input double ProfitTarget = 50.0; // Profit target in deposit currency
input bool ShowConfirm = true; // Show confirmation dialog before closing
//+------------------------------------------------------------------+
//| Script program start function |
//+------------------------------------------------------------------+
void OnStart()
{
//--- Wait for next tick to avoid race conditions
Sleep(100);
bool shouldClose = false;
string reason = "";
//--- Determine if closing condition is met
if(CloseMode == CLOSE_BY_TIME)
{
datetime now = TimeCurrent();
MqlDateTime dt;
TimeToStruct(now, dt);
if(dt.hour >= CloseHour && dt.min >= CloseMinute)
{
shouldClose = true;
reason = StringFormat("Time threshold reached: %02d:%02d", CloseHour, CloseMinute);
}
}
else // CLOSE_BY_PROFIT
{
double totalProfit = CalculateTotalProfit();
if(totalProfit >= ProfitTarget)
{
shouldClose = true;
reason = StringFormat("Profit target reached: %.2f %s", totalProfit, AccountInfoString(ACCOUNT_CURRENCY));
}
}
//--- Execute close if condition met
if(shouldClose)
{
if(ShowConfirm)
{
int answer = MessageBox(StringFormat("Close all positions?\nReason: %s", reason),
"Auto Close Script", MB_OKCANCEL | MB_ICONQUESTION);
if(answer != IDOK)
{
Print("Manual cancel by user.");
return;
}
}
CloseAllOrders();
Print("Auto close executed: ", reason);
}
else
{
string modeDesc = (CloseMode == CLOSE_BY_TIME) ? "Time mode" : "Profit mode";
Print("Condition not met (", modeDesc, "). Script will idle and exit.");
}
}
//+------------------------------------------------------------------+
//| Calculate total profit of all market orders (including swaps) |
//+------------------------------------------------------------------+
double CalculateTotalProfit()
{
double total = 0.0;
for(int i=OrdersTotal()-1; i>=0; i--)
{
if(OrderSelect(i, SELECT_BY_POS, MODE_TRADES))
{
if(OrderType() == OP_BUY || OrderType() == OP_SELL)
{
total += OrderProfit() + OrderSwap() + OrderCommission();
}
}
}
return total;
}
//+------------------------------------------------------------------+
//| Close all market orders |
//+------------------------------------------------------------------+
void CloseAllOrders()
{
int closed = 0;
int errors = 0;
for(int i=OrdersTotal()-1; i>=0; i--)
{
if(OrderSelect(i, SELECT_BY_POS, MODE_TRADES))
{
int type = OrderType();
if(type == OP_BUY || type == OP_SELL)
{
bool result = false;
if(type == OP_BUY)
result = OrderClose(OrderTicket(), OrderLots(), Bid, 3, clrNONE);
else // OP_SELL
result = OrderClose(OrderTicket(), OrderLots(), Ask, 3, clrNONE);
if(result)
{
closed++;
Print("Closed order #", OrderTicket(), " at ", (type==OP_BUY?DoubleToString(Bid,Digits()):DoubleToString(Ask,Digits())));
}
else
{
errors++;
Print("Failed to close order #", OrderTicket(), ", Error: ", GetLastError());
}
Sleep(50); // Small delay to avoid broker limits
}
}
}
Print("Auto close finished. Closed: ", closed, ", Errors: ", errors);
if(closed > 0 && errors == 0)
Alert("Successfully closed ", closed, " orders.");
}
//+------------------------------------------------------------------+
```
How to Compile & Use
1. Save the code as `Auto_Close_Profit_V1.mq4` in your MT4 `Scripts` folder.
2. Compile with MetaEditor (F7). No errors expected.
3. Drag the script onto a chart. Input parameters will appear.
4. Choose mode: CLOSE_BY_TIME (e.g., 22:00 broker time) or CLOSE_BY_PROFIT (e.g., $50).
5. The script checks the condition once then exits. For continuous monitoring, use a scheduled task or run it repeatedly (e.g., every minute via a helper EA).
Parameter Explanation
Modification Tips (EA Programming Basics)
To adapt this utility script, you can:
This free EA download serves as a solid foundation for learning MQL4 compilation and modification. For advanced multi-condition risk management (trailing stop, break-even, partial close), consider our premium RiskGuard EA Suite. Subscribe to receive more EA source code tutorials weekly.
Reference: AutoCompile AI - Original MQL4 utility script for risk management, 2025.