close_by_type

Download script
Author: Copyright � 2004, MetaQuotes Software Corp.
close_by_type

This script is designed to automate the process of closing specific types of active trades on your MetaTrader platform. It acts as a targeted "exit command" that identifies and shuts down positions based on your pre-defined preferences.

Core Functionality

The primary purpose of this tool is to simplify trade management by automatically closing either all "Buy" orders or all "Sell" orders across a specific currency pair. Instead of manually clicking through each open position, the script scans your active trades and executes the closure for you.

How it Works

When you run the script, it follows a structured logical sequence to ensure accurate execution:

  • User Configuration: You can choose which type of trade the script should target (Buying or Selling) before running it. This prevents the script from accidentally closing the wrong side of your market exposure.
  • Active Scan: The script performs a comprehensive sweep of all currently open positions in your trading account.
  • Precision Filtering: It applies two specific filters to ensure it only acts on the intended trades:
    1. Trade Type Match: It checks if the trade matches the category you selected (e.g., only closing "Buy" orders).
    2. Symbol Match: It ensures that it only closes trades for the specific currency pair or asset you are currently viewing, preventing it from affecting trades on other charts.
  • Execution Loop: Once a matching trade is identified, the script attempts to close it immediately. If the market price shifts slightly during the millisecond the command is sent (a common occurrence in fast markets), the script is designed to "refresh" and retry the closure until it is successfully confirmed by the server.
  • Error Reporting: If a trade cannot be closed for any reason (such as a connection issue or an invalid price), the script will record the specific error code into the platform's log, allowing you to troubleshoot issues easily.

Summary of Use

This tool is ideal for traders who need to quickly flatten out a specific side of their portfolio on a particular asset without the risk of manual clicking errors. It systematically identifies, validates, and closes your chosen trades based on your settings.

Orders Execution
Checks for the total of open ordersIt Closes Orders by itself
11 Views
0 Downloads
0 Favorites
close_by_type
//+------------------------------------------------------------------+
//|                                                        close.mq4 |
//|                      Copyright © 2004, MetaQuotes Software Corp. |
//|                                       http://www.metaquotes.net/ |
//+------------------------------------------------------------------+
#property copyright "Copyright © 2004, MetaQuotes Software Corp."
#property link      "http://www.metaquotes.net/"
#property show_inputs

extern string Trade_Type = "Close Trade Type (0=Buying 1=Selling)";
extern int trade_type_selection = OP_BUY; //default is to close buy trades


//+------------------------------------------------------------------+
//| script "close first market order if it is first in the list"     |
//+------------------------------------------------------------------+
int start()
  {
   bool   result;
   double price;
   int    cmd,error,total;
//----
  total = OrdersTotal();
  for(int i=total-1;i>=0;i--)
  {
   if(OrderSelect(i,SELECT_BY_POS,MODE_TRADES)){
      cmd=OrderType();
      //---- first order is buy or sell
      if((cmd==trade_type_selection)&& (OrderSymbol()==Symbol())){
         while(true){
            if(cmd==OP_BUY) price=Bid;
            else            price=Ask;
            result=OrderClose(OrderTicket(),OrderLots(),price,3,CLR_NONE);
            if(result!=TRUE) { error=GetLastError(); Print("LastError = ",error); }
            else error=0;
            if(error==135) RefreshRates();
            else break;
         }
      }
   }
   else Print( "Error when order select ", GetLastError());
  }
//----
   return(0);
  }
//+------------------------------------------------------------------+

Comments