消息前十分钟自动撤挂单减仓 写了个小脚本
上周消息夜那半分钟,没成交的挂单直接跳过了,还有一张成交价比我设的滑了一截,事后就想着把这一步交给脚本。逻辑很简单,到点前十分钟把挂单全删掉,持仓按比例减一半,消息过后自动解除,时间点和减仓比例都是参数,想改成哪个自己改都能改。代码不长,贴下面,需要就自己拿去改。
//+------------------------------------------------------------------+
//| NewsGuard.mq5 |
//| 消息窗口保护:提前 N 分钟撤掉全部挂单 持仓按比例减仓 |
//| 消息过后 M 分钟自动解除 参数自己改 |
//+------------------------------------------------------------------+
#property version "1.00"
#property strict
#include <Trade\Trade.mqh>
input int InpGuardHour = 21; // 消息小时(服务器时间)
input int InpGuardMinute = 30; // 消息分钟
input int InpBeforeMin = 10; // 提前几分钟开始
input int InpAfterMin = 5; // 消息后几分钟解除
input double InpCutRatio = 0.50; // 提前减仓比例 0.5 表示减一半
bool g_guarded = false;
CTrade trade;
bool InWindow()
{
MqlDateTime t;
TimeToStruct(TimeCurrent(), t);
int nowMin = t.hour * 60 + t.min;
int newsMin = InpGuardHour * 60 + InpGuardMinute;
return (nowMin >= newsMin - InpBeforeMin && nowMin <= newsMin + InpAfterMin);
}
void CutPositions(double ratio)
{
for(int i = PositionsTotal() - 1; i >= 0; i--)
{
ulong ticket = PositionGetTicket(i);
if(ticket == 0) continue;
double vol = PositionGetDouble(POSITION_VOLUME);
double cut = NormalizeDouble(vol * ratio, 2);
if(cut <= 0.0) continue;
trade.PositionClosePartial(ticket, cut);
}
}
int OnInit()
{
trade.SetExpertMagicNumber(20261107);
return INIT_SUCCEEDED;
}
void OnTick()
{
bool inWin = InWindow();
if(inWin && !g_guarded)
{
g_guarded = true;
for(int i = OrdersTotal() - 1; i >= 0; i--)
{
ulong ticket = OrderGetTicket(i);
if(ticket > 0) trade.OrderDelete(ticket);
}
CutPositions(InpCutRatio);
Print("NewsGuard on, orders cleared, positions cut ", DoubleToString(InpCutRatio, 2));
}
if(!inWin && g_guarded)
{
g_guarded = false;
Print("NewsGuard off");
}
}
全部回复(20)
发表回复
请先登录后再回复。
