634 lines
26 KiB
MQL5
//+------------------------------------------------------------------+
| |||
//| PropNewsSpreadGuard.mq5 |
| |||
//| ForexNewsRadar |
| |||
//| https://www.mql5.com/en/users/forexnewsradar |
| |||
//+------------------------------------------------------------------+
| |||
#property copyright "ForexNewsRadar"
| |||
#property link "https://www.mql5.com/en/users/forexnewsradar"
| |||
#property version "1.00"
| |||
#property description "Standalone Prop-Firm Pre-News Blackout, Spread-Spike VETO & Pending-Order Guard EA."
| |||
#property description "Combines native MQL5 Economic Calendar countdowns, recurring macro blackout windows,"
| |||
#property description "EMA spread-widening detection, non-destructive pending-order cleanup, and RAM bridge."
| |||
| |||
#include <Trade\Trade.mqh>
| |||
| |||
//+------------------------------------------------------------------+
| |||
//| Enumerations |
| |||
//+------------------------------------------------------------------+
| |||
enum ENUM_GUARD_CORNER
| |||
{
| |||
GUARD_CORNER_TOP_RIGHT = 0, // Top-Right Chart Corner
| |||
GUARD_CORNER_TOP_LEFT = 1, // Top-Left Chart Corner
| |||
GUARD_CORNER_BOTTOM_RIGHT = 2, // Bottom-Right Chart Corner
| |||
GUARD_CORNER_BOTTOM_LEFT = 3 // Bottom-Left Chart Corner
| |||
};
| |||
| |||
enum ENUM_GUARD_STATUS
| |||
{
| |||
STATUS_SAFE_CLEAR = 0,
| |||
STATUS_PRE_NEWS = 1,
| |||
STATUS_POST_NEWS = 2,
| |||
STATUS_TIME_WINDOW = 3,
| |||
STATUS_SPREAD_VETO = 4
| |||
};
| |||
| |||
//+------------------------------------------------------------------+
| |||
//| Input Parameters |
| |||
//+------------------------------------------------------------------+
| |||
input group "=== 1. Prop-Firm News Blackout Rules ==="
| |||
input bool InpUseNativeCalendar = true; // Use Native MT5 Economic Calendar
| |||
input bool InpIncludeModerateNews = false; // Include Medium-Impact News (false = High Only)
| |||
input int InpPreNewsMinutes = 5; // Pre-News Blackout Window (Minutes, e.g. T-5m)
| |||
input int InpPostNewsMinutes = 5; // Post-News Cooldown Window (Minutes, e.g. T+5m)
| |||
| |||
input group "=== 2. Recurring Daily Macro Window Fallback (Server Time) ==="
| |||
input bool InpUseDailyWindowFallback = false; // Enable Recurring Daily Blackout Window
| |||
input int InpWindowStartHour = 15; // Daily Blackout Start Hour (0..23 Server Time)
| |||
input int InpWindowStartMinute = 25; // Daily Blackout Start Minute (0..59)
| |||
input int InpWindowDurationMinutes = 15; // Daily Blackout Duration (Minutes)
| |||
| |||
input group "=== 3. Spread-Spike & Liquidity Vacuum VETO ==="
| |||
input bool InpUseSpreadGuard = true; // Enable Live Spread-Spike VETO
| |||
input int InpMaxSpreadPoints = 35; // Hard Max Allowed Spread (Points, 0 = Disabled)
| |||
input double InpSpreadSpikeMultiplier = 2.20; // Dynamic Spike Multiplier vs Rolling EMA (0 = Off)
| |||
input int InpSpreadEmaSamples = 60; // Rolling Spread EMA Smoothing Samples
| |||
| |||
input group "=== 4. Pending-Order Sweeper & Cross-EA RAM Bridge ==="
| |||
input bool InpSweepPendingOnVeto = false; // Delete Pending Orders During Active VETO
| |||
input long InpTargetMagicNumber = -1; // Pending Order Magic Filter (-1 = All Magic Numbers)
| |||
input bool InpPublishGlobalVars = true; // Publish FNR_GUARD_SAFE_<SYMBOL> GlobalVariables
| |||
input bool InpSendPushNotifications = false; // Send MT5 Mobile Push Alert on VETO Transition
| |||
| |||
input group "=== 5. On-Chart Institutional HUD ==="
| |||
input bool InpShowHudPanel = true; // Render Non-Destructive On-Chart HUD Panel
| |||
input ENUM_GUARD_CORNER InpHudCorner = GUARD_CORNER_TOP_RIGHT;// HUD Anchor Corner
| |||
input int InpHudOffsetX = 16; // Horizontal Offset (Pixels)
| |||
input int InpHudOffsetY = 24; // Vertical Offset (Pixels)
| |||
| |||
//+------------------------------------------------------------------+
| |||
//| Constants & Global State |
| |||
//+------------------------------------------------------------------+
| |||
#define HUD_PREFIX "FNR_SG_"
| |||
| |||
double g_emaSpreadPts = 0.0;
| |||
bool g_emaInitialized = false;
| |||
ENUM_GUARD_STATUS g_currentStatus = STATUS_SAFE_CLEAR;
| |||
ENUM_GUARD_STATUS g_previousStatus = STATUS_SAFE_CLEAR;
| |||
string g_statusDetail = "All 4 Prop Risk Checks Clear";
| |||
string g_nextEventLabel = "None in next 24h";
| |||
int g_nextEventSec = -1;
| |||
int g_vetoRemainingSec = 0;
| |||
ulong g_sweptOrdersCount = 0;
| |||
datetime g_lastCalendarCheck = 0;
| |||
bool g_calendarAvailable = false;
| |||
| |||
struct CachedNewsWindow
| |||
{
| |||
datetime eventTime;
| |||
string currency;
| |||
string eventName;
| |||
bool isHighImpact;
| |||
};
| |||
| |||
CachedNewsWindow g_cachedEvents[];
| |||
| |||
//+------------------------------------------------------------------+
| |||
//| Clean Currency Code Helper |
| |||
//+------------------------------------------------------------------+
| |||
string CleanCurrencyCode(const string rawCode)
| |||
{
| |||
string code = rawCode;
| |||
StringTrimLeft(code);
| |||
StringTrimRight(code);
| |||
StringToUpper(code);
| |||
return code;
| |||
}
| |||
| |||
//+------------------------------------------------------------------+
| |||
//| Resolve Relevant Currencies for Current Symbol |
| |||
//+------------------------------------------------------------------+
| |||
void ResolveSymbolCurrencies(string &baseCcy, string &profitCcy)
| |||
{
| |||
baseCcy = CleanCurrencyCode(SymbolInfoString(_Symbol, SYMBOL_CURRENCY_BASE));
| |||
profitCcy = CleanCurrencyCode(SymbolInfoString(_Symbol, SYMBOL_CURRENCY_PROFIT));
| |||
| |||
string upSym = _Symbol;
| |||
StringToUpper(upSym);
| |||
if(StringFind(upSym, "XAU") >= 0 || StringFind(upSym, "GOLD") >= 0 ||
| |||
StringFind(upSym, "XAG") >= 0 || StringFind(upSym, "SILVER") >= 0)
| |||
{
| |||
if(profitCcy == "" || profitCcy == "XAU" || profitCcy == "XAG")
| |||
profitCcy = "USD";
| |||
}
| |||
}
| |||
| |||
//+------------------------------------------------------------------+
| |||
//| Refresh Native MQL5 Calendar Cache (Once per 60s) |
| |||
//+------------------------------------------------------------------+
| |||
void RefreshCalendarCache()
| |||
{
| |||
ArrayResize(g_cachedEvents, 0);
| |||
g_calendarAvailable = false;
| |||
| |||
if(!InpUseNativeCalendar || (bool)MQLInfoInteger(MQL_TESTER))
| |||
return;
| |||
| |||
datetime nowSrv = TimeTradeServer();
| |||
if(nowSrv <= 0)
| |||
nowSrv = TimeCurrent();
| |||
| |||
datetime fromTime = nowSrv - (datetime)(MathMax(InpPostNewsMinutes, 10) * 60 + 300);
| |||
datetime toTime = nowSrv + 86400;
| |||
| |||
string baseCcy = "", profitCcy = "";
| |||
ResolveSymbolCurrencies(baseCcy, profitCcy);
| |||
| |||
MqlCalendarValue values[];
| |||
ResetLastError();
| |||
int count = CalendarValueHistory(values, fromTime, toTime, NULL, NULL);
| |||
if(count <= 0)
| |||
return;
| |||
| |||
g_calendarAvailable = true;
| |||
| |||
for(int i = 0; i < count; i++)
| |||
{
| |||
MqlCalendarEvent ev;
| |||
if(!CalendarEventById(values[i].event_id, ev))
| |||
continue;
| |||
| |||
bool isHigh = (ev.importance == CALENDAR_IMPORTANCE_HIGH);
| |||
bool isMod = (ev.importance == CALENDAR_IMPORTANCE_MODERATE);
| |||
if(!isHigh && !(InpIncludeModerateNews && isMod))
| |||
continue;
| |||
| |||
MqlCalendarCountry country;
| |||
if(!CalendarCountryById(ev.country_id, country))
| |||
continue;
| |||
| |||
string evCcy = CleanCurrencyCode(country.currency);
| |||
if(evCcy == "")
| |||
continue;
| |||
| |||
if(evCcy != baseCcy && evCcy != profitCcy)
| |||
continue;
| |||
| |||
int idx = ArraySize(g_cachedEvents);
| |||
ArrayResize(g_cachedEvents, idx + 1, 32);
| |||
g_cachedEvents[idx].eventTime = values[i].time;
| |||
g_cachedEvents[idx].currency = evCcy;
| |||
g_cachedEvents[idx].eventName = ev.name;
| |||
g_cachedEvents[idx].isHighImpact = isHigh;
| |||
}
| |||
}
| |||
| |||
//+------------------------------------------------------------------+
| |||
//| Format Seconds into Compact Human Countdown |
| |||
//+------------------------------------------------------------------+
| |||
string FormatDurationCompact(const int totalSec)
| |||
{
| |||
if(totalSec <= 0)
| |||
return "0s";
| |||
int hrs = totalSec / 3600;
| |||
int mins = (totalSec % 3600) / 60;
| |||
int secs = totalSec % 60;
| |||
if(hrs > 0)
| |||
return IntegerToString(hrs) + "h " + IntegerToString(mins) + "m";
| |||
if(mins > 0)
| |||
return IntegerToString(mins) + "m " + IntegerToString(secs) + "s";
| |||
return IntegerToString(secs) + "s";
| |||
}
| |||
| |||
//+------------------------------------------------------------------+
| |||
//| Evaluate Active Risk State |
| |||
//+------------------------------------------------------------------+
| |||
void EvaluateGuardState()
| |||
{
| |||
datetime nowSrv = TimeTradeServer();
| |||
if(nowSrv <= 0)
| |||
nowSrv = TimeCurrent();
| |||
| |||
// 1. Refresh calendar cache every 60 seconds outside Strategy Tester
| |||
if(InpUseNativeCalendar && !(bool)MQLInfoInteger(MQL_TESTER))
| |||
{
| |||
if(g_lastCalendarCheck == 0 || (nowSrv - g_lastCalendarCheck) >= 60)
| |||
{
| |||
RefreshCalendarCache();
| |||
g_lastCalendarCheck = nowSrv;
| |||
}
| |||
}
| |||
| |||
// 2. Update live spread & rolling EMA baseline
| |||
long rawSpread = SymbolInfoInteger(_Symbol, SYMBOL_SPREAD);
| |||
double curSpread = (rawSpread > 0) ? (double)rawSpread : 0.0;
| |||
int samples = MathMax(5, InpSpreadEmaSamples);
| |||
double alpha = 2.0 / ((double)samples + 1.0);
| |||
| |||
if(!g_emaInitialized || g_emaSpreadPts <= 0.0)
| |||
{
| |||
if(curSpread > 0.0)
| |||
{
| |||
g_emaSpreadPts = curSpread;
| |||
g_emaInitialized = true;
| |||
}
| |||
}
| |||
else if(curSpread > 0.0 && g_currentStatus == STATUS_SAFE_CLEAR)
| |||
{
| |||
// Update baseline EMA only during calm periods so news spikes do not pollute baseline
| |||
g_emaSpreadPts = curSpread * alpha + g_emaSpreadPts * (1.0 - alpha);
| |||
}
| |||
| |||
ENUM_GUARD_STATUS resolvedStatus = STATUS_SAFE_CLEAR;
| |||
string resolvedDetail = "All Prop-Firm Risk Checks Clear";
| |||
int resolvedWait = 0;
| |||
| |||
// 3. Evaluate Native Calendar Windows
| |||
g_nextEventSec = -1;
| |||
g_nextEventLabel = (InpUseNativeCalendar && !g_calendarAvailable && !(bool)MQLInfoInteger(MQL_TESTER))
| |||
? "Broker Calendar Empty/Off"
| |||
: "No High-Impact in 24h";
| |||
| |||
int preSec = MathMax(0, InpPreNewsMinutes) * 60;
| |||
int postSec = MathMax(0, InpPostNewsMinutes) * 60;
| |||
int totalEv = ArraySize(g_cachedEvents);
| |||
| |||
for(int i = 0; i < totalEv; i++)
| |||
{
| |||
int deltaSec = (int)(g_cachedEvents[i].eventTime - nowSrv);
| |||
| |||
// Track nearest upcoming catalyst
| |||
if(deltaSec > 0 && (g_nextEventSec < 0 || deltaSec < g_nextEventSec))
| |||
{
| |||
g_nextEventSec = deltaSec;
| |||
string shortTitle = g_cachedEvents[i].eventName;
| |||
if(StringLen(shortTitle) > 24)
| |||
shortTitle = StringSubstr(shortTitle, 0, 22) + "..";
| |||
g_nextEventLabel = g_cachedEvents[i].currency + " " + shortTitle + " in " + FormatDurationCompact(deltaSec);
| |||
}
| |||
| |||
// Check Pre-News Blackout [eventTime - preSec .. eventTime]
| |||
if(deltaSec >= 0 && deltaSec <= preSec && preSec > 0)
| |||
{
| |||
resolvedStatus = STATUS_PRE_NEWS;
| |||
resolvedWait = deltaSec + postSec;
| |||
resolvedDetail = "PRE-NEWS HOLD: " + g_cachedEvents[i].currency + " in " + FormatDurationCompact(deltaSec);
| |||
break;
| |||
}
| |||
| |||
// Check Post-News Cooldown [eventTime .. eventTime + postSec]
| |||
if(deltaSec < 0 && (-deltaSec) <= postSec && postSec > 0)
| |||
{
| |||
int rem = postSec - (-deltaSec);
| |||
resolvedStatus = STATUS_POST_NEWS;
| |||
resolvedWait = rem;
| |||
resolvedDetail = "POST-NEWS VETO: Cooldown " + FormatDurationCompact(rem);
| |||
break;
| |||
}
| |||
}
| |||
| |||
// 4. Evaluate Recurring Daily Time Window Fallback (when enabled)
| |||
if(resolvedStatus == STATUS_SAFE_CLEAR && InpUseDailyWindowFallback && InpWindowDurationMinutes > 0)
| |||
{
| |||
MqlDateTime dt;
| |||
TimeToStruct(nowSrv, dt);
| |||
int curMinOfDay = dt.hour * 60 + dt.min;
| |||
int startMinOfDay = (MathMax(0, MathMin(23, InpWindowStartHour)) * 60) + MathMax(0, MathMin(59, InpWindowStartMinute));
| |||
int durMin = MathMin(720, MathMax(1, InpWindowDurationMinutes));
| |||
int diffMin = curMinOfDay - startMinOfDay;
| |||
if(diffMin < 0)
| |||
diffMin += 1440;
| |||
| |||
if(diffMin >= 0 && diffMin < durMin)
| |||
{
| |||
int remSec = (durMin - diffMin) * 60 - dt.sec;
| |||
if(remSec < 1)
| |||
remSec = 1;
| |||
resolvedStatus = STATUS_TIME_WINDOW;
| |||
resolvedWait = remSec;
| |||
resolvedDetail = "SCHEDULED BLACKOUT: " + FormatDurationCompact(remSec) + " left";
| |||
}
| |||
}
| |||
| |||
// 5. Evaluate Spread-Spike & Liquidity Vacuum Guard
| |||
if(resolvedStatus == STATUS_SAFE_CLEAR && InpUseSpreadGuard && curSpread > 0.0)
| |||
{
| |||
bool hardBreach = (InpMaxSpreadPoints > 0 && curSpread > (double)InpMaxSpreadPoints);
| |||
bool emaBreach = (InpSpreadSpikeMultiplier > 1.0 && g_emaSpreadPts >= 1.0 &&
| |||
curSpread >= (g_emaSpreadPts * InpSpreadSpikeMultiplier) &&
| |||
curSpread >= 5.0);
| |||
if(hardBreach || emaBreach)
| |||
{
| |||
resolvedStatus = STATUS_SPREAD_VETO;
| |||
resolvedWait = 15;
| |||
resolvedDetail = "SPREAD VETO: " + IntegerToString((int)curSpread) + " pts (EMA " +
| |||
DoubleToString(g_emaSpreadPts, 1) + " pts)";
| |||
}
| |||
}
| |||
| |||
g_currentStatus = resolvedStatus;
| |||
g_statusDetail = resolvedDetail;
| |||
g_vetoRemainingSec = resolvedWait;
| |||
}
| |||
| |||
//+------------------------------------------------------------------+
| |||
//| Publish Cross-EA Safety Flag to Terminal RAM |
| |||
//+------------------------------------------------------------------+
| |||
void PublishRamBridge()
| |||
{
| |||
if(!InpPublishGlobalVars)
| |||
return;
| |||
| |||
string keySafe = "FNR_GUARD_SAFE_" + _Symbol;
| |||
string keyWait = "FNR_GUARD_WAIT_" + _Symbol;
| |||
| |||
if(!GlobalVariableCheck(keySafe))
| |||
GlobalVariableTemp(keySafe);
| |||
if(!GlobalVariableCheck(keyWait))
| |||
GlobalVariableTemp(keyWait);
| |||
| |||
double isSafe = (g_currentStatus == STATUS_SAFE_CLEAR) ? 1.0 : 0.0;
| |||
GlobalVariableSet(keySafe, isSafe);
| |||
GlobalVariableSet(keyWait, (double)g_vetoRemainingSec);
| |||
}
| |||
| |||
//+------------------------------------------------------------------+
| |||
//| Safely Sweep Unexecuted Pending Orders on Current Symbol |
| |||
//+------------------------------------------------------------------+
| |||
void SweepPendingOrdersIfRequired()
| |||
{
| |||
if(!InpSweepPendingOnVeto || g_currentStatus == STATUS_SAFE_CLEAR)
| |||
return;
| |||
| |||
if(!TerminalInfoInteger(TERMINAL_TRADE_ALLOWED) ||
| |||
!MQLInfoInteger(MQL_TRADE_ALLOWED) ||
| |||
!AccountInfoInteger(ACCOUNT_TRADE_EXPERT))
| |||
return;
| |||
| |||
ENUM_SYMBOL_TRADE_MODE tradeMode = (ENUM_SYMBOL_TRADE_MODE)SymbolInfoInteger(_Symbol, SYMBOL_TRADE_MODE);
| |||
if(tradeMode == SYMBOL_TRADE_MODE_DISABLED)
| |||
return;
| |||
| |||
long freezePts = SymbolInfoInteger(_Symbol, SYMBOL_TRADE_FREEZE_LEVEL);
| |||
double pointVal = SymbolInfoDouble(_Symbol, SYMBOL_POINT);
| |||
double bid = SymbolInfoDouble(_Symbol, SYMBOL_BID);
| |||
double ask = SymbolInfoDouble(_Symbol, SYMBOL_ASK);
| |||
| |||
CTrade trade;
| |||
trade.SetAsyncMode(false);
| |||
| |||
int total = OrdersTotal();
| |||
for(int i = total - 1; i >= 0; i--)
| |||
{
| |||
ulong ticket = OrderGetTicket(i);
| |||
if(ticket == 0)
| |||
continue;
| |||
| |||
if(OrderGetString(ORDER_SYMBOL) != _Symbol)
| |||
continue;
| |||
| |||
if(InpTargetMagicNumber >= 0 && OrderGetInteger(ORDER_MAGIC) != InpTargetMagicNumber)
| |||
continue;
| |||
| |||
ENUM_ORDER_TYPE ordType = (ENUM_ORDER_TYPE)OrderGetInteger(ORDER_TYPE);
| |||
bool isPending = (ordType == ORDER_TYPE_BUY_LIMIT ||
| |||
ordType == ORDER_TYPE_SELL_LIMIT ||
| |||
ordType == ORDER_TYPE_BUY_STOP ||
| |||
ordType == ORDER_TYPE_SELL_STOP ||
| |||
ordType == ORDER_TYPE_BUY_STOP_LIMIT ||
| |||
ordType == ORDER_TYPE_SELL_STOP_LIMIT);
| |||
if(!isPending)
| |||
continue;
| |||
| |||
// Respect broker freeze level before attempting deletion
| |||
if(freezePts > 0 && pointVal > 0.0 && bid > 0.0 && ask > 0.0)
| |||
{
| |||
double openPrice = OrderGetDouble(ORDER_PRICE_OPEN);
| |||
double refPrice = (ordType == ORDER_TYPE_BUY_LIMIT || ordType == ORDER_TYPE_BUY_STOP || ordType == ORDER_TYPE_BUY_STOP_LIMIT)
| |||
? ask : bid;
| |||
double distPts = MathAbs(openPrice - refPrice) / pointVal;
| |||
if(distPts <= (double)freezePts)
| |||
continue;
| |||
}
| |||
| |||
ResetLastError();
| |||
if(trade.OrderDelete(ticket))
| |||
{
| |||
g_sweptOrdersCount++;
| |||
Print("PropNewsSpreadGuard: Removed pending order #", ticket, " on ", _Symbol, " (", g_statusDetail, ")");
| |||
}
| |||
}
| |||
}
| |||
| |||
//+------------------------------------------------------------------+
| |||
//| Resolve Base Chart Corner |
| |||
//+------------------------------------------------------------------+
| |||
ENUM_BASE_CORNER ResolveBaseCorner()
| |||
{
| |||
switch(InpHudCorner)
| |||
{
| |||
case GUARD_CORNER_TOP_LEFT: return CORNER_LEFT_UPPER;
| |||
case GUARD_CORNER_BOTTOM_RIGHT: return CORNER_RIGHT_LOWER;
| |||
case GUARD_CORNER_BOTTOM_LEFT: return CORNER_LEFT_LOWER;
| |||
default: return CORNER_RIGHT_UPPER;
| |||
}
| |||
}
| |||
| |||
//+------------------------------------------------------------------+
| |||
//| Create or Update Single HUD Text Row |
| |||
//+------------------------------------------------------------------+
| |||
void UpsertHudLabel(const string name,
| |||
const ENUM_BASE_CORNER corner,
| |||
const int xDist,
| |||
const int yDist,
| |||
const string text,
| |||
const color clr,
| |||
const int fontSize,
| |||
const bool isBold)
| |||
{
| |||
if(ObjectFind(0, name) < 0)
| |||
{
| |||
if(!ObjectCreate(0, name, OBJ_LABEL, 0, 0, 0))
| |||
return;
| |||
ObjectSetInteger(0, name, OBJPROP_SELECTABLE, false);
| |||
ObjectSetInteger(0, name, OBJPROP_SELECTED, false);
| |||
ObjectSetInteger(0, name, OBJPROP_HIDDEN, true);
| |||
ObjectSetInteger(0, name, OBJPROP_BACK, false);
| |||
}
| |||
| |||
ObjectSetInteger(0, name, OBJPROP_CORNER, corner);
| |||
ObjectSetInteger(0, name, OBJPROP_ANCHOR, ANCHOR_LEFT_UPPER);
| |||
| |||
ObjectSetInteger(0, name, OBJPROP_XDISTANCE, xDist);
| |||
ObjectSetInteger(0, name, OBJPROP_YDISTANCE, yDist);
| |||
ObjectSetInteger(0, name, OBJPROP_FONTSIZE, fontSize);
| |||
ObjectSetInteger(0, name, OBJPROP_COLOR, clr);
| |||
ObjectSetString(0, name, OBJPROP_FONT, isBold ? "Trebuchet MS Bold" : "Consolas");
| |||
ObjectSetString(0, name, OBJPROP_TEXT, text);
| |||
}
| |||
| |||
//+------------------------------------------------------------------+
| |||
//| Render Non-Destructive Institutional HUD Card |
| |||
//+------------------------------------------------------------------+
| |||
void RenderHudPanel()
| |||
{
| |||
if(!InpShowHudPanel || ((bool)MQLInfoInteger(MQL_TESTER) && !(bool)MQLInfoInteger(MQL_VISUAL_MODE)))
| |||
return;
| |||
| |||
ENUM_BASE_CORNER corner = ResolveBaseCorner();
| |||
int cardW = 308;
| |||
int cardH = 104;
| |||
| |||
int boxX = InpHudOffsetX;
| |||
int boxY = InpHudOffsetY;
| |||
| |||
// In right-hand corners, OBJ_RECTANGLE_LABEL XDISTANCE is distance from right edge to left edge of rectangle
| |||
if(corner == CORNER_RIGHT_UPPER || corner == CORNER_RIGHT_LOWER)
| |||
boxX = InpHudOffsetX + cardW;
| |||
if(corner == CORNER_LEFT_LOWER || corner == CORNER_RIGHT_LOWER)
| |||
boxY = InpHudOffsetY + cardH;
| |||
| |||
string bgName = HUD_PREFIX + "BG";
| |||
string accentName = HUD_PREFIX + "ACCENT";
| |||
| |||
bool isSafe = (g_currentStatus == STATUS_SAFE_CLEAR);
| |||
color borderClr = isSafe ? C'24,78,58' : (g_currentStatus == STATUS_PRE_NEWS ? C'146,92,18' : C'136,34,42');
| |||
color badgeClr = isSafe ? C'52,211,153' : (g_currentStatus == STATUS_PRE_NEWS ? C'251,191,36' : C'248,113,113');
| |||
| |||
if(ObjectFind(0, bgName) < 0)
| |||
{
| |||
if(ObjectCreate(0, bgName, OBJ_RECTANGLE_LABEL, 0, 0, 0))
| |||
{
| |||
ObjectSetInteger(0, bgName, OBJPROP_SELECTABLE, false);
| |||
ObjectSetInteger(0, bgName, OBJPROP_HIDDEN, true);
| |||
ObjectSetInteger(0, bgName, OBJPROP_BACK, false);
| |||
}
| |||
}
| |||
ObjectSetInteger(0, bgName, OBJPROP_CORNER, corner);
| |||
ObjectSetInteger(0, bgName, OBJPROP_XDISTANCE, boxX);
| |||
ObjectSetInteger(0, bgName, OBJPROP_YDISTANCE, boxY);
| |||
ObjectSetInteger(0, bgName, OBJPROP_XSIZE, cardW);
| |||
ObjectSetInteger(0, bgName, OBJPROP_YSIZE, cardH);
| |||
ObjectSetInteger(0, bgName, OBJPROP_BGCOLOR, C'11,14,20');
| |||
ObjectSetInteger(0, bgName, OBJPROP_BORDER_TYPE, BORDER_FLAT);
| |||
ObjectSetInteger(0, bgName, OBJPROP_COLOR, borderClr);
| |||
ObjectSetInteger(0, bgName, OBJPROP_WIDTH, 1);
| |||
| |||
if(ObjectFind(0, accentName) < 0)
| |||
{
| |||
if(ObjectCreate(0, accentName, OBJ_RECTANGLE_LABEL, 0, 0, 0))
| |||
{
| |||
ObjectSetInteger(0, accentName, OBJPROP_SELECTABLE, false);
| |||
ObjectSetInteger(0, accentName, OBJPROP_HIDDEN, true);
| |||
ObjectSetInteger(0, accentName, OBJPROP_BACK, false);
| |||
}
| |||
}
| |||
ObjectSetInteger(0, accentName, OBJPROP_CORNER, corner);
| |||
ObjectSetInteger(0, accentName, OBJPROP_XDISTANCE, boxX);
| |||
ObjectSetInteger(0, accentName, OBJPROP_YDISTANCE, boxY);
| |||
ObjectSetInteger(0, accentName, OBJPROP_XSIZE, 4);
| |||
ObjectSetInteger(0, accentName, OBJPROP_YSIZE, cardH);
| |||
ObjectSetInteger(0, accentName, OBJPROP_BGCOLOR, badgeClr);
| |||
ObjectSetInteger(0, accentName, OBJPROP_BORDER_TYPE, BORDER_FLAT);
| |||
ObjectSetInteger(0, accentName, OBJPROP_COLOR, badgeClr);
| |||
| |||
int textX = (corner == CORNER_RIGHT_UPPER || corner == CORNER_RIGHT_LOWER) ? (boxX - 12) : (boxX + 12);
| |||
int topY = (corner == CORNER_LEFT_LOWER || corner == CORNER_RIGHT_LOWER) ? (boxY - 10) : (boxY + 10);
| |||
int stepY = (corner == CORNER_LEFT_LOWER || corner == CORNER_RIGHT_LOWER) ? -21 : 21;
| |||
| |||
string titleLine = _Symbol + " | " + (isSafe ? "PROP SAFE - CLEAR" : "VETO - DO NOT ENTER");
| |||
long curSpr = SymbolInfoInteger(_Symbol, SYMBOL_SPREAD);
| |||
string sprLine = "Spread: " + IntegerToString((int)curSpr) + " pts (EMA " + DoubleToString(g_emaSpreadPts, 1) +
| |||
(InpMaxSpreadPoints > 0 ? " / Max " + IntegerToString(InpMaxSpreadPoints) : "") + ")";
| |||
string catLine = "Next: " + g_nextEventLabel;
| |||
string sweepLine = "Pending Guard: " + (InpSweepPendingOnVeto ? "ARMED" : "MONITOR") +
| |||
" | Swept: " + IntegerToString((int)g_sweptOrdersCount);
| |||
| |||
UpsertHudLabel(HUD_PREFIX + "L1", corner, textX, topY, titleLine, badgeClr, 9, true);
| |||
UpsertHudLabel(HUD_PREFIX + "L2", corner, textX, topY + stepY, g_statusDetail, C'226,232,240', 8, false);
| |||
UpsertHudLabel(HUD_PREFIX + "L3", corner, textX, topY + stepY * 2, sprLine, C'148,163,184', 8, false);
| |||
UpsertHudLabel(HUD_PREFIX + "L4", corner, textX, topY + stepY * 3, (isSafe ? catLine : sweepLine), C'148,163,184', 8, false);
| |||
| |||
ChartRedraw(0);
| |||
}
| |||
| |||
//+------------------------------------------------------------------+
| |||
//| Remove All HUD Objects Created by This EA |
| |||
//+------------------------------------------------------------------+
| |||
void CleanupHudObjects()
| |||
{
| |||
ObjectsDeleteAll(0, HUD_PREFIX);
| |||
ChartRedraw(0);
| |||
}
| |||
| |||
//+------------------------------------------------------------------+
| |||
//| Core Execution Cycle |
| |||
//+------------------------------------------------------------------+
| |||
void RunGuardCycle()
| |||
{
| |||
EvaluateGuardState();
| |||
PublishRamBridge();
| |||
SweepPendingOrdersIfRequired();
| |||
| |||
if(g_currentStatus != g_previousStatus)
| |||
{
| |||
if(InpSendPushNotifications && g_currentStatus != STATUS_SAFE_CLEAR && !(bool)MQLInfoInteger(MQL_TESTER))
| |||
SendNotification("PropNewsSpreadGuard [" + _Symbol + "]: " + g_statusDetail);
| |||
g_previousStatus = g_currentStatus;
| |||
}
| |||
| |||
RenderHudPanel();
| |||
}
| |||
| |||
//+------------------------------------------------------------------+
| |||
//| Expert initialization function |
| |||
//+------------------------------------------------------------------+
| |||
int OnInit()
| |||
{
| |||
if(InpPreNewsMinutes < 0 || InpPostNewsMinutes < 0)
| |||
{
| |||
Print("PropNewsSpreadGuard: Pre/Post news minutes must be non-negative.");
| |||
return INIT_PARAMETERS_INCORRECT;
| |||
}
| |||
| |||
g_lastCalendarCheck = 0;
| |||
EventSetTimer(1);
| |||
RunGuardCycle();
| |||
return INIT_SUCCEEDED;
| |||
}
| |||
| |||
//+------------------------------------------------------------------+
| |||
//| Expert deinitialization function |
| |||
//+------------------------------------------------------------------+
| |||
void OnDeinit(const int reason)
| |||
{
| |||
EventKillTimer();
| |||
CleanupHudObjects();
| |||
}
| |||
| |||
//+------------------------------------------------------------------+
| |||
//| Timer event handler |
| |||
//+------------------------------------------------------------------+
| |||
void OnTimer()
| |||
{
| |||
RunGuardCycle();
| |||
}
| |||
| |||
//+------------------------------------------------------------------+
| |||
//| Tick event handler |
| |||
//+------------------------------------------------------------------+
| |||
void OnTick()
| |||
{
| |||
RunGuardCycle();
| |||
}
| |||
| |||
//+------------------------------------------------------------------+
| |||
//| TradeTransaction handler (instant intercept for .ex5 orders) |
| |||
//+------------------------------------------------------------------+
| |||
void OnTradeTransaction(const MqlTradeTransaction &trans,
| |||
const MqlTradeRequest &request,
| |||
const MqlTradeResult &result)
| |||
{
| |||
if(trans.type == TRADE_TRANSACTION_ORDER_ADD && InpSweepPendingOnVeto && g_currentStatus != STATUS_SAFE_CLEAR)
| |||
SweepPendingOrdersIfRequired();
| |||
}
| |||
//+------------------------------------------------------------------+
|