Close all pending orders
Download scriptThis script is designed to act as a comprehensive "cleanup" tool for your trading account. Its primary function is to identify all active orders and instructions currently sitting in your trading terminal and systematically remove them from the market.
Here is a breakdown of how the logic works:
Core Functionality
The script performs a full sweep of your open positions and pending requests. It examines every single item in your order list to determine what type of trade it is and then applies the appropriate action based on that category.
How it Handles Different Order Types
The logic categorizes your trades into two main groups:
-
Active Positions (Buy and Sell): The script identifies any "Live" trades where you are currently in a position (either "Long/Buy" or "Short/Sell"). When it detects these, it flags them for closure. This is useful for quickly exiting all current market exposure at once.
-
Pending Orders: The script also scans for "Limit" and "Stop" orders—these are instructions to buy or sell at a specific price in the future. The logic identifies all four types of pending orders (Buy Limit, Buy Stop, Sell Limit, and Sell Stop) and initiates a command to delete them from the system entirely.
Error Handling & Notifications
To ensure you are kept informed of the script's progress, it includes a built-in safety check:
- Success Monitoring: The script attempts to process each order one by one.
- Alert System: If the script encounters any issue where an order fails to close or delete (for example, due to a connection glitch or a market restriction), it will trigger an immediate on-screen alert notification.
- Pause Mechanism: If a failure occurs, the script is programmed to wait briefly before moving on, allowing the system time to stabilize before attempting to process the next item in the list.
Summary for the User
Essentially, this tool serves as an automated "Emergency Exit" or "Account Reset" button. Rather than you having to manually click through every open trade and pending request to close them individually, this script automates that entire process in a single execution.
int start()
{
int total = OrdersTotal();
for(int i=total-1;i>=0;i--)
{
OrderSelect(i, SELECT_BY_POS);
int type = OrderType();
bool result = false;
switch(type)
{
//Close opened long positions
case OP_BUY : result = true;
//result = OrderClose( OrderTicket(), OrderLots(), MarketInfo(OrderSymbol(), MODE_BID), 5, Red );
break;
//Close opened short positions
case OP_SELL : result = true;
//result = OrderClose( OrderTicket(), OrderLots(), MarketInfo(OrderSymbol(), MODE_ASK), 5, Red );
break;
//Close pending orders
case OP_BUYLIMIT :
case OP_BUYSTOP :
case OP_SELLLIMIT :
case OP_SELLSTOP : result = OrderDelete( OrderTicket() );
}
if(result == false)
{
Alert("Order " , OrderTicket() , " failed to close. Error:" , GetLastError() );
Sleep(3000);
}
}
return(0);
}
Comments