CloseBasketProfit
Download scriptThis script is designed to manage a group of open trades simultaneously by evaluating their collective financial performance. Instead of looking at each trade in isolation, the tool views your active positions as a single "basket," allowing you to manage risk and lock in gains based on a specific monetary goal.
How the Logic Works
1. Setting the Profit Goal The primary driver of this script is a user-defined profit target (in dollars). The logic first scans all currently open trades in your account to calculate the combined sum of their profits and losses.
2. Evaluating the Basket The script performs a continuous check: "Is the total profit of all my open trades greater than or equal to my specified goal?"
- If the total profit is below the target, the script does nothing and leaves your trades running.
- If the total profit meets or exceeds the target, the script automatically initiates a two-stage liquidation process.
3. The Two-Stage Liquidation Process To ensure the most efficient exit from the market, the script follows a specific sequence once the profit goal is met:
-
Phase One: Clearing the Losses The script first identifies every individual trade within your basket that is currently in a negative (losing) position. It closes these losing trades first. This is intended to "clean up" the portfolio, ensuring that the realized profit from your winning trades isn't offset by continuing losses on underperforming positions.
-
Phase Two: Closing the Remainder Once all losing trades have been successfully closed, the script moves to its final action: closing every remaining trade in the basket (the profitable ones). This ensures that the entire basket is liquidated at once, securing the total profit you originally targeted.
Error Handling and Safety
During the execution of these closures, the script includes a built-in monitoring system. If the platform encounters any difficulty closing a specific position (such as a connection issue or a price gap), the script will trigger an alert notification to inform you of the specific error. It then pauses briefly before attempting to continue, providing a buffer to ensure the process doesn't crash due to momentary market instability.
//+------------------------------------------------------------------+
//| CloseBasketProfit.mq4 |
//| Copyright © 2007, MetaQuotes Software Corp. |
//| http://www.metaquotes.net |
//+------------------------------------------------------------------+
#property link "http://www.metaquotes.net"
#property copyright "Copyright © 2006, Robert Hill."
#property show_inputs
//---- Include
#include <stderror.mqh>
#include <stdlib.mqh>
//----
extern int ProfitTarget = 10; // Profit target in dollars
//----
double TotalProfit = 0.0;
int total, i;
bool result = false;
//+------------------------------------------------------------------+
//| script program start function |
//+------------------------------------------------------------------+
int start()
{
//---- Calculate total profit on all trades
total = OrdersTotal();
for(i=total-1;i>=0;i--)
{
OrderSelect(i, SELECT_BY_POS);
TotalProfit += OrderProfit();
}
if (TotalProfit >= ProfitTarget)
{
//---- First close losing trades
//total = OrdersTotal();
for(i=total-1;i>=0;i--)
{
OrderSelect(i, SELECT_BY_POS);
result = false;
switch(OrderType())
{
//---- Close opened long positions
case OP_BUY :
if ( OrderProfit() < 0)
result = OrderClose( OrderTicket(), OrderLots(), MarketInfo(OrderSymbol(), MODE_BID), 5, Red );
break;
//---- Close opened short positions
case OP_SELL :
if ( OrderProfit() < 0)
result = OrderClose( OrderTicket(), OrderLots(), MarketInfo(OrderSymbol(), MODE_ASK), 5, Red );
}
if(result == false)
{
Alert("Order " , OrderTicket() , " failed to close. Error:" , GetLastError() );
Sleep(3000);
}
}
//---- Now close remaining trades
//total = OrdersTotal();
for(i=total-1;i>=0;i--)
{
OrderSelect(i, SELECT_BY_POS);
result = false;
switch(OrderType())
{
//---- Close opened long positions
case OP_BUY :
result = OrderClose( OrderTicket(), OrderLots(), MarketInfo(OrderSymbol(), MODE_BID), 5, Red );
break;
//---- Close opened short positions
case OP_SELL :
result = OrderClose( OrderTicket(), OrderLots(), MarketInfo(OrderSymbol(), MODE_ASK), 5, Red );
}
if(result == false)
{
Alert("Order " , OrderTicket() , " failed to close. Error:" , GetLastError() );
Sleep(3000);
}
}
}
//----
return(0);
}
//+------------------------------------------------------------------+
Comments