Vigiar
1
2
Derivar
Você já tinha feito uma derivação do repositório Vizion-Trading-EA, anteriormente
2
Vizion-Trading-EA/PositionManagement.mqh
#ifndef POSITION_MANAGEMENT_MQH
#define POSITION_MANAGEMENT_MQH
void QueueReEntryCandidate(const bool is_buy, const string reason);
// v7.25: initial risk (price distance entry -> initial stop) of an open position, cached per position.
// Source: the opening order's SL; fallback: the current SL if it is still on the loss side; last resort ATR.
double PM_InitialRisk(const ulong ticket, const bool is_buy, const double entry, const double cur_sl)
{
static ulong keys[256];
static double vals[256];
static int next = 0;
for(int i = 0; i < 256; ++i) if(keys[i] == ticket && vals[i] > 0.0) return vals[i];
double r = 0.0;
long ident = PositionGetInteger(POSITION_IDENTIFIER);
if(HistoryOrderSelect((ulong)ident))
{
double osl = HistoryOrderGetDouble((ulong)ident, ORDER_SL);
if(osl > 0.0) r = MathAbs(entry - osl);
}
if(r <= 0.0 && cur_sl > 0.0 && ((is_buy && cur_sl < entry) || (!is_buy && cur_sl > entry))) r = MathAbs(entry - cur_sl);
if(r <= 0.0) r = Current_ATR * SL_ATR_Mult;
keys[next] = ticket; vals[next] = r; next = (next + 1) % 256;
return r;
}
// v7.25 R-based break-even and trailing. Returns true when it handled the position.
bool PM_ManageR(const ulong ticket, const bool is_buy, const double entry, const double sl, const double tp, const double bid, const double ask)
{
if(!Use_R_Exits) return false;
double R = PM_InitialRisk(ticket, is_buy, entry, sl);
if(R <= 0.0) return false;
double profit = is_buy ? (bid - entry) : (entry - ask);
double target = sl;
if(profit >= BE_Trigger_R * R)
target = is_buy ? MathMax(target, entry) : (target == 0.0 ? entry : MathMin(target, entry));
if(profit >= Trail_Start_R * R)
{
double t = is_buy ? (bid - Trail_Distance_R * R) : (ask + Trail_Distance_R * R);
target = is_buy ? MathMax(target, t) : (target == 0.0 ? t : MathMin(target, t));
}
if(target == sl) return true;
bool better = is_buy ? (sl == 0.0 || target - sl >= Trail_Min_Step_R * R || (sl < entry && target >= entry))
: (sl == 0.0 || sl - target >= Trail_Min_Step_R * R || (sl > entry && target <= entry));
if(!better) return true;
// respect the broker's minimum stop distance
double min_dist = MinStopPoints() * _Point;
if(is_buy && bid - target < min_dist) return true;
if(!is_buy && target - ask < min_dist) return true;
if(Trade.PositionModify(ticket, NormalizePrice(target), tp))
Print("Exit: #", ticket, " stop -> ", DoubleToString(target, _Digits), " (", DoubleToString(profit / R, 2), "R in profit; ",
(profit >= Trail_Start_R * R ? "trailing " + DoubleToString(Trail_Distance_R, 1) + "R" : "break-even"), ")");
return true;
}
void ManagePositions()
{
double bid = SymbolInfoDouble(_Symbol, SYMBOL_BID);
double ask = SymbolInfoDouble(_Symbol, SYMBOL_ASK);
static ulong prev_tickets[64];
static bool prev_is_buy[64];
static int prev_count = 0;
ulong cur_tickets[64];
int cur_count = 0;
for(int i = PositionsTotal() - 1; i >= 0; --i)
{
ulong ticket = PositionGetTicket(i);
if(ticket == 0 || !PositionSelectByTicket(ticket))
continue;
if(PositionGetInteger(POSITION_MAGIC) != MagicNumber) continue;
if(PositionGetString(POSITION_SYMBOL) != _Symbol) continue;
bool is_buy = (PositionGetInteger(POSITION_TYPE) == POSITION_TYPE_BUY);
double entry = PositionGetDouble(POSITION_PRICE_OPEN);
double sl = PositionGetDouble(POSITION_SL);
double tp = PositionGetDouble(POSITION_TP);
if(cur_count < 64)
{
cur_tickets[cur_count] = ticket;
cur_count++;
}
if(PM_ManageR(ticket, is_buy, entry, sl, tp, bid, ask)) continue; // v7.25 R-based exits
double profit_points = is_buy ? ((bid - entry) / _Point) : ((entry - ask) / _Point);
// Volatility-scaled exits (2026-09-16): BE trigger and trail distance as ATR multiples.
double atr_pts = (Use_ATR_Exits && Current_ATR > 0.0) ? Current_ATR / _Point : 0.0;
double be_trigger = (atr_pts > 0.0) ? atr_pts * BE_Trigger_ATR : (double)BE_Trigger_Points;
if(profit_points >= be_trigger)
{
double be_sl = entry;
if((is_buy && (sl < be_sl || sl == 0.0)) || (!is_buy && (sl > be_sl || sl == 0.0)))
Trade.PositionModify(ticket, NormalizePrice(be_sl), tp);
}
int trail = Trail_Counter_Points;
if(Current_State == STATE_CONTINUATION)
trail = Trail_Continuation_Points;
if(Active_Praise_Signals >= 4)
trail = Trail_Supreme_Points;
if(atr_pts > 0.0)
{
double m = Trail_ATR_Counter;
if(Current_State == STATE_CONTINUATION) m = Trail_ATR_Continuation;
if(Active_Praise_Signals >= 4) m = Trail_ATR_Supreme;
trail = MathMax((int)(atr_pts * m), MinStopPoints());
}
if(profit_points > trail)
{
double new_sl = is_buy ? (bid - trail * _Point) : (ask + trail * _Point);
new_sl = NormalizePrice(new_sl);
if((is_buy && new_sl > sl) || (!is_buy && (sl == 0.0 || new_sl < sl)))
Trade.PositionModify(ticket, new_sl, tp);
}
}
// Detect recently closed positions for re-entry candidates.
for(int p = 0; p < prev_count; ++p)
{
bool still_open = false;
for(int c = 0; c < cur_count; ++c)
{
if(prev_tickets[p] == cur_tickets[c])
{
still_open = true;
break;
}
}
if(!still_open && Enable_ReEntry)
{
// Who closed it? A human (or another tool such as Magic Keys on a sister chart) closing a
// position must not trigger a re-entry; only our own SL/TP/expert exits should (2026-09-17).
// Only OUR stop / target / stop-out earns a re-entry. Anything else — you, Magic Keys
// (DEAL_REASON_EXPERT), mobile, web — is a manual exit. A position that was itself a
// re-entry does not spawn another, so a TP cannot start a chain (2026-09-17).
bool our_exit = false; long reason = -1; bool was_reentry = false; string base_setup = ""; double parent_pnl = 0.0;
if(HistorySelectByPosition(prev_tickets[p]))
{
for(int d = HistoryDealsTotal() - 1; d >= 0; --d)
{
ulong dt = HistoryDealGetTicket(d);
if(dt == 0) continue;
long en = HistoryDealGetInteger(dt, DEAL_ENTRY);
if(en == DEAL_ENTRY_IN)
{
string cmt = HistoryDealGetString(dt, DEAL_COMMENT);
if(StringFind(cmt, "RE-ENTRY") == 0)
{
was_reentry = true;
int bar = StringFind(cmt, " | ");
base_setup = (bar >= 0) ? StringSubstr(cmt, bar + 3) : "";
}
else base_setup = cmt;
continue;
}
if(en != DEAL_ENTRY_OUT && en != DEAL_ENTRY_INOUT) continue;
parent_pnl += HistoryDealGetDouble(dt, DEAL_PROFIT) + HistoryDealGetDouble(dt, DEAL_SWAP) + HistoryDealGetDouble(dt, DEAL_COMMISSION);
if(reason < 0)
{
reason = HistoryDealGetInteger(dt, DEAL_REASON);
our_exit = (reason == DEAL_REASON_SL || reason == DEAL_REASON_TP || reason == DEAL_REASON_SO);
}
}
}
bool manual_close = (reason == DEAL_REASON_CLIENT || reason == DEAL_REASON_MOBILE || reason == DEAL_REASON_WEB);
if(manual_close)
Print("ReEntry: position #", prev_tickets[p], " closed manually - re-entry suppressed");
else if(ReEntry_Only_After_Own_Exit && !our_exit)
Print("ReEntry: position #", prev_tickets[p], " closed externally (reason ", reason, ") - re-entry suppressed");
else if(ReEntry_No_Chains && was_reentry)
Print("ReEntry: position #", prev_tickets[p], " was a re-entry - no chained re-entry");
else if(ReEntry_Require_Parent_Win && parent_pnl < -ReEntry_BE_Tolerance)
Print("ReEntry: position #", prev_tickets[p], " closed at ", DoubleToString(parent_pnl, 2),
" - not armed (v7.20: re-entries after a losing parent won 4%, after a winning one 87%)");
else if(ReEntry_Require_Setup)
{
// arm the original setup; it re-enters only if the setup engine fires it again
if(StringLen(base_setup) == 0 || StringFind(base_setup, "POST-") == 0)
Print("ReEntry: position #", prev_tickets[p], " has no setup name - not armed");
else
{
QueueReEntryCandidate(prev_is_buy[p], base_setup);
Print("ReEntry: armed ", base_setup, " ", prev_is_buy[p] ? "BUY" : "SELL", " - re-enters only if the setup fires again");
}
}
else
{
string why = (reason == DEAL_REASON_TP) ? "POST-TP VALIDATION" : "POST-CLOSE VALIDATION";
QueueReEntryCandidate(prev_is_buy[p], why);
}
}
}
prev_count = 0;
for(int c2 = 0; c2 < cur_count && c2 < 64; ++c2)
{
if(PositionSelectByTicket(cur_tickets[c2]))
{
prev_tickets[prev_count] = cur_tickets[c2];
prev_is_buy[prev_count] = (PositionGetInteger(POSITION_TYPE) == POSITION_TYPE_BUY);
prev_count++;
}
}
}
#endif