本教程提供一个可直接使用的MT4脚本源码,一键关闭所有持仓和挂单。手工交易者和EA用户都需要这个工具,在高波动或新闻事件前快速管理风险。
为什么需要一键平仓脚本?
MT4默认界面关闭每个订单需要多次点击。本脚本将其简化为一次拖放操作,毫秒级关闭全部或指定订单。这是每位交易者工具包中必备的免费EA下载工具。
完整MQL4源码
```cpp
//+------------------------------------------------------------------+
//| CloseAllOrders_V1.mq4 |
//| Generated by AutoCompile AI |
//| |
//+------------------------------------------------------------------+
#property copyright "AutoCompile AI"
#property link ""
#property version "1.00"
#property strict
#property script_show_inputs
//--- 输入参数
input bool CloseMarketBuys = true; // 关闭市价买单持仓
input bool CloseMarketSells = true; // 关闭市价卖单持仓
input bool ClosePendingBuys = true; // 关闭买入挂单(限价/止损)
input bool ClosePendingSells = true; // 关闭卖出挂单(限价/止损)
input int MagicFilter = -1; // 魔术号过滤(-1表示全部)
input bool ShowConfirmDialog = true; // 关闭前显示确认对话框
//+------------------------------------------------------------------+
//| 脚本程序启动函数 |
//+------------------------------------------------------------------+
void OnStart()
{
int totalOrders = OrdersTotal();
if(totalOrders == 0)
{
Print("未找到任何订单。");
return;
}
string confirmMsg = "将关闭 ";
int count = 0;
for(int i=0; i
if(OrderSelect(i, SELECT_BY_POS, MODE_TRADES))
{
if(MagicFilter != -1 && OrderMagicNumber() != MagicFilter)
continue;
int type = OrderType();
if(type == OP_BUY && CloseMarketBuys) count++;
else if(type == OP_SELL && CloseMarketSells) count++;
else if((type == OP_BUYLIMIT || type == OP_BUYSTOP) && ClosePendingBuys) count++;
else if((type == OP_SELLLIMIT || type == OP_SELLSTOP) && ClosePendingSells) count++;
}
}
if(count == 0)
{
Print("没有订单匹配所选过滤条件。");
return;
}
if(ShowConfirmDialog && MessageBox("将关闭 " + IntegerToString(count) + " 个订单?",
"确认平仓", MB_YESNO | MB_ICONQUESTION) != IDYES)
{
Print("用户取消了平仓操作。");
return;
}
int closed = 0;
int errors = 0;
for(int i=OrdersTotal()-1; i>=0; i--)
{
if(OrderSelect(i, SELECT_BY_POS, MODE_TRADES))
{
if(MagicFilter != -1 && OrderMagicNumber() != MagicFilter)
continue;
int type = OrderType();
bool shouldClose = false;
if(type == OP_BUY && CloseMarketBuys)
shouldClose = true;
else if(type == OP_SELL && CloseMarketSells)
shouldClose = true;
else if((type == OP_BUYLIMIT || type == OP_BUYSTOP) && ClosePendingBuys)
shouldClose = true;
else if((type == OP_SELLLIMIT || type == OP_SELLSTOP) && ClosePendingSells)
shouldClose = true;
if(shouldClose)
{
bool result = OrderClose(OrderTicket(), OrderLots(),
OrderClosePrice(), 100, clrRed);
if(result)
closed++;
else
{
errors++;
Print("关闭订单 #", OrderTicket(), " 失败,错误码:", GetLastError());
}
}
}
}
Print("平仓完成:成功 ", closed, " 个,失败 ", errors, " 个。");
}
//+------------------------------------------------------------------+
```
如何编译与使用
1. 将代码保存为 `CloseAllOrders_V1.mq4`,放入MT4数据目录的 `Scripts` 文件夹。
2. 打开MetaEditor,按F7编译,确保无错误。
3. 从导航器窗口将脚本拖拽到任意图表上。
4. 若启用了确认对话框,会显示待关闭订单数量。
参数说明
使用技巧
对于需要高级逻辑(移动止损、保本止损、部分平仓)的自动化仓位管理的交易者,我们的高级版EA管理套件提供完整解决方案。订阅获取更多免费工具和更新。
参考来源:AutoCompile AI - 原创MQL4实现,2025年。
```