Quick CloseAll
Download scriptThis script is a specialized utility designed for MetaTrader 4 to provide an immediate and comprehensive exit strategy for your trading positions. Its primary purpose is to clear all active trades and pending orders that share a specific identification number, allowing for a "panic button" or a rapid cleanup of the trading dashboard.
How the Logic Works
1. Identification and Filtering The script identifies which trades it should handle by looking at two specific criteria:
- Magic Number: This is a unique identifier assigned to automated trades. The script only interacts with orders that match the specific ID pre-set in the code (defaulting to 915). This ensures that the script doesn't accidentally close manual trades or trades from other systems you might be running simultaneously.
- Current Symbol: It checks the current currency pair or asset you are viewing to ensure it only processes relevant data.
2. Connection Verification Before attempting any actions, the script performs a "handshake" check with your broker's server. If there is no active internet connection or the trading platform is disconnected, it will issue an alert notification rather than trying (and failing) to execute commands.
3. Comprehensive Order Processing The logic distinguishes between different types of market activities to ensure every type of "order" is addressed correctly:
- Active Positions (Buy/Sell): If the script finds an open Buy or Sell position, it executes a closing command at the current market price.
- Pending Orders (Limits and Stops): If the script finds orders that have been set but not yet triggered (such as Buy Limits or Sell Stops), it performs a deletion command to remove them from the active watch list entirely.
4. Execution Flow and Stability To ensure the script doesn't crash or miss any trades during high-speed execution, it employs several safety measures:
- Reverse Iteration: It counts and processes orders starting from the most recent back to the first. This is a standard safety protocol in trading software to prevent skipping an order when one is removed from the list mid-process.
- Queue Management: The script includes a "Wait" mechanism. If the trading server is busy processing one request at a time, the script will pause for a fraction of a second before sending the next command, ensuring that every single order gets processed without causing an error.
- Continuous Loop: The script continues to scan and close orders until it confirms that zero matching trades remain on your account.
//+-------------------------------------------------------------------------+
//| IBFX - Quick CloseAll.mq4 |
//+-------------------------------------------------------------------------+
#property copyright "Copyright © 2008, IBFX"
#property link "www.ibfx.com"
//----
int start()
{
/*+-------------------------------------------------------------------------+
Because these scripts are meant to execute fast there are no user
external inputs. Make sure to modify the settings below, then compile
the script before assigning a hot key to it and using it.
The magicNumber HAS TO TO BE THE SAME ON ALL SCRIPTS if you change it
here make sure to change it on all scripts!!!
Do not forget to click on COMPILE once your changes have been made!!!
+-------------------------------------------------------------------------+*/
int MagicNumber = 915;
int Slippage = 3;
string Commentary = " Quick CloseAll ";
string FontName = "Arial";
int FontSize = 12;
//+-------------------------------------------------------------------------+
//| DO NOT MODIFY ANYTHING BELOW THIS LINE!!! |
//+-------------------------------------------------------------------------+
//---- A few checks before we get started
if( !IsConnected() ) { Alert( Commentary + " - No Connection!!" ); return(0); }
//+------------------------------------------------------------------+
// CloseAllOrders |
//+------------------------------------------------------------------+
int type = 0; int ErrorCode = 0; bool result = false;
Comment( " QuickCloseAll | Closing ALL Orders, please wait ..." );
if( CountAll( MagicNumber ) > 0 )
{
while( CountAll( MagicNumber ) > 0 )
{
for(int i = OrdersTotal()-1; i>=0; i--)
{
OrderSelect(i,SELECT_BY_POS,MODE_TRADES);
if( MagicNumber == OrderMagicNumber() && OrderSymbol() == Symbol() )
{
type = OrderType();
result = false;
ErrorCode = 0;
//-- Switch
switch(type)
{
case OP_BUY : Wait(); result = OrderClose( OrderTicket(), OrderLots(), MarketInfo(OrderSymbol(), MODE_BID), 0, CLR_NONE ); if( result < 0 ) { ErrorCode = GetLastError(); } break;
case OP_SELL : Wait(); result = OrderClose( OrderTicket(), OrderLots(), MarketInfo(OrderSymbol(), MODE_ASK), 0, CLR_NONE ); if( result < 0 ) { ErrorCode = GetLastError(); } break;
case OP_BUYLIMIT :
case OP_BUYSTOP :
case OP_SELLLIMIT :
case OP_SELLSTOP : Wait(); result = OrderDelete( OrderTicket() ); break;
default : break;
} // Switch
}
}// For
}// While
}
Comment("");
//----
return(0);
}
//+------------------------------------------------------------------+
//+------------------------------------------------------------------+
//+ Wait +
//+------------------------------------------------------------------+
void Wait() { while( IsTradeContextBusy() )
{ Sleep(50); } }
//+------------------------------------------------------------------+
//+------------------------------------------------------------------+
// CountAll |
//+------------------------------------------------------------------+
int CountAll( int MagicNumber )
{
int Count=0;
for(int i = OrdersTotal()-1; i>=0; i--)
{
OrderSelect(i,SELECT_BY_POS,MODE_TRADES);
if( OrderMagicNumber() == MagicNumber )
{ Count++; }
}
return(Count);
}
//+------------------------------------------------------------------+
Comments