| #ifndef TRADE_EXECUTION_MQH
|
| #define TRADE_EXECUTION_MQH
|
|
|
| #include "AISignalConfirmation.mqh"
|
| #include "NNDataLogger.mqh"
|
|
|
| void UpdateLastTradeInfo(const string direction);
|
|
|
| bool IsInCooldown()
|
| {
|
| if(g_reentry_attempt && ReEntry_Bypass_Cooldown)
|
| return false; // re-entries pace themselves with ReEntry_Cooldown
|
| datetime now = TimeCurrent();
|
| return (now - Last_Trade_Time < Trade_Cooldown_Seconds);
|
| }
|
|
|
| // ATR(14) expressed in points, for volatility-scaled stops. 0 if ATR not ready.
|
| double ATRPoints()
|
| {
|
| if(Current_ATR <= 0.0 || _Point <= 0.0) return 0.0;
|
| return Current_ATR / _Point;
|
| }
|
|
|
| int CountOpenTradesForSymbol()
|
| {
|
| int count = 0;
|
| for(int i = PositionsTotal() - 1; i >= 0; --i)
|
| {
|
| ulong ticket = PositionGetTicket(i);
|
| if(ticket == 0 || !PositionSelectByTicket(ticket))
|
| continue;
|
|
|
| if(PositionGetString(POSITION_SYMBOL) == _Symbol && PositionGetInteger(POSITION_MAGIC) == MagicNumber)
|
| count++;
|
| }
|
| return count;
|
| }
|
|
|
| // ── Base gate: cooldown + position cap ──────────────────────────────────────
|
| // News direction checks live in OpenBuy / OpenSell so each side can be gated
|
| // independently (e.g., news is bullish → OpenBuy passes, OpenSell blocked).
|
| bool CanOpenNewTrade()
|
| {
|
| if(!RiskGuardsAllowEntry()) // hours / ADX / daily loss / daily cap (RiskGuards.mqh)
|
| return false;
|
|
|
| if(IsInCooldown())
|
| return false;
|
|
|
| if(CountOpenTradesForSymbol() >= Max_Open_Trades)
|
| return false;
|
|
|
| return true;
|
| }
|
|
|
| // Broker's minimum SL/TP distance in points. SL of a buy is measured against
|
| // Bid while entry is Ask (and vice versa for sells), so the spread has to be
|
| // added on top of SYMBOL_TRADE_STOPS_LEVEL or tight stops still bounce with
|
| // "invalid stops".
|
| int MinStopPoints()
|
| {
|
| int stops_level = (int)SymbolInfoInteger(_Symbol, SYMBOL_TRADE_STOPS_LEVEL);
|
| int spread = (int)SymbolInfoInteger(_Symbol, SYMBOL_SPREAD);
|
| return stops_level + spread + 1;
|
| }
|
|
|
| int GetSLPoints(const bool continuation)
|
| {
|
| int pts;
|
| if(Use_ATR_Exits && ATRPoints() > 0.0)
|
| return MathMax((int)(ATRPoints() * SL_ATR_Mult), MinStopPoints());
|
| if(Symbol_Profile_Initialized)
|
| pts = continuation ? Symbol_SL_Points : MathMax(20, Symbol_SL_Points / 2);
|
| else
|
| pts = continuation ? Continuation_SL_Points : Counter_SL_Points;
|
| return MathMax(pts, MinStopPoints());
|
| }
|
|
|
| int GetTPPoints(const bool continuation)
|
| {
|
| int pts;
|
| if(Use_ATR_Exits && ATRPoints() > 0.0)
|
| return MathMax((int)(ATRPoints() * TP_ATR_Mult), MinStopPoints());
|
| if(Symbol_Profile_Initialized)
|
| pts = continuation ? Symbol_TP_Points : MathMax(80, (int)((double)Symbol_TP_Points * 0.85));
|
| else
|
| pts = continuation ? Continuation_TP_Points : Counter_TP_Points;
|
| return MathMax(pts, MinStopPoints());
|
| }
|
|
|
| double MAT_SizeMult(); // MATheory.mqh
|
|
|
| double BuildLotMultiplier()
|
| {
|
| double mult = 1.0;
|
|
|
| // Under the MA theory size follows the momentum score, not praise counts / War_Survivor.
|
| if(Use_MA_Theory)
|
| {
|
| mult = MAT_SizeMult();
|
| if(Use_Signal_Coordinator) mult *= Coordinator_Lot_Multiplier;
|
| return mult;
|
| }
|
|
|
| if(Active_Praise_Signals >= 4)
|
| mult *= 2.0;
|
| else if(Active_Praise_Signals == 3)
|
| mult *= 1.5;
|
|
|
| if(Active_Warnings >= 3)
|
| mult *= 0.5;
|
|
|
| if(Current_State == STATE_CONTINUATION)
|
| mult *= War_Survivor_Lot_Multiplier;
|
|
|
| if(Use_Signal_Coordinator)
|
| mult *= Coordinator_Lot_Multiplier;
|
|
|
| return mult;
|
| }
|
|
|
| bool OpenBuy(const string reason, double lot_multiplier = 1.0)
|
| {
|
| if(!CanOpenNewTrade())
|
| return false;
|
|
|
| // Trade policy: only setups the trade log shows an edge for (see TradePolicy.mqh)
|
| if(!SetupAllowedByPolicy(reason, true))
|
| return false;
|
| if(EU_Intercept(true, reason)) // v7.31 entry upgrades: watch for a failed break / retest instead
|
| return false;
|
| if(!RG_SideAllowed(true, reason)) // v7.20 stacking guards (RiskGuards.mqh)
|
| return false;
|
| lot_multiplier *= SetupProbationMult(reason); // v7.20 probation (TradePolicy.mqh)
|
| { double cm = SetupConditionMult(reason, true); if(cm <= 0.0) return false; lot_multiplier *= cm; } // v7.29 setup conditions
|
|
|
| // Hard news block (no clear directional bias)
|
| if(News_Trade_Block_Active)
|
| return false;
|
|
|
| // News directional gate — only sell-only sessions block buys
|
| if(News_Trade_Allowed_Direction == -1)
|
| return false;
|
|
|
| bool continuation = (Current_Mode == MODE_TRENDING && Current_State == STATE_CONTINUATION);
|
| double entry = SymbolInfoDouble(_Symbol, SYMBOL_ASK);
|
| int sl_pts = GetSLPoints(continuation);
|
| int tp_pts = GetTPPoints(continuation);
|
| if(g_sl_override_pts > 0) { sl_pts = g_sl_override_pts; tp_pts = g_tp_override_pts; } // v7.31 structure stop (EntryUpgrade)
|
|
|
| // Size and margin-check BEFORE asking the AI: an entry we cannot afford must not cost a gateway
|
| // call per tick (2026-09-17: 240 accepted verdicts in 11 min all died on margin).
|
| double base_mult = lot_multiplier * BuildLotMultiplier();
|
| if(!RiskFitStop(true, entry, sl_pts, tp_pts, reason)) return false; // tighten the stop to the cap if the min lot is too big
|
| double pre_lots = (Lot_Sizing_Mode == LOTS_RISK_PERCENT) ? RiskSizedLots(true, entry, sl_pts, base_mult, reason)
|
| : NormalizeLots(BaseLotSize * base_mult);
|
| if(pre_lots <= 0.0) return false; // RiskSizedLots journaled why
|
| if(FitLotsToMargin(true, pre_lots, entry) <= 0.0)
|
| {
|
| static datetime last_margin_note = 0;
|
| if(TimeCurrent() - last_margin_note >= 60)
|
| {
|
| Print("OpenBuy skipped: free margin ", DoubleToString(AccountInfoDouble(ACCOUNT_MARGIN_FREE), 2),
|
| " cannot cover the minimum lot for ", _Symbol, " (", reason, ")");
|
| last_margin_note = TimeCurrent();
|
| }
|
| return false;
|
| }
|
|
|
| double ai_mult = 1.0;
|
| if(!AIApproveTrade(true, reason, ai_mult))
|
| return false;
|
|
|
| double lots = pre_lots;
|
| if(MathAbs(ai_mult - 1.0) > 0.001)
|
| {
|
| double mult = base_mult * ai_mult;
|
| lots = (Lot_Sizing_Mode == LOTS_RISK_PERCENT) ? RiskSizedLots(true, entry, sl_pts, mult, reason)
|
| : NormalizeLots(BaseLotSize * mult);
|
| if(lots <= 0.0) return false;
|
| }
|
| lots = FitLotsToMargin(true, lots, entry);
|
| if(lots <= 0.0)
|
| {
|
| Print("OpenBuy skipped: free margin cannot cover the minimum lot for ", _Symbol);
|
| return false;
|
| }
|
|
|
| double sl = NormalizePrice(entry - (sl_pts * _Point));
|
| double tp = NormalizePrice(entry + (tp_pts * _Point));
|
|
|
| bool ok = Trade.Buy(lots, _Symbol, 0.0, sl, tp, reason);
|
| if(ok)
|
| {
|
| Last_Trade_Time = TimeCurrent();
|
| UpdateLastTradeInfo("bullish");
|
| TodayTrades++;
|
| BuyTrades++;
|
|
|
| // Capture feature snapshot for NN training (labeled when trade closes via NN_LabelFromDeal)
|
| if(NN_LogData)
|
| {
|
| // Position id = the opening order's ticket; read it from the deal when history
|
| // has it, else from the order (the deal is often not in history yet right here).
|
| ulong d = Trade.ResultDeal();
|
| ulong pos_id = (d > 0 && HistoryDealSelect(d))
|
| ? (ulong)HistoryDealGetInteger(d, DEAL_POSITION_ID) : Trade.ResultOrder();
|
| if(pos_id > 0)
|
| {
|
| int cat = (Current_State == STATE_CONTINUATION) ? 0 : 1;
|
| NN_CaptureEntry(pos_id, true, reason,
|
| Coordinator_Cluster_Strength, Coordinator_Conflict_Score, cat);
|
| }
|
| }
|
| }
|
| return ok;
|
| }
|
|
|
| bool OpenSell(const string reason, double lot_multiplier = 1.0)
|
| {
|
| if(!CanOpenNewTrade())
|
| return false;
|
|
|
| // Trade policy: only setups the trade log shows an edge for (see TradePolicy.mqh)
|
| if(!SetupAllowedByPolicy(reason, false))
|
| return false;
|
| if(EU_Intercept(false, reason)) // v7.31 entry upgrades: watch for a failed break / retest instead
|
| return false;
|
| if(!RG_SideAllowed(false, reason)) // v7.20 stacking guards (RiskGuards.mqh)
|
| return false;
|
| lot_multiplier *= SetupProbationMult(reason); // v7.20 probation (TradePolicy.mqh)
|
| { double cm = SetupConditionMult(reason, false); if(cm <= 0.0) return false; lot_multiplier *= cm; } // v7.29 setup conditions
|
|
|
| // Hard news block (no clear directional bias)
|
| if(News_Trade_Block_Active)
|
| return false;
|
|
|
| // News directional gate — only buy-only sessions block sells
|
| if(News_Trade_Allowed_Direction == 1)
|
| return false;
|
|
|
| bool continuation = (Current_Mode == MODE_TRENDING && Current_State == STATE_CONTINUATION);
|
| double entry = SymbolInfoDouble(_Symbol, SYMBOL_BID);
|
| int sl_pts = GetSLPoints(continuation);
|
| int tp_pts = GetTPPoints(continuation);
|
| if(g_sl_override_pts > 0) { sl_pts = g_sl_override_pts; tp_pts = g_tp_override_pts; } // v7.31 structure stop (EntryUpgrade)
|
|
|
| // Size and margin-check BEFORE asking the AI: an entry we cannot afford must not cost a gateway
|
| // call per tick (2026-09-17: 240 accepted verdicts in 11 min all died on margin).
|
| double base_mult = lot_multiplier * BuildLotMultiplier();
|
| if(!RiskFitStop(false, entry, sl_pts, tp_pts, reason)) return false; // tighten the stop to the cap if the min lot is too big
|
| double pre_lots = (Lot_Sizing_Mode == LOTS_RISK_PERCENT) ? RiskSizedLots(false, entry, sl_pts, base_mult, reason)
|
| : NormalizeLots(BaseLotSize * base_mult);
|
| if(pre_lots <= 0.0) return false; // RiskSizedLots journaled why
|
| if(FitLotsToMargin(false, pre_lots, entry) <= 0.0)
|
| {
|
| static datetime last_margin_note = 0;
|
| if(TimeCurrent() - last_margin_note >= 60)
|
| {
|
| Print("OpenSell skipped: free margin ", DoubleToString(AccountInfoDouble(ACCOUNT_MARGIN_FREE), 2),
|
| " cannot cover the minimum lot for ", _Symbol, " (", reason, ")");
|
| last_margin_note = TimeCurrent();
|
| }
|
| return false;
|
| }
|
|
|
| double ai_mult = 1.0;
|
| if(!AIApproveTrade(false, reason, ai_mult))
|
| return false;
|
|
|
| double lots = pre_lots;
|
| if(MathAbs(ai_mult - 1.0) > 0.001)
|
| {
|
| double mult = base_mult * ai_mult;
|
| lots = (Lot_Sizing_Mode == LOTS_RISK_PERCENT) ? RiskSizedLots(false, entry, sl_pts, mult, reason)
|
| : NormalizeLots(BaseLotSize * mult);
|
| if(lots <= 0.0) return false;
|
| }
|
| lots = FitLotsToMargin(false, lots, entry);
|
| if(lots <= 0.0)
|
| {
|
| Print("OpenSell skipped: free margin cannot cover the minimum lot for ", _Symbol);
|
| return false;
|
| }
|
|
|
| double sl = NormalizePrice(entry + (sl_pts * _Point));
|
| double tp = NormalizePrice(entry - (tp_pts * _Point));
|
|
|
| bool ok = Trade.Sell(lots, _Symbol, 0.0, sl, tp, reason);
|
| if(ok)
|
| {
|
| Last_Trade_Time = TimeCurrent();
|
| UpdateLastTradeInfo("bearish");
|
| TodayTrades++;
|
| SellTrades++;
|
|
|
| // Capture feature snapshot for NN training (labeled when trade closes via NN_LabelFromDeal)
|
| if(NN_LogData)
|
| {
|
| // Position id = the opening order's ticket; read it from the deal when history
|
| // has it, else from the order (the deal is often not in history yet right here).
|
| ulong d = Trade.ResultDeal();
|
| ulong pos_id = (d > 0 && HistoryDealSelect(d))
|
| ? (ulong)HistoryDealGetInteger(d, DEAL_POSITION_ID) : Trade.ResultOrder();
|
| if(pos_id > 0)
|
| {
|
| int cat = (Current_State == STATE_CONTINUATION) ? 0 : 1;
|
| NN_CaptureEntry(pos_id, false, reason,
|
| Coordinator_Cluster_Strength, Coordinator_Conflict_Score, cat);
|
| }
|
| }
|
| }
|
| return ok;
|
| }
|
|
|
| #endif
|