//+------------------------------------------------------------------+
//| MyIndicator.mq4|
//| Copyright 2022, MetaQuotes Software Corp. |
//| https://www.mql5.com |
//+------------------------------------------------------------------+
#property indicator_chart_window
double longProfit = 0; // 多头盈利总和
double shortProfit = 0; // 空头盈利总和
//+------------------------------------------------------------------+
//| Custom indicator initialization function |
//+------------------------------------------------------------------+
int OnInit()
{
// 在初始化时,清空盈利总和
longProfit = 0;
shortProfit = 0;
return(INIT_SUCCEEDED);
}
//+------------------------------------------------------------------+
//| Custom indicator iteration function |
//+------------------------------------------------------------------+
int OnCalculate(const int rates_total,
const int prev_calculated,
const datetime &time[],
const double &open[],
const double &high[],
const double &low[],
const double &close[],
const long &tick_volume[],
const long &volume[],
const int &spread[])
{
// 遍历所有已开仓的交易
for(int i = OrdersTotal() - 1; i >= 0; i--)
{
if(OrderSelect(i, SELECT_BY_POS, MODE_TRADES))
{
// 只统计品种为当前指标应用品种的多空盈利
if(OrderSymbol() == Symbol())
{
if(OrderType() == OP_BUY)
{
// 累计多头盈利
longProfit += OrderProfit();
}
else if(OrderType() == OP_SELL)
{
// 累计空头盈利
shortProfit += OrderProfit();
}
}
}
}
// 打印多头和空头盈利总和
printf("多头盈利总和:%.2f", longProfit);
printf("空头盈利总和:%.2f", shortProfit);
return(rates_total);
}
//+------------------------------------------------------------------+
//| CloseAll.mq4 |
//| Copyright 2022, MetaQuotes Software Corp. |
//| https://www.mql5.com |
//+------------------------------------------------------------------+
#property script_show_inputs
//+------------------------------------------------------------------+
//| Script program start function |
//+------------------------------------------------------------------+
void OnStart()
{
// 遍历所有已开仓的交易
for(int i = OrdersTotal() - 1; i >= 0; i--)
{
if(OrderSelect(i, SELECT_BY_POS, MODE_TRADES))
{
// 只平仓品种为当前图表上的品种的交易
if(OrderSymbol() == Symbol())
{
// 平仓交易
if(OrderType() == OP_BUY || OrderType() == OP_SELL)
{
if(OrderClose(OrderTicket(), OrderLots(), MarketInfo(OrderSymbol(), MODE_BID), 10) == true)
{
Print("平仓交易成功:", OrderTicket());
}
else
{
Print("平仓交易失败:", OrderTicket(), "错误代码:", GetLastError());
}
}
}
}
}
}