Vizion-Trading-EA/RiskGuards.mqh
250 lines
10 KiB
MQL5
#ifndef RISK_GUARDS_MQH
#define RISK_GUARDS_MQH
// ---------------------------------------------------------------------------
// RiskGuards.mqh — account-level entry guards (2026-09-16)
//
// Derived from the EA's own trade log (246 position-matched trades):
// - 2026-03-02 alone was -603 (the EA is +278 without it): no daily loss limit existed.
// - server hours 04-05: 18 trades, 0 wins, -475.
// - ADX top third (> ~33): 82 trades, 22% win, -360 — the EA loses chasing strong trends.
// - 99 trades on 07-15, 68 on 08-18: no cap on trades per day.
// All guards are inputs; 0 / empty disables a guard. Each block is journaled once per reason.
// ---------------------------------------------------------------------------
bool RG_HourBlocked(const int hour)
{
if(StringLen(Blocked_Entry_Hours) == 0) return false;
string parts[];
int n = StringSplit(Blocked_Entry_Hours, ',', parts);
for(int i = 0; i < n; ++i)
{
string p = parts[i]; StringTrimLeft(p); StringTrimRight(p);
if(StringLen(p) > 0 && (int)StringToInteger(p) == hour) return true;
}
return false;
}
// Today's closed P/L and today's opened-trade count for this EA (magic), account-wide.
void RG_TodayStats(double &closed_pnl, int &opened_count)
{
closed_pnl = 0.0; opened_count = 0;
MqlDateTime dt; TimeToStruct(TimeCurrent(), dt);
dt.hour = 0; dt.min = 0; dt.sec = 0;
datetime day_start = StructToTime(dt);
if(!HistorySelect(day_start, TimeCurrent())) return;
int total = HistoryDealsTotal();
for(int i = 0; i < total; ++i)
{
ulong t = HistoryDealGetTicket(i);
if(t == 0) continue;
if(HistoryDealGetInteger(t, DEAL_MAGIC) != MagicNumber) continue;
long entry = HistoryDealGetInteger(t, DEAL_ENTRY);
if(entry == DEAL_ENTRY_IN) opened_count++;
if(entry == DEAL_ENTRY_OUT || entry == DEAL_ENTRY_INOUT)
closed_pnl += HistoryDealGetDouble(t, DEAL_PROFIT) + HistoryDealGetDouble(t, DEAL_SWAP) + HistoryDealGetDouble(t, DEAL_COMMISSION);
}
}
datetime RG_ServerDayStart()
{
MqlDateTime dt; TimeToStruct(TimeCurrent(), dt);
dt.hour = 0; dt.min = 0; dt.sec = 0;
return StructToTime(dt);
}
// v7.22: account balance at the start of the server day = balance now minus every deal booked today
// (all EAs, manual trades, deposits). The daily loss limit is a % of this, so it does not shrink as the day loses.
double RG_DayStartBalance()
{
double bal = AccountInfoDouble(ACCOUNT_BALANCE);
if(!HistorySelect(RG_ServerDayStart(), TimeCurrent())) return bal;
double today = 0.0;
int total = HistoryDealsTotal();
for(int i = 0; i < total; ++i)
{
ulong t = HistoryDealGetTicket(i);
if(t == 0) continue;
today += HistoryDealGetDouble(t, DEAL_PROFIT) + HistoryDealGetDouble(t, DEAL_SWAP) + HistoryDealGetDouble(t, DEAL_COMMISSION);
}
return bal - today;
}
// v7.22: once the daily loss limit is hit it stays hit until the next server day, on every chart and
// across restarts (terminal global VZ_DAILY_LOSS_DAY = the day it was hit). Before this, open trades
// bouncing around the limit paused and resumed entries ~10 times in 3 minutes (2026-11-09 03:10).
bool RG_DailyLossLatched()
{
return GlobalVariableCheck("VZ_DAILY_LOSS_DAY") && (datetime)GlobalVariableGet("VZ_DAILY_LOSS_DAY") == RG_ServerDayStart();
}
void RG_LatchDailyLoss() { GlobalVariableSet("VZ_DAILY_LOSS_DAY", (double)RG_ServerDayStart()); }
// Manual pause switch (2026-09-17): terminal global variables, so a hotkey script (VZ_TogglePause)
// or Magic Keys on a sister chart can stop new entries without touching the EA inputs.
// VZ_PAUSE_ALL = 1 -> no entries on any chart running this EA
// VZ_PAUSE_<SYMBOL> = 1 -> no entries for that symbol only
// Open positions keep being managed (BE, trail, exits); only entries and re-entries stop.
bool RG_ManualPause(string &scope)
{
scope = "";
if(GlobalVariableCheck("VZ_PAUSE_ALL") && GlobalVariableGet("VZ_PAUSE_ALL") > 0.0)
{ scope = "VZ_PAUSE_ALL"; return true; }
string key = "VZ_PAUSE_" + _Symbol;
if(GlobalVariableCheck(key) && GlobalVariableGet(key) > 0.0)
{ scope = key; return true; }
return false;
}
// Symbol allowlist (2026-09-17): a chart whose symbol is not listed never opens trades.
bool RG_SymbolAllowed()
{
if(StringLen(Trade_Symbols_Fixed) == 0) return true;
string parts[];
int n = StringSplit(Trade_Symbols_Fixed, ',', parts);
for(int i = 0; i < n; ++i)
{
string p = parts[i]; StringTrimLeft(p); StringTrimRight(p);
if(StringLen(p) > 0 && StringCompare(p, _Symbol, false) == 0) return true;
}
return false;
}
// Minimum trading timeframe for this chart: the global input, or a per-symbol override.
ENUM_TIMEFRAMES RG_TFFromString(const string s)
{
if(s == "M1") return PERIOD_M1;
if(s == "M5") return PERIOD_M5;
if(s == "M15") return PERIOD_M15;
if(s == "M30") return PERIOD_M30;
if(s == "H1") return PERIOD_H1;
if(s == "H4") return PERIOD_H4;
if(s == "D1") return PERIOD_D1;
return PERIOD_CURRENT;
}
ENUM_TIMEFRAMES RG_MinTimeframe()
{
ENUM_TIMEFRAMES tf = Min_Trade_Timeframe;
if(StringLen(Symbol_Min_TF_Overrides) > 0)
{
string parts[];
int n = StringSplit(Symbol_Min_TF_Overrides, ',', parts);
for(int i = 0; i < n; ++i)
{
string p = parts[i]; StringTrimLeft(p); StringTrimRight(p);
int c = StringFind(p, ":");
if(c <= 0) continue;
string sym = StringSubstr(p, 0, c); StringTrimRight(sym);
string tfs = StringSubstr(p, c + 1); StringTrimLeft(tfs);
if(StringCompare(sym, _Symbol, false) == 0)
{
ENUM_TIMEFRAMES o = RG_TFFromString(tfs);
if(o != PERIOD_CURRENT) tf = o;
}
}
}
return tf;
}
// Open P/L of this EA's positions, account-wide (v7.20: the daily loss limit counts it too).
double RG_FloatingPnl()
{
double sum = 0.0;
for(int i = PositionsTotal() - 1; i >= 0; --i)
{
ulong t = PositionGetTicket(i);
if(t == 0 || !PositionSelectByTicket(t)) continue;
if(PositionGetInteger(POSITION_MAGIC) != MagicNumber) continue;
sum += PositionGetDouble(POSITION_PROFIT) + PositionGetDouble(POSITION_SWAP);
}
return sum;
}
// v7.20 stacking guards: may this symbol take one more position in this direction?
// Counts every setup on this symbol and side. Blocks at Max_Same_Side_Positions, and while the side
// is down more than No_Add_Side_Loss_Pct of equity (no adding to a losing side).
bool RG_SideAllowed(const bool is_buy, const string setup)
{
int n = 0; double floating = 0.0;
long side = is_buy ? POSITION_TYPE_BUY : POSITION_TYPE_SELL;
for(int i = PositionsTotal() - 1; i >= 0; --i)
{
ulong t = PositionGetTicket(i);
if(t == 0 || !PositionSelectByTicket(t)) continue;
if(PositionGetString(POSITION_SYMBOL) != _Symbol || PositionGetInteger(POSITION_MAGIC) != MagicNumber) continue;
if(PositionGetInteger(POSITION_TYPE) != side) continue;
n++;
floating += PositionGetDouble(POSITION_PROFIT) + PositionGetDouble(POSITION_SWAP);
}
string why = "";
if(Max_Same_Side_Positions > 0 && n >= Max_Same_Side_Positions)
why = IntegerToString(n) + " " + (is_buy ? "BUY" : "SELL") + " positions open (max " + IntegerToString(Max_Same_Side_Positions) + ")";
else if(No_Add_Side_Loss_Pct > 0.0 && n > 0)
{
double limit = AccountInfoDouble(ACCOUNT_EQUITY) * No_Add_Side_Loss_Pct / 100.0;
if(floating < -limit)
why = (is_buy ? "BUY" : "SELL") + " side down " + DoubleToString(floating, 2) + " (> " + DoubleToString(No_Add_Side_Loss_Pct, 1) + "% of equity) - not adding to a losing side";
}
if(StringLen(why) == 0) return true;
static datetime last_note = 0; static string last_why = "";
if(why != last_why || TimeCurrent() - last_note >= 60)
{
Print("RiskGuards: ", setup, " skipped - ", why);
last_note = TimeCurrent(); last_why = why;
}
return false;
}
bool RiskGuardsAllowEntry()
{
static string last_reason = "";
string reason = "";
ENUM_TIMEFRAMES min_tf = RG_MinTimeframe();
if(min_tf != PERIOD_CURRENT && Period() < min_tf)
reason = EnumToString((ENUM_TIMEFRAMES)Period()) + " is below the minimum trading timeframe " + EnumToString(min_tf) + " for " + _Symbol;
if(StringLen(reason) == 0 && !RG_SymbolAllowed())
reason = _Symbol + " not in Trade_Symbols_Fixed (" + Trade_Symbols_Fixed + ")";
if(StringLen(reason) == 0 && Use_Watchlist_Rotation && !IsSymbolActiveTrading(_Symbol))
reason = _Symbol + " is not in the active top-10 watchlist rotation (manage-only)";
string pause_scope = "";
if(StringLen(reason) == 0 && RG_ManualPause(pause_scope))
reason = "manual pause (" + pause_scope + " set; run VZ_TogglePause to resume)";
MqlDateTime dt; TimeToStruct(TimeCurrent(), dt);
if(StringLen(reason) == 0 && RG_HourBlocked(dt.hour))
reason = "blocked hour " + IntegerToString(dt.hour) + " (server time)";
if(StringLen(reason) == 0 && Max_ADX_To_Trade > 0.0 && Current_ADX > Max_ADX_To_Trade)
reason = "ADX " + DoubleToString(Current_ADX, 1) + " > " + DoubleToString(Max_ADX_To_Trade, 1) + " (trend too strong to chase)";
if(StringLen(reason) == 0 && (Daily_Loss_Limit_Pct > 0.0 || Max_Trades_Per_Day > 0))
{
double pnl; int opened;
RG_TodayStats(pnl, opened);
string incl = "";
if(Daily_Loss_Include_Floating) { pnl += RG_FloatingPnl(); incl = " incl. open"; }
double start_bal = RG_DayStartBalance();
double limit = start_bal * Daily_Loss_Limit_Pct / 100.0;
bool latched = RG_DailyLossLatched();
if(Daily_Loss_Limit_Pct > 0.0 && (latched || pnl <= -limit))
{
if(!latched) RG_LatchDailyLoss();
reason = "daily loss limit hit (" + DoubleToString(pnl, 2) + incl + " <= -" + DoubleToString(limit, 2) +
" = " + DoubleToString(Daily_Loss_Limit_Pct, 1) + "% of start-of-day balance " + DoubleToString(start_bal, 2) +
") - paused until the next server day";
}
else if(Max_Trades_Per_Day > 0 && opened >= Max_Trades_Per_Day)
reason = "daily trade cap reached (" + IntegerToString(opened) + "/" + IntegerToString(Max_Trades_Per_Day) + ")";
}
if(StringLen(reason) > 0)
{
if(reason != last_reason) { Print("RiskGuards: entries paused - ", reason); last_reason = reason; }
return false;
}
if(StringLen(last_reason) > 0) { Print("RiskGuards: entries resumed"); last_reason = ""; }
return true;
}
#endif