Problem Description
Solution
Here is the MQL4 code for an Expert Advisor (EA) that monitors your account and automatically closes all open trades when the total floating profit reaches $100.
Why an Expert Advisor and not a Script?
In MetaTrader 4, a Script runs once and stops. It cannot "wait" for the profit to hit $100. An Expert Advisor runs continuously on every price tick, allowing it to monitor your profit in real-time and act the moment your target is reached.
MQL4 Code
Save this code in your MQL4/Experts folder as CloseOnProfit.mq4.
//+------------------------------------------------------------------+
//| CloseOnProfit.mq4 |
//| Copyright 2023, Quantitative |
//| https://www.mql5.com |
//+------------------------------------------------------------------+
#property copyright "Copyright 2023, Quantitative"
#property link "https://www.mql5.com"
#property version "1.00"
#property strict
//--- Input Parameters
input double TargetProfitUSD = 100.0; // Target Profit in Account Currency (e.g., $100)
input int Slippage = 3; // Maximum allowed slippage in pips
input bool CloseAllSymbols = true; // True = Close all symbols, False = Close only current chart symbol
//+------------------------------------------------------------------+
//| Expert initialization function |
//+------------------------------------------------------------------+
int OnInit()
{
// Basic check to ensure inputs are logical
if(TargetProfitUSD <= 0)
{
Print("Error: Target Profit must be greater than 0.");
return(INIT_FAILED);
}
Print("Monitoring started. Will close all trades when profit reaches: ", TargetProfitUSD);
return(INIT_SUCCEEDED);
}
//+------------------------------------------------------------------+
//| Expert tick function |
//+------------------------------------------------------------------+
void OnTick()
{
// 1. Check if the total account profit has reached the target
if(AccountProfit() >= TargetProfitUSD)
{
Print("Target Profit of ", TargetProfitUSD, " reached. Current Profit: ", AccountProfit(), ". Closing trades...");
CloseAllTrades();
}
}
//+------------------------------------------------------------------+
//| Function to close all open market orders |
//+------------------------------------------------------------------+
void CloseAllTrades()
{
int total = OrdersTotal();
// Iterate backwards through orders to avoid index shifting issues when closing
for(int i = total - 1; i >= 0; i--)
{
if(OrderSelect(i, SELECT_BY_POS, MODE_TRADES))
{
// Check if we should close all symbols or only the current one
if(CloseAllSymbols == false && OrderSymbol() != Symbol()) continue;
// Only close Market Orders (OP_BUY or OP_SELL), ignore Pending Orders
int type = OrderType();
bool result = false;
// Refresh rates to get the latest Bid/Ask prices
RefreshRates();
if(type == OP_BUY)
{
// Close Buy at Bid price
double closePrice = MarketInfo(OrderSymbol(), MODE_BID);
result = OrderClose(OrderTicket(), OrderLots(), closePrice, Slippage, clrRed);
}
else if(type == OP_SELL)
{
// Close Sell at Ask price
double closePrice = MarketInfo(OrderSymbol(), MODE_ASK);
result = OrderClose(OrderTicket(), OrderLots(), closePrice, Slippage, clrBlue);
}
// Error handling
if(!result && (type == OP_BUY || type == OP_SELL))
{
Print("Failed to close order #", OrderTicket(), " Error: ", GetLastError());
}
}
}
}
How to Install and Use
- Open MetaEditor: In MT4, press
F4. - Create New File: Click New -> Expert Advisor (template) -> Name it
CloseOnProfit. - Paste Code: Delete everything in the new file and paste the code provided above.
- Compile: Press
F7or click Compile. Ensure there are no errors in the "Errors" tab at the bottom. - Activate in MT4:
- Go back to the main MT4 window.
- Find
CloseOnProfitin the Navigator panel under Expert Advisors. - Drag it onto any chart.
- In the Inputs tab, set
TargetProfitUSDto100.0. - Ensure Allow Live Trading is checked in the Common tab.
- Make sure the AutoTrading button on the top toolbar is Green (On).
Key Features of This Code
- Global Monitoring: It uses
AccountProfit(), which calculates the floating profit/loss of all open trades on the account combined (including swaps and commissions). - Symbol Filtering: Includes an input
CloseAllSymbols. If set totrue, it closes trades on EURUSD, GBPUSD, Gold, etc. Iffalse, it only closes trades for the symbol of the chart the EA is attached to. - Reverse Iteration: The loop
for(int i = total - 1; i >= 0; i--)counts backwards. This is crucial in MQL4; if you count forward while deleting orders, the index shifts and you will skip orders. - MarketInfo: Uses
MarketInfo(OrderSymbol(), ...)to get the correct Bid/Ask price for the specific symbol of the order being closed, ensuring cross-currency trades close correctly.
Q&A: Quantitative Strategy Implementation
Q: Does AccountProfit() include Swaps and Commissions?
A: Yes. AccountProfit() returns the net floating equity change. This ensures that if you set a target of $100, you actually walk away with $100 net (excluding the spread cost realized at closing), rather than having commissions eat into that profit.
Q: Will this close Pending Orders (Limit/Stop orders)?
A: No. The code specifically checks if(type == OP_BUY) or if(type == OP_SELL). It ignores OP_BUYLIMIT, OP_SELLSTOP, etc. If you wish to delete pending orders as well, the code would need to use OrderDelete() for those specific types.
Q: What happens if the market moves fast (Slippage)?
A: The Slippage input (default 3 pips) allows the order to close even if the price moves slightly between the request and execution. If the price moves more than 3 pips, the server may return a "Requote" error. In a highly volatile environment, you may need to increase the Slippage input value.
Q: Can I run this on multiple charts simultaneously?
A: You should only run this on one chart if CloseAllSymbols is set to true. If you attach it to multiple charts with the same logic, they might try to close the same orders simultaneously, resulting in "Order Locked" or "Invalid Ticket" errors.