Free MT4 Tool: One-Click Close All Positions EA (Created with ChatGPT GPTs)

ChatGPT-Generated
スポンサーリンク

Instantly Close All Open Positions with a Single Click!

This free MT4 Expert Advisor (EA) allows traders to close all open positions with just one click. A button is added directly to the chart, enabling quick and easy trade management.

🚀 Developed with ChatGPT (EA Creator)

🔹 Key Features

✔️ One-Click Execution – Instantly close all open positions with a single button press.
✔️ Customizable Button Position & Size – Adjust placement for optimal usability.
✔️ Efficient & Reliable Execution – Ensures all positions are closed without delay.
✔️ Improved Code with Event Handling – Uses OnChartEvent for responsive interactions.

Tool image

Request Details and Execution Results

I made some minor adjustments, but overall, the tool worked as intended.

First Request

EA Development Request:

  • Place a button for closing all positions.
  • When the button is clicked, close all currently open positions.
ChatGPT Output

Based on the provided specifications, here is the MQL4 code for an EA that places a “Close All” button on the chart and closes all positions when clicked.

//+------------------------------------------------------------------+
//| CloseAllEA |
//| Copyright 2023, MetaQuotes Software Corp. |
//| http://www.metaquotes.net/ |
//+------------------------------------------------------------------+
#property strict

input int ButtonX = 10; // X-coordinate of the button
input int ButtonY = 10; // Y-coordinate of the button
input int ButtonWidth = 100; // Width of the button
input int ButtonHeight = 30; // Height of the button

//+------------------------------------------------------------------+
//| Expert initialization function |
//+------------------------------------------------------------------+
int OnInit()
{
// Create the button
CreateCloseAllButton();
return(INIT_SUCCEEDED);
}

//+------------------------------------------------------------------+
//| Expert deinitialization function |
//+------------------------------------------------------------------+
void OnDeinit(const int reason)
{
// Delete the button
ObjectDelete(0, "CloseAllButton");
}

//+------------------------------------------------------------------+
//| Expert tick function |
//+------------------------------------------------------------------+
void OnTick()
{
// Check if the button was clicked
if (ObjectGetInteger(0, "CloseAllButton", OBJPROP_STATE))
{
// Close all positions when the button is clicked
CloseAllPositions();
// Reset button state
ObjectSetInteger(0, "CloseAllButton", OBJPROP_STATE, false);
}
}

//+------------------------------------------------------------------+
//| Function to create the button |
//+------------------------------------------------------------------+
void CreateCloseAllButton()
{
// Create the button
if (!ObjectCreate(0, "CloseAllButton", OBJ_BUTTON, 0, 0, 0))
Print("Failed to create the button!");

// Set button properties
ObjectSetInteger(0, "CloseAllButton", OBJPROP_CORNER, 0);
ObjectSetInteger(0, "CloseAllButton", OBJPROP_XDISTANCE, ButtonX);
ObjectSetInteger(0, "CloseAllButton", OBJPROP_YDISTANCE, ButtonY);
ObjectSetInteger(0, "CloseAllButton", OBJPROP_WIDTH, ButtonWidth);
ObjectSetInteger(0, "CloseAllButton", OBJPROP_HEIGHT, ButtonHeight);
ObjectSetInteger(0, "CloseAllButton", OBJPROP_HIDDEN, false);
ObjectSetInteger(0, "CloseAllButton", OBJPROP_STATE, false);
ObjectSetString(0, "CloseAllButton", OBJPROP_TEXT, "Close All");
ObjectSetInteger(0, "CloseAllButton", OBJPROP_FONTSIZE, 12);
ObjectSetInteger(0, "CloseAllButton", OBJPROP_BORDER_TYPE, BORDER_RAISED);
ObjectSetInteger(0, "CloseAllButton", OBJPROP_CORNER, CORNER_LEFT_UPPER);
}

//+------------------------------------------------------------------+
//| Function to close all open positions |
//+------------------------------------------------------------------+
void CloseAllPositions()
{
for (int i = OrdersTotal() - 1; i >= 0; i--)
{
if (OrderSelect(i, SELECT_BY_POS))
{
if (OrderType() == OP_BUY || OrderType() == OP_SELL)
{
// Close position
if (!OrderClose(OrderTicket(), OrderLots(), OrderClosePrice(), Slippage, clrRed))
Print("Failed to close order: ", OrderTicket());
}
}
}
}

This EA places a “Close All” button on the chart. When clicked, the CloseAllPositions function is triggered, closing all open positions. The button’s position and size can be customized through input parameters.

To use this EA, copy the code into the MetaTrader 4 editor, compile, and run it on your trading chart.

Second Request:

Can the button click be handled as an event instead of state monitoring?

ChatGPT Output:

Yes, it is possible to handle button clicks using events. In MetaTrader 4, you can use the OnChartEvent function to process chart object events. The following code listens for button clicks and closes all positions when the button is pressed.

//+------------------------------------------------------------------+
//|                      CloseAllEA                                  |
//|    Copyright 2023, MetaQuotes Software Corp.                    |
//|    http://www.metaquotes.net/                                    |
//+------------------------------------------------------------------+
#property strict

input int ButtonX = 10;  // X-coordinate of the button  
input int ButtonY = 10;  // Y-coordinate of the button  
input int ButtonWidth = 100;  // Button width  
input int ButtonHeight = 30;  // Button height  
input int Slippage = 3;  // Slippage  

//+------------------------------------------------------------------+
//| Expert initialization function                                   |
//+------------------------------------------------------------------+
int OnInit()
{
   // Create the button
   CreateCloseAllButton();
   return(INIT_SUCCEEDED);
}

//+------------------------------------------------------------------+
//| Expert deinitialization function                                 |
//+------------------------------------------------------------------+
void OnDeinit(const int reason)
{
   // Delete the button
   ObjectDelete(0, "CloseAllButton");
}

//+------------------------------------------------------------------+
//| Expert tick function                                             |
//+------------------------------------------------------------------+
void OnTick()
{
   // Add any necessary logic here
}

//+------------------------------------------------------------------+
//| Chart event function                                             |
//+------------------------------------------------------------------+
void OnChartEvent(const int id, const long &lparam, const double &dparam, const string &sparam)
{
   if (id == CHARTEVENT_OBJECT_CLICK && sparam == "CloseAllButton")
   {
      // When the button is clicked, close all positions
      CloseAllPositions();
   }
}

//+------------------------------------------------------------------+
//| Function to create the button                                    |
//+------------------------------------------------------------------+
void CreateCloseAllButton()
{
   // Create the button
   if (!ObjectCreate(0, "CloseAllButton", OBJ_BUTTON, 0, 0, 0))
      Print("Failed to create the button!");

   // Set button properties
   ObjectSetInteger(0, "CloseAllButton", OBJPROP_CORNER, 0);
   ObjectSetInteger(0, "CloseAllButton", OBJPROP_XDISTANCE, ButtonX);
   ObjectSetInteger(0, "CloseAllButton", OBJPROP_YDISTANCE, ButtonY);
   ObjectSetInteger(0, "CloseAllButton", OBJPROP_WIDTH, ButtonWidth);
   ObjectSetInteger(0, "CloseAllButton", OBJPROP_HEIGHT, ButtonHeight);
   ObjectSetInteger(0, "CloseAllButton", OBJPROP_HIDDEN, false);
   ObjectSetInteger(0, "CloseAllButton", OBJPROP_STATE, false);
   ObjectSetString(0, "CloseAllButton", OBJPROP_TEXT, "Close All");
   ObjectSetInteger(0, "CloseAllButton", OBJPROP_FONTSIZE, 12);
   ObjectSetInteger(0, "CloseAllButton", OBJPROP_BORDER_TYPE, BORDER_RAISED);
   ObjectSetInteger(0, "CloseAllButton", OBJPROP_CORNER, CORNER_LEFT_UPPER);
}

//+------------------------------------------------------------------+
//| Function to close all open positions                            |
//+------------------------------------------------------------------+
void CloseAllPositions()
{
   for (int i = OrdersTotal() - 1; i >= 0; i--)
   {
      if (OrderSelect(i, SELECT_BY_POS))
      {
         if (OrderType() == OP_BUY || OrderType() == OP_SELL)
         {
            // Close position
            if (!OrderClose(OrderTicket(), OrderLots(), OrderClosePrice(), Slippage, clrRed))
               Print("Failed to close order: ", OrderTicket());
         }
      }
   }
}

This EA uses the OnChartEvent function to detect when the “Close All” button is clicked. Once clicked, it triggers the CloseAllPositions function to close all open positions. Unlike the previous version, which relied on state monitoring within OnTick, this implementation uses event-driven execution, making it more efficient.

Simply copy and compile this code in MetaTrader 4, and it will be ready for use.

Revised Code

Modifications:
There were issues where:

  • The button remained pressed after clicking.
  • The button size could not be changed.

These have been adjusted as follows:

input int ButtonX = 200;  // X-coordinate of the button  
input int ButtonY = 10;  // Y-coordinate of the button  
input int ButtonWidth = 80;  // Button width  
input int ButtonHeight = 20;  // Button height  
input int Slippage = 3;  // Slippage  

...  

//+------------------------------------------------------------------+
//| Expert tick function                                             |
//+------------------------------------------------------------------+  
void OnTick()  
{  
   // If any usual processing is needed, add it here.  
   // Reset button state  
   ObjectSetInteger(0, "CloseAllButton", OBJPROP_STATE, false);  
}  

//+------------------------------------------------------------------+
//| Chart event function                                             |
//+------------------------------------------------------------------+  
void OnChartEvent(const int id, const long &lparam, const double &dparam, const string &sparam)  
{  
   if (id == CHARTEVENT_OBJECT_CLICK && sparam == "CloseAllButton")  
   {  
      Print("Pressed.");  

      // Close all positions when the button is pressed  
      CloseAllPositions();  

      // Reset button state (Commented out as OnTick now handles this)  
      // ObjectSetInteger(0, "CloseAllButton", OBJPROP_STATE, false);  
   }  
}  

//+------------------------------------------------------------------+
//| Function to create the button                                    |
//+------------------------------------------------------------------+  
void CreateCloseAllButton()  
{  
   // Create the button  
   if (!ObjectCreate(0, "CloseAllButton", OBJ_BUTTON, 0, 0, 0))  
      Print("Failed to create the button!");  

   // Set button properties  
   ObjectSetInteger(0, "CloseAllButton", OBJPROP_CORNER, CORNER_RIGHT_UPPER);  
   ObjectSetInteger(0, "CloseAllButton", OBJPROP_XDISTANCE, ButtonX);  
   ObjectSetInteger(0, "CloseAllButton", OBJPROP_YDISTANCE, ButtonY);  
   ObjectSetInteger(0, "CloseAllButton", OBJPROP_XSIZE, ButtonWidth);  
   ObjectSetInteger(0, "CloseAllButton", OBJPROP_YSIZE, ButtonHeight);  
   ObjectSetInteger(0, "CloseAllButton", OBJPROP_HIDDEN, false);  
   ObjectSetInteger(0, "CloseAllButton", OBJPROP_STATE, false);  
   ObjectSetString(0, "CloseAllButton", OBJPROP_TEXT, "Close All");  
   ObjectSetInteger(0, "CloseAllButton", OBJPROP_FONTSIZE, 12);  
   ObjectSetInteger(0, "CloseAllButton", OBJPROP_BORDER_TYPE, BORDER_RAISED);  
}  

...  

📥 Download the Indicator

🚀 Get instant access to the Higher Timeframe MA & High/Low Indicator!

You can download the created EA below. While basic functionality has been tested, we cannot compensate for any losses incurred from its use. Please use it at your own risk and verify its operation thoroughly.

👉 Download Now (Unlock content to access the file)

📢 Looking for More Trading Tools?

Explore my blog for more free MT4 indicators and trading strategies!
👉 Visit FX Trading Gym

🚀 Thank You for Using Our Tools! A Small Favor to Ask 🚀

Thank you so much for choosing our FX indicators and tools!
To support your success in FX trading, we’ve carefully selected some services that can help you achieve better results.
If you find them useful, we’d greatly appreciate your support.

Your participation will not only motivate us but also help us continue to develop even better tools for you in the future!

💼 Increase Your Profits with an Overseas FX Account!
🌍 Exness Account – The Broker I Trust the Most!
  • Industry-low spreads to reduce trading costs
  • Fully compatible with MT4/MT5, perfect for automated trading (EA)
  • Instant withdrawals for smooth fund management

👉 Open an Exness Account Now (Special Offer)



💸 Reduce Trading Costs with Cashback from Overseas FX Accounts!
 🚀 TariTali – High Cashback Rates That Make a Difference!
  • Maximize savings with high-rate cashback on every trade
  • Supports a wide range of MT4/MT5 brokers, ideal for EAs
  • Real-time tracking of your cashback history
  • Fast withdrawals to domestic bank accounts

👉 Cut Your Trading Costs Smartly with TariTali!

海外FXキャッシュバック口座開設ならTariTali(タリタリ)

🔥 Money Charger – The New Standard for Forex Cashback!
  • Automatic cashback on every trade → The more you trade, the more you earn!
  • Industry-leading cashback rates for maximum profit efficiency
  • Simple registration with instant cashback available
  • Supports multiple brokers, giving you flexible account choices

👉 Start Earning Cashback with Money Charger Today!
More details: Complete Guide to Forex Cashback

🤖 Accelerate Your Profits with Automated Trading Systems (EAs)!
🔥 Introducing High-Performance EAs I’ve Developed
  • Poundeur (HL Band M15 for GJ) → The best choice for stable profits
  • BBHL Band H1 for EJ & BBHL Band H1 for AJ → Excellent performance even in high-volatility markets

👉 Discover Our Profitable MT4 EAs for FX Traders

📊 Check Out the Most Popular EAs!
  • Handpicked EAs trusted by many traders
  • Performance records and profit data are publicly available

👉 See the Top-Ranked EAs Now

関連記事

スポンサーリンク
海外FXキャッシュバック口座開設ならTariTali(タリタリ)

コメント

タイトルとURLをコピーしました