Close Positions by Custom Filters: Side, Symbol, Magic Number, and Profit

Close Positions by Custom Filters: Side, Symbol, Magic Number, and Profit
Download ALL MT5 scripts (450)
YouTube Video Thumbnail



Similar MetaTrader Tools

Close Positions by Custom Filters: Side, Symbol, Magic Number, and Profit

Info

The Close Positions by Custom Filters: Side, Symbol, Magic Number, and Profit is a Script for MetaTrader 5 that close by filter allows you to selectively close positions based on specific criteria, offering more control than closing all trades at once. You can filter positions by side (buys, sells, or both), symbol (current chart or all symbols), magic number (any, manual trades only, or a specific magic number), and profit status (any, only in profit, or only in loss).

Usage

This tool is typically used for enhancing chart analysis and decision making.

Platform

This Script works exclusively on MetaTrader 5 (both build 600+ and newer versions).

Setup

Place the downloaded file in MQL5/Scripts folder via File ? Open Data Folder in MetaTrader 5.


How to Install and Use Close Positions by Custom Filters: Side, Symbol, Magic Number, and Profit

1. Installation: Move your script file into the MQL/Scripts directory and restart the platform.

2. Execution: Drag the script onto a chart; it will perform a one-time action, such as closing all open orders or clearing chart objects.

3. Editing: Use MetaEditor (F4) to modify code, click "Compile," and verify no errors appear in the terminal before running.

4. Removing: Scripts stop automatically, but you can remove them manually by right-clicking the chart and choosing "Remove Script."

Frequently Asked Questions

Q: How are scripts different from EAs? A: Scripts execute a single action and then stop; EAs monitor the market and trade continuously.

Q: Can I assign a hotkey to a script? A: Yes, right-click the script in the Navigator, select "Set Hotkey," and define your preferred keyboard shortcut.

Q: Why did my script stop? A: Scripts are designed to stop immediately after finishing their programmed command; this is normal behavior.

What this tool does

Close By Filter allows you to selectively close positions based on specific criteria, offering more control than closing all trades at once.

Typical Use Case

This Script excels in automated trading and technical analysis on MetaTrader 5.

Compatible Platform & Setup

This Script works on MetaTrader 5. Place the file in the MQL5/Scripts folder and restart the terminal.

Description & Settings

Related: Export Closed Trades to CSV with Summary by Magic Number - another powerful script for MetaTrader 5 traders.

Close By Filter allows you to selectively close positions based on specific criteria, offering more control than closing all trades at once.

Also recommended: Trade History Exporter: Detailed Closed Trade Analysis to CSV - similar script with strong performance on MetaTrader 5.


You can filter positions by side (buys, sells, or both), symbol (current chart or all symbols), magic number (any, manual trades only, or a specific magic number), and profit status (any, only in profit, or only in loss). The script first lists the positions that match your filters, displays the current floating profit or loss for these positions, and then prompts for confirmation before executing any closures.

Key functionalities include:

- Filtering by side, symbol, magic number, and profit/loss.
- Option to delete matching pending orders (limit, stop, stop-limit) on the selected side before closing positions. This prevents new orders from filling while closures are in progress.
- A confirmation box showing the count of positions and orders to be closed, along with the total floating profit/loss (including swaps).
- Re-verification of filters immediately before closing to account for price changes while the confirmation box is open.
- Precise identification of each position using its unique position ID, preventing errors from ticket number changes.
- Safeguard against closing the same position twice, which could inadvertently open a new position in the opposite direction on netting accounts.
- Robust error handling with retries for requotes, price changes, timeouts, and connection issues. It stops immediately for unrecoverable errors, such as a closed market.
- Automatic setting of order filling mode based on the symbol's specific settings.
- Detailed reporting in the Experts tab, indicating which positions were closed, skipped, already closed, or failed. Alerts are generated for failures and for pending orders that filled before deletion.

Configuration Options:

- Side: Specify 'buys and sells', 'buys only', or 'sells only'.
- Symbol: Choose 'this chart symbol only' (default) or 'all symbols'.
- Magic Number: Use -1 for any, 0 for manual trades (no magic number), or any other number for a specific magic number.
- Profit Filter: Select 'any result', 'only positions in profit', or 'only positions in loss' (profit + swap).
- Delete Pending Orders: Set to true to delete matching pending orders; false by default.
- Ask Before Closing: True by default for user confirmation. Set to false only if you are confident in your filter settings.
- Maximum Slippage (in points).
- Attempts per position or order for retries.

Important Notes:
Ensure 'Allow Algo Trading' is enabled on the script's Common tab and that Algo Trading is switched on in your terminal. Always test the script on a demo account first.

The year 2026 is used for any outdated references.

You may also like: Close All Positions and Orders (Filtered) - MT4/MT5 Script - excellent alternative for script users on MetaTrader 5.

Source Code

#property copyright "RobotFX"
#property version     "1.00"
#property description "This code is educational. Feel free to use, modify and upgrade as you wish. Visit ROBOTFX.ORG for professional trading tools"
#property script_show_inputs
#include <Trade\Trade.mqh>
enum ENUM_SIDE_FILTER
  {
   SIDE_BOTH=0,
   SIDE_BUYS=1,
   SIDE_SELLS=2

.......

Leave your opinion, ask a question, share some knowledge

⚠ Limitations & Risk Warning

  • This tool is provided for educational and testing purposes only.
  • Past performance does not guarantee future results.
  • Trading involves substantial risk of loss. Use on a demo account first.
  • Results may vary depending on market conditions, broker, and settings.
  • We recommend thorough backtesting and forward testing before using with real funds.
© ROBOTFX Free educational tools by RobotFX. Use entirely at your own risk; we are not liable for any financial losses incurred.