CloseAllPairs
Download scriptThis script is a specialized utility designed for MetaTrader 5 users who need to quickly manage their active trading portfolio. Its primary purpose is to provide an immediate "emergency exit" or a "clean slate" functionality by identifying and closing all open positions simultaneously.
How the Logic Works
The script operates through a straightforward, sequential process to ensure that every active trade is accounted for:
- Portfolio Scanning: Once activated, the script immediately scans your entire trading account to determine how many active positions are currently open. If it finds that there are no open positions, it simply stops and does nothing.
- Reverse Iteration Logic: To ensure the script doesn't "skip" any trades while closing them, it processes your list of open positions starting from the most recent one and works backward to the first. This is a standard safety procedure in trading software to maintain the integrity of the data sequence as items are being removed from the list.
- Trade Verification: For every position identified during the scan, the script verifies its status. It specifically looks for active "Buy" or "Sell" orders.
- Execution of Closure: Once a position is confirmed, the script sends an automated command to the server to close that specific trade immediately. This continues until every single open position in your account has been processed.
Summary of Use Case
Instead of manually clicking "Close" on dozens of different currency pairs or assets one by one—which can be time-consuming and prone to human error during volatile market conditions—this script automates that entire manual task into a single action. It is essentially an automated "Off Switch" for your active trading activity.
//+------------------------------------------------------------------+
//| CloseAllPairs.mq5 |
//| Copyright 2018,fxMeter |
//| https://www.mql5.com/en/users/fxmeter |
//+------------------------------------------------------------------+
#property copyright "Copyright 2018,fxMeter"
#property link "https://www.mql5.com/en/users/fxmeter"
#property version "1.00"
#include <Trade\trade.mqh>
#include <Trade\PositionInfo.mqh>
CTrade trade;
//+------------------------------------------------------------------+
//| Script program start function |
//+------------------------------------------------------------------+
void OnStart()
{
//---
ulong ticket=0;
int total= PositionsTotal();
if(total<=0)return;
for(int i=total-1;i>=0;i--)
{
if((ticket=PositionGetTicket(i))>0)
{
if((PositionGetInteger(POSITION_TYPE)==POSITION_TYPE_BUY) || (PositionGetInteger(POSITION_TYPE)==POSITION_TYPE_SELL))
{
trade.PositionClose(ticket);
}
}
}
}
//+------------------------------------------------------------------+
Comments