//+------------------------------------------------------------------+ //| UniversalTradeCopier.mq5 | //| Murari Kumar Jha | //+------------------------------------------------------------------+ #property copyright "Murari Kumar Jha" #property link "https://www.mql5.com" #property version "6.10" #property strict #include //--- Enumerations enum ENUM_COPIER_ROLE { ROLE_MASTER = 0, // Master Transmitter ROLE_SLAVE = 1 // Slave Receiver }; //--- Input Parameters input group "=== Operation Mode ===" input ENUM_COPIER_ROLE InpCopierRole = ROLE_SLAVE; // Role for this Terminal Instance input string InpBridgeFileName = "MasterMultiSlaveQueue.txt"; // Shared Queue File (Common/Files) input group "=== Master Transmitter Settings ===" input ulong InpMasterMagic = 100200; // Master Magic Number input bool InpMasterBEPartial = true; // Master: Enable 25-pip BE + 50% Partial Close input double InpMasterBETrigger = 25.0; // Master: Pips in profit for BE/Partial input bool InpMasterTrailing = true; // Master: Enable Trailing Stop input double InpMasterTrailDist = 15.0; // Master: Trailing Distance in Pips input double InpMasterTrailStep = 5.0; // Master: Trailing Step in Pips input bool InpMasterTargetClose = true; // Master: Auto-Close & Broadcast at +1.2% Gain input double InpMasterTargetPct = 1.2; // Master: Daily Gain Target % input group "=== Slave Receiver Settings ===" input ulong InpSlaveMagic = 200201; // Slave Magic Number (Unique per Slave) input int InpMaxDeviationPips = 5; // Slave: Max Allowed Price Drift (Pips) input int InpMaxDelaySec = 18; // Slave: Max Signal Age Threshold (Seconds) input double InpMaxSpreadPips = 0.0; // Slave: Max Spread Filter in Pips (0.0 = Disabled) input double InpMaxDailyLossPct = 1.8; // Slave: Cumulative Daily Loss Limit % input double InpMaxDailyProfitPct = 1.2; // Slave: Cumulative Daily Profit Target % (Lockout) input double InpRiskPerTradePct = 0.7; // Slave: Dynamic Risk Per Trade % input double InpMaxLotsPer10k = 1.0; // Prop Guard: Max Lots per $10k Balance (1.0 = 10.0 lots on 100k) input double InpMinSLPips = 5.0; // Prop Guard: Minimum SL distance floor in pips input double InpSlaveBETrigger = 25.0; // Slave: Pips in profit for BE/Partial input double InpSlaveTrailDist = 15.0; // Slave: Trailing Distance in Pips input double InpSlaveTrailStep = 5.0; // Slave: Trailing Step in Pips input group "=== Symbol Mapping (Slave Only) ===" input string InpSlavePrefix = ""; // Slave Broker Prefix (e.g., "m.") input string InpSlaveSuffix = ""; // Slave Broker Suffix (e.g., ".pro", "m") input string InpCustomMapPairs = "GOLD:XAUUSD,US30:DJ30"; // Manual overrides (MASTER:SLAVE) input group "=== Notifications & Alerts ===" input bool InpEnableTelegram = false; // Enable Telegram Alerts input string InpBotToken = ""; // Telegram Bot Token input string InpChatID = ""; // Telegram Chat ID input bool InpEnableSoundAlert = true; // Enable Desktop Sound & Modal Popups input string InpAlertSoundFile = "alert2.wav"; // Alert Sound File in MT5/Sounds/ //--- Global Variables CTrade m_trade; double g_dayStartBalance = 0.0; double g_initialEquity = 0.0; bool g_dailyTargetHit = false; bool g_dailyLossLimitHit = false; bool g_masterTargetHit = false; datetime g_lastPruneTime = 0; #define EPSILON 0.0000001 //+------------------------------------------------------------------+ //| Helper: Normalize Pips to Points with Zero-Check | //+------------------------------------------------------------------+ double PipsToPoints(string sym, double pips) { double point = SymbolInfoDouble(sym, SYMBOL_POINT); if(point <= EPSILON) point = 0.0001; int digits = (int)SymbolInfoInteger(sym, SYMBOL_DIGITS); double mult = (digits == 3 || digits == 5) ? 10.0 : 1.0; return pips * mult * point; } //+------------------------------------------------------------------+ //| Helper: Dynamic Broker Supported Filling Mode | //+------------------------------------------------------------------+ void ApplySupportedFillingMode(string sym) { uint filling = (uint)SymbolInfoInteger(sym, SYMBOL_FILLING_MODE); if((filling & SYMBOL_FILLING_IOC) != 0) m_trade.SetTypeFilling(ORDER_FILLING_IOC); else if((filling & SYMBOL_FILLING_FOK) != 0) m_trade.SetTypeFilling(ORDER_FILLING_FOK); else m_trade.SetTypeFilling(ORDER_FILLING_RETURN); } //+------------------------------------------------------------------+ //| Symbol Mapping Logic | //+------------------------------------------------------------------+ string ResolveSymbol(string masterSymbol) { if(StringLen(InpCustomMapPairs) > 0) { string pairs[]; int total = StringSplit(InpCustomMapPairs, ',', pairs); for(int i = 0; i < total; i++) { string mapping[]; if(StringSplit(pairs[i], ':', mapping) == 2) { StringTrimLeft(mapping[0]); StringTrimRight(mapping[0]); StringTrimLeft(mapping[1]); StringTrimRight(mapping[1]); if(StringCompare(masterSymbol, mapping[0], false) == 0) { SymbolSelect(mapping[1], true); return mapping[1]; } } } } string resolved = InpSlavePrefix + masterSymbol + InpSlaveSuffix; if(SymbolSelect(resolved, true)) return resolved; if(SymbolSelect(masterSymbol, true)) return masterSymbol; return ""; } //+------------------------------------------------------------------+ //| Telegram Notification Sender (Market Validator Safe) | //+------------------------------------------------------------------+ void SendTelegramMessage(string text) { if(MQLInfoInteger(MQL_TESTER)) return; if(!InpEnableTelegram || StringLen(InpBotToken) == 0 || StringLen(InpChatID) == 0) return; string url = "https://api.telegram.org/bot" + InpBotToken + "/sendMessage"; string payload = "chat_id=" + InpChatID + "&text=" + text; char data[]; StringToCharArray(payload, data, 0, WHOLE_ARRAY, CP_UTF8); ArrayResize(data, ArraySize(data) - 1); char result[]; string resultHeaders; string headers = "Content-Type: application/x-www-form-urlencoded\r\n"; WebRequest("POST", url, headers, 3000, data, result, resultHeaders); } //+------------------------------------------------------------------+ //| Unified Rejection Alert Router | //+------------------------------------------------------------------+ void TriggerRejectionAlert(string reason, string details) { string formattedText = StringFormat("[REJECT ALERT] %s: %s", reason, details); Print(formattedText); if(!MQLInfoInteger(MQL_TESTER) && InpEnableSoundAlert) { Alert(formattedText); PlaySound(InpAlertSoundFile); } if(InpEnableTelegram) { string tgMsg = StringFormat("⚠️ *TRADE REJECTED*\nAccount: %I64u\nReason: %s\nDetails: %s", AccountInfoInteger(ACCOUNT_LOGIN), reason, details); SendTelegramMessage(tgMsg); } } //+------------------------------------------------------------------+ //| One-Time Daily Limit Alert (Fires exactly ONCE per session day) | //+------------------------------------------------------------------+ void SendOneTimeDailyLimitAlert(string limitType, double reachedPct, double thresholdPct) { string dateStr = TimeToString(TimeCurrent(), TIME_DATE); string alertMarker = StringFormat("SLAVE_ALERTED_%s_%I64d_%s", limitType, AccountInfoInteger(ACCOUNT_LOGIN), dateStr); if(GlobalVariableCheck(alertMarker)) return; GlobalVariableSet(alertMarker, 1.0); string title = (limitType == "TARGET") ? "🎯 DAILY TARGET ACHIEVED" : "🚨 DAILY DRAWDOWN LIMIT HIT"; string details = (limitType == "TARGET") ? StringFormat("Account hit +%.2f%% gain (Target: +%.1f%%). All trades liquidated. New entries LOCKED until midnight.", reachedPct, thresholdPct) : StringFormat("Account reached -%.2f%% loss (Cap: -%.1f%%). All trades liquidated. New entries LOCKED until midnight.", reachedPct, thresholdPct); PrintFormat("[%s] %s", title, details); if(!MQLInfoInteger(MQL_TESTER) && InpEnableSoundAlert) { Alert(title + " | " + details); PlaySound(InpAlertSoundFile); } if(InpEnableTelegram) { string tgMsg = StringFormat("%s\nAccount: %I64d\nStatus: %s", title, AccountInfoInteger(ACCOUNT_LOGIN), details); SendTelegramMessage(tgMsg); } } //+------------------------------------------------------------------+ //| Session & ATR Engine | //+------------------------------------------------------------------+ void CalculateSessionATR(string sym, double &slPips, double &tpPips) { MqlDateTime dt; TimeGMT(dt); int hour = dt.hour; double multSL = 1.5; double multTP = 3.0; int minutesLeftInSession = 0; if(hour >= 8 && hour < 13) // London Pure { multSL = 1.3; multTP = 2.6; minutesLeftInSession = (13 - hour) * 60 - dt.min; } else if(hour >= 13 && hour < 17) // London / NY Overlap { multSL = 1.8; multTP = 3.6; minutesLeftInSession = (17 - hour) * 60 - dt.min; } else if(hour >= 17 && hour < 22) // NY Afternoon { multSL = 1.4; multTP = 2.5; minutesLeftInSession = (22 - hour) * 60 - dt.min; } else // Asian Session { multSL = 1.0; multTP = 2.0; minutesLeftInSession = (hour < 8) ? (8 - hour) * 60 - dt.min : (24 - hour + 8) * 60 - dt.min; } if(minutesLeftInSession > 0 && minutesLeftInSession <= 60) { multSL *= 0.8; multTP *= 0.8; } int atrHandle = iATR(sym, PERIOD_M15, 14); double atrValues[]; ArraySetAsSeries(atrValues, true); double rawATR = 0.0010; if(atrHandle != INVALID_HANDLE && CopyBuffer(atrHandle, 0, 0, 1, atrValues) > 0) { rawATR = atrValues[0]; IndicatorRelease(atrHandle); } double point = SymbolInfoDouble(sym, SYMBOL_POINT); if(point <= EPSILON) point = 0.0001; int digits = (int)SymbolInfoInteger(sym, SYMBOL_DIGITS); double pipUnit = (digits == 3 || digits == 5) ? point * 10.0 : point; if(pipUnit <= EPSILON) pipUnit = 0.0001; double atrInPips = rawATR / pipUnit; if(atrInPips <= EPSILON) atrInPips = 15.0; slPips = atrInPips * multSL; tpPips = atrInPips * multTP; } //+------------------------------------------------------------------+ //| Calculate True Daily PnL and Check Persistent Locks | //+------------------------------------------------------------------+ void CheckAndRestoreDailyRiskState(double &outStartBalance, double &outNetPnL, bool &outTargetHit, bool &outLossHit) { outTargetHit = false; outLossHit = false; string dateStr = TimeToString(TimeCurrent(), TIME_DATE); string targetLockKey = StringFormat("SLAVE_LOCK_TARGET_%I64d_%s", AccountInfoInteger(ACCOUNT_LOGIN), dateStr); string lossLockKey = StringFormat("SLAVE_LOCK_LOSS_%I64d_%s", AccountInfoInteger(ACCOUNT_LOGIN), dateStr); // Check if already locked earlier today if(GlobalVariableCheck(targetLockKey)) outTargetHit = true; if(GlobalVariableCheck(lossLockKey)) outLossHit = true; // 1. Calculate Midnight Server Time MqlDateTime dt; TimeToStruct(TimeCurrent(), dt); dt.hour = 0; dt.min = 0; dt.sec = 0; datetime midnight = StructToTime(dt); // 2. Select today's trade history HistorySelect(midnight, TimeCurrent()); double closedProfitToday = 0.0; int totalDeals = HistoryDealsTotal(); for(int i = 0; i < totalDeals; i++) { ulong ticket = HistoryDealGetTicket(i); if(ticket == 0) continue; long entry = HistoryDealGetInteger(ticket, DEAL_ENTRY); if(entry == DEAL_ENTRY_OUT || entry == DEAL_ENTRY_INOUT) { closedProfitToday += HistoryDealGetDouble(ticket, DEAL_PROFIT) + HistoryDealGetDouble(ticket, DEAL_SWAP) + HistoryDealGetDouble(ticket, DEAL_COMMISSION); } } // 3. True Midnight Starting Balance = Current Balance - Today's Closed Profit double currentBalance = AccountInfoDouble(ACCOUNT_BALANCE); outStartBalance = currentBalance - closedProfitToday; if(outStartBalance <= EPSILON) outStartBalance = currentBalance; // 4. Net PnL including floating open equity double currentEquity = AccountInfoDouble(ACCOUNT_EQUITY); outNetPnL = (currentEquity - outStartBalance); double targetMoney = outStartBalance * (InpMaxDailyProfitPct / 100.0); double maxLossMoney = outStartBalance * (InpMaxDailyLossPct / 100.0); // 5. Evaluate breaches if(closedProfitToday >= targetMoney || outNetPnL >= targetMoney) { outTargetHit = true; GlobalVariableSet(targetLockKey, 1.0); double currentGainPct = (outNetPnL / outStartBalance) * 100.0; SendOneTimeDailyLimitAlert("TARGET", currentGainPct, InpMaxDailyProfitPct); } if(closedProfitToday <= -maxLossMoney || outNetPnL <= -maxLossMoney) { outLossHit = true; GlobalVariableSet(lossLockKey, 1.0); double currentLossPct = MathAbs(outNetPnL / outStartBalance) * 100.0; SendOneTimeDailyLimitAlert("LOSS", currentLossPct, InpMaxDailyLossPct); } } //+------------------------------------------------------------------+ //| Daily PnL and Floating Risk Check (Slave Only) | //+------------------------------------------------------------------+ void CheckDailyLossAndProfit(double &dailyRealizedLoss, double &dailyRealizedProfit, double &runningRiskDollars) { datetime todayStart = StringToTime(TimeToString(TimeCurrent(), TIME_DATE) + " 00:00"); HistorySelect(todayStart, TimeCurrent()); double closedProfit = 0.0; int deals = HistoryDealsTotal(); for(int i = 0; i < deals; i++) { ulong dealTicket = HistoryDealGetTicket(i); if(dealTicket > 0) { ENUM_DEAL_ENTRY entry = (ENUM_DEAL_ENTRY)HistoryDealGetInteger(dealTicket, DEAL_ENTRY); if(entry == DEAL_ENTRY_OUT) { closedProfit += HistoryDealGetDouble(dealTicket, DEAL_PROFIT) + HistoryDealGetDouble(dealTicket, DEAL_SWAP) + HistoryDealGetDouble(dealTicket, DEAL_COMMISSION); } } } dailyRealizedLoss = (closedProfit < 0) ? MathAbs(closedProfit) : 0.0; dailyRealizedProfit = (closedProfit > 0) ? closedProfit : 0.0; runningRiskDollars = 0.0; for(int i = PositionsTotal() - 1; i >= 0; i--) { ulong ticket = PositionGetTicket(i); if(ticket > 0 && PositionGetInteger(POSITION_MAGIC) == InpSlaveMagic) { string sym = PositionGetString(POSITION_SYMBOL); ENUM_POSITION_TYPE pType = (ENUM_POSITION_TYPE)PositionGetInteger(POSITION_TYPE); double openPrice = PositionGetDouble(POSITION_PRICE_OPEN); double sl = PositionGetDouble(POSITION_SL); double vol = PositionGetDouble(POSITION_VOLUME); if(sl > EPSILON) { double distPoints = (pType == POSITION_TYPE_BUY) ? (openPrice - sl) : (sl - openPrice); if(distPoints > 0) { // --- 1. Calculate symbol point and spread points --- double point = SymbolInfoDouble(sym, SYMBOL_POINT); if(point <= EPSILON) point = 0.0001; double spreadPoints = (double)SymbolInfoInteger(sym, SYMBOL_SPREAD) * point; // --- 2. Add spread buffer to distance --- distPoints += spreadPoints; // Include immediate spread cost // --- 3. Compute running risk dollars with spread included --- double tickVal = SymbolInfoDouble(sym, SYMBOL_TRADE_TICK_VALUE); double tickSize = SymbolInfoDouble(sym, SYMBOL_TRADE_TICK_SIZE); if(tickSize > EPSILON && tickVal > EPSILON) { runningRiskDollars += (distPoints / tickSize) * tickVal * vol; } } } } } } //+------------------------------------------------------------------+ //| Dynamic Prop-Firm Compliant Lot Sizing Engine (FTMO & 5ers Safe) | //+------------------------------------------------------------------+ double CalculateSlaveLot(string sym, double slDistancePoints, double currentRunningRisk) { double balance = AccountInfoDouble(ACCOUNT_BALANCE); if(balance <= EPSILON) return 0.0; // 1. Minimum Stop Loss Distance Floor (Prevents runaway lot size on tiny SLs) double minSLPoints = PipsToPoints(sym, InpMinSLPips); if(slDistancePoints < minSLPoints) { slDistancePoints = minSLPoints; } // 2. Risk Budgeting double maxTradeRiskMoney = balance * (InpRiskPerTradePct / 100.0); // To (Reserve a 0.35% safety buffer for spreads and commissions): double allowedDailyRiskPct = MathMax(0.5, InpMaxDailyLossPct - 0.35); // Allocates ~1.45% max double maxDailyRiskMoney = balance * (allowedDailyRiskPct / 100.0); double remainingRiskBudget = maxDailyRiskMoney - currentRunningRisk; if(remainingRiskBudget <= EPSILON) { TriggerRejectionAlert("Risk Cap Exceeded", "Cumulative daily open risk reaches or exceeds threshold."); return 0.0; } double allowedRisk = MathMin(maxTradeRiskMoney, remainingRiskBudget); if(allowedRisk <= EPSILON) return 0.0; double tickVal = SymbolInfoDouble(sym, SYMBOL_TRADE_TICK_VALUE); double tickSize = SymbolInfoDouble(sym, SYMBOL_TRADE_TICK_SIZE); if(tickVal <= EPSILON) { MqlTick dummyTick; SymbolInfoTick(sym, dummyTick); tickVal = SymbolInfoDouble(sym, SYMBOL_TRADE_TICK_VALUE); } double minLot = SymbolInfoDouble(sym, SYMBOL_VOLUME_MIN); double maxLot = SymbolInfoDouble(sym, SYMBOL_VOLUME_MAX); double stepLot = SymbolInfoDouble(sym, SYMBOL_VOLUME_STEP); if(tickSize <= EPSILON || tickVal <= EPSILON || slDistancePoints <= EPSILON || stepLot <= EPSILON) { TriggerRejectionAlert("Math Warning", "Tick size, tick value, or SL distance is zero/invalid."); return minLot; } double lossPerLot = (slDistancePoints / tickSize) * tickVal; if(lossPerLot <= EPSILON) return minLot; double calculatedLot = allowedRisk / lossPerLot; // 3. FTMO & The5ers Balance-Proportional Hard Cap (Default 1 lot per $10,000 balance) double maxPropAllowedLots = (balance / 10000.0) * InpMaxLotsPer10k; if(calculatedLot > maxPropAllowedLots) { PrintFormat("[PROP GUARD] Capping lot from %.2f to %.2f (Rule: Max %.1f lots per $10k)", calculatedLot, maxPropAllowedLots, InpMaxLotsPer10k); calculatedLot = maxPropAllowedLots; } // 4. Broker Margin Safety Check (Max 50% free margin per single position) double marginForOneLot = 0.0; if(OrderCalcMargin(ORDER_TYPE_BUY, sym, 1.0, SymbolInfoDouble(sym, SYMBOL_ASK), marginForOneLot)) { if(marginForOneLot > EPSILON) { double maxMarginAllowedLots = (AccountInfoDouble(ACCOUNT_MARGIN_FREE) * 0.50) / marginForOneLot; if(calculatedLot > maxMarginAllowedLots) { PrintFormat("[MARGIN GUARD] Capping lot from %.2f to %.2f to preserve margin buffer", calculatedLot, maxMarginAllowedLots); calculatedLot = maxMarginAllowedLots; } } } // 5. Volume Step Alignment & Clamping calculatedLot = MathFloor(calculatedLot / stepLot) * stepLot; if(calculatedLot < minLot) calculatedLot = minLot; if(calculatedLot > maxLot) calculatedLot = maxLot; return calculatedLot; } //+------------------------------------------------------------------+ //| Master Broadcast Engine | //+------------------------------------------------------------------+ void BroadcastSignal(string message) { int handle = FileOpen(InpBridgeFileName, FILE_READ | FILE_WRITE | FILE_TXT | FILE_COMMON | FILE_SHARE_READ | FILE_SHARE_WRITE); if(handle != INVALID_HANDLE) { FileSeek(handle, 0, SEEK_END); FileWriteString(handle, message + "\r\n"); FileClose(handle); PrintFormat("[TRANSMITTER] Broadcasted: %s", message); } else { handle = FileOpen(InpBridgeFileName, FILE_WRITE | FILE_TXT | FILE_COMMON | FILE_SHARE_READ | FILE_SHARE_WRITE); if(handle != INVALID_HANDLE) { FileWriteString(handle, message + "\r\n"); FileClose(handle); PrintFormat("[TRANSMITTER] Broadcasted (New Queue): %s", message); } else { PrintFormat("[TRANSMITTER ERROR] Failed writing to queue: %d", GetLastError()); } } } //+------------------------------------------------------------------+ //| Master Queue Pruning | //+------------------------------------------------------------------+ void PruneOldSignals() { if(TimeGMT() - g_lastPruneTime < 30) return; g_lastPruneTime = TimeGMT(); if(!FileIsExist(InpBridgeFileName, FILE_COMMON)) return; int handle = FileOpen(InpBridgeFileName, FILE_READ | FILE_TXT | FILE_COMMON | FILE_SHARE_READ | FILE_SHARE_WRITE); if(handle == INVALID_HANDLE) return; string lines[]; int totalLines = 0; while(!FileIsEnding(handle)) { string line = FileReadString(handle); StringTrimLeft(line); StringTrimRight(line); if(StringLen(line) > 0) { int timeIdx = StringFind(line, "TIME="); if(timeIdx >= 0) { long t = (long)StringToInteger(StringSubstr(line, timeIdx + 5)); if(t > 0 && (TimeGMT() - t) < 60) { ArrayResize(lines, totalLines + 1); lines[totalLines] = line; totalLines++; } } } } FileClose(handle); int writeHandle = FileOpen(InpBridgeFileName, FILE_WRITE | FILE_TXT | FILE_COMMON | FILE_SHARE_READ | FILE_SHARE_WRITE); if(writeHandle != INVALID_HANDLE) { for(int i = 0; i < totalLines; i++) { FileWriteString(writeHandle, lines[i] + "\r\n"); } FileClose(writeHandle); } } //+------------------------------------------------------------------+ //| Close all positions & cancel pending orders | //+------------------------------------------------------------------+ void CloseAllAccountTrades(ulong magicFilter) { for(int i = PositionsTotal() - 1; i >= 0; i--) { ulong ticket = PositionGetTicket(i); if(ticket > 0) { if(magicFilter == 0 || PositionGetInteger(POSITION_MAGIC) == magicFilter) m_trade.PositionClose(ticket); } } for(int i = OrdersTotal() - 1; i >= 0; i--) { ulong ticket = OrderGetTicket(i); if(ticket > 0) { if(magicFilter == 0 || OrderGetInteger(ORDER_MAGIC) == magicFilter) m_trade.OrderDelete(ticket); } } } //+------------------------------------------------------------------+ //| Process Inbound Signal (Slave Only) | //+------------------------------------------------------------------+ void ProcessMasterSignal(string payload) { string action="", type="", masterSym="", id=""; double masterVol=0.0, masterPrice=0.0, masterSL=0.0, masterTP=0.0; long masterTimestamp = 0; string tokens[]; int count = StringSplit(payload, '|', tokens); for(int i = 0; i < count; i++) { string kv[]; if(StringSplit(tokens[i], '=', kv) == 2) { if(kv[0] == "ACTION") action = kv[1]; else if(kv[0] == "TYPE") type = kv[1]; else if(kv[0] == "SYMBOL") masterSym = kv[1]; else if(kv[0] == "VOL") masterVol = StringToDouble(kv[1]); else if(kv[0] == "PRICE") masterPrice = StringToDouble(kv[1]); else if(kv[0] == "SL") masterSL = StringToDouble(kv[1]); else if(kv[0] == "TP") masterTP = StringToDouble(kv[1]); else if(kv[0] == "ID") id = kv[1]; else if(kv[0] == "TIME") masterTimestamp = (long)StringToInteger(kv[1]); } } if(StringLen(id) == 0) return; // 1. Emergency Liquidation Command if(action == "CLOSE_ALL") { string closeAllMarker = "SLAVE_CLOSEALL_" + (string)AccountInfoInteger(ACCOUNT_LOGIN) + "_" + id; if(!GlobalVariableCheck(closeAllMarker)) { GlobalVariableSet(closeAllMarker, 1.0); CloseAllAccountTrades(InpSlaveMagic); TriggerRejectionAlert("Master Close All", "Received liquidation command from Master."); } return; } // 2. Pending Limit Order Cancellation Sync if(action == "CANCEL_LIMIT") { string mappedKey = "SLAVE_LIMIT_MAP_" + (string)AccountInfoInteger(ACCOUNT_LOGIN) + "_" + id; if(GlobalVariableCheck(mappedKey)) { ulong slaveOrderTicket = (ulong)GlobalVariableGet(mappedKey); if(slaveOrderTicket > 0) { m_trade.OrderDelete(slaveOrderTicket); GlobalVariableDel(mappedKey); PrintFormat("[SLAVE] Deleted slave limit order %I64u (Master ID: %s)", slaveOrderTicket, id); } } return; } // 3. Duplicate Execution Filter (Check before executing or rejecting) string executedMarker = "SLAVE_PROC_" + (string)AccountInfoInteger(ACCOUNT_LOGIN) + "_" + id; if(GlobalVariableCheck(executedMarker)) return; // 4. PERSISTENT RISK-GATE CHECKS (Guarantees no entry if limit breached) if(g_dailyLossLimitHit) { GlobalVariableSet(executedMarker, 1.0); // Mark processed to avoid multiple alerts PrintFormat("[LOCK ENFORCED] Trade ID %s rejected: Daily Drawdown limit (-%.1f%%) active.", id, InpMaxDailyLossPct); return; } if(g_dailyTargetHit) { GlobalVariableSet(executedMarker, 1.0); // Mark processed to avoid multiple alerts PrintFormat("[LOCK ENFORCED] Trade ID %s rejected: Daily Profit Target (+%.1f%%) active.", id, InpMaxDailyProfitPct); return; } // Mark signal processed now that risk gates have verified eligibility GlobalVariableSet(executedMarker, 1.0); string slaveSym = ResolveSymbol(masterSym); if(StringLen(slaveSym) == 0) { TriggerRejectionAlert("Symbol Resolution Failed", StringFormat("Cannot find %s on broker.", masterSym)); return; } // 5. Drawdown Cap Check Against Starting Baseline double dailyLoss=0.0, dailyProfit=0.0, runningRisk=0.0; CheckDailyLossAndProfit(dailyLoss, dailyProfit, runningRisk); if(g_dayStartBalance > EPSILON && ((dailyLoss / g_dayStartBalance) * 100.0 >= InpMaxDailyLossPct)) { TriggerRejectionAlert("Max Daily Loss Reached", StringFormat("Daily loss is %.2f%% (Limit: %.2f%%).", (dailyLoss / g_dayStartBalance) * 100.0, InpMaxDailyLossPct)); return; } // 6. Signal Age Threshold if(masterTimestamp > 0 && (TimeGMT() - masterTimestamp) > InpMaxDelaySec) { TriggerRejectionAlert("Execution Timeout", StringFormat("Signal transmission lag was %d seconds.", (int)(TimeGMT() - masterTimestamp))); return; } // 7. Spread Filter Check if(InpMaxSpreadPips > 0.0) { long currentSpread = SymbolInfoInteger(slaveSym, SYMBOL_SPREAD); double maxSpreadPoints = PipsToPoints(slaveSym, InpMaxSpreadPips); if((double)currentSpread > maxSpreadPoints) { TriggerRejectionAlert("Spread Filter Exceeded", StringFormat("Spread: %d points (> %.1f pips limit).", currentSpread, InpMaxSpreadPips)); return; } } // 8. Max Deviation Check double currentBid = SymbolInfoDouble(slaveSym, SYMBOL_BID); double currentAsk = SymbolInfoDouble(slaveSym, SYMBOL_ASK); double slaveCurrentPrice = (type == "BUY" || type == "BUY_LIMIT") ? currentAsk : currentBid; double maxDevPoints = PipsToPoints(slaveSym, (double)InpMaxDeviationPips); if(action == "MARKET" && MathAbs(slaveCurrentPrice - masterPrice) > maxDevPoints) { TriggerRejectionAlert("Deviation Exceeded", StringFormat("Master: %.5f | Slave: %.5f", masterPrice, slaveCurrentPrice)); return; } // 9. ATR SL/TP Resolution double finalSL = masterSL; double finalTP = masterTP; double referencePrice = (action == "LIMIT") ? masterPrice : slaveCurrentPrice; if(finalSL <= EPSILON || finalTP <= EPSILON) { double atrSLPips=0.0, atrTPPips=0.0; CalculateSessionATR(slaveSym, atrSLPips, atrTPPips); double slPoints = PipsToPoints(slaveSym, atrSLPips); double tpPoints = PipsToPoints(slaveSym, atrTPPips); if(type == "BUY" || type == "BUY_LIMIT") { if(finalSL <= EPSILON) finalSL = referencePrice - slPoints; if(finalTP <= EPSILON) finalTP = referencePrice + tpPoints; } else if(type == "SELL" || type == "SELL_LIMIT") { if(finalSL <= EPSILON) finalSL = referencePrice + slPoints; if(finalTP <= EPSILON) finalTP = referencePrice - tpPoints; } } // 10. Risk Lot Sizing (with FTMO & The5ers rules built-in) double slDistPoints = MathAbs(referencePrice - finalSL); // Add spread points to SL distance so lot sizing reserves room for spread double point = SymbolInfoDouble(slaveSym, SYMBOL_POINT); if(point <= EPSILON) point = 0.0001; double spreadPoints = (double)SymbolInfoInteger(slaveSym, SYMBOL_SPREAD) * point; slDistPoints += spreadPoints; double slaveLot = CalculateSlaveLot(slaveSym, slDistPoints, runningRisk); if(slaveLot <= EPSILON) { TriggerRejectionAlert("Risk Budget Violated", "Calculated lot violates single or cumulative risk."); return; } // 11. Margin Check ENUM_ORDER_TYPE oType = (type == "BUY" || type == "BUY_LIMIT") ? ORDER_TYPE_BUY : ORDER_TYPE_SELL; double marginRequired = 0.0; if(OrderCalcMargin(oType, slaveSym, slaveLot, referencePrice, marginRequired)) { if(marginRequired > AccountInfoDouble(ACCOUNT_MARGIN_FREE)) { TriggerRejectionAlert("Insufficient Margin", StringFormat("Required: $%.2f | Free: $%.2f", marginRequired, AccountInfoDouble(ACCOUNT_MARGIN_FREE))); return; } } // 12. Execution ApplySupportedFillingMode(slaveSym); m_trade.SetDeviationInPoints((ulong)maxDevPoints); bool success = false; if(action == "MARKET") { if(type == "BUY") success = m_trade.Buy(slaveLot, slaveSym, currentAsk, finalSL, finalTP, "Copied Trade"); else if(type == "SELL") success = m_trade.Sell(slaveLot, slaveSym, currentBid, finalSL, finalTP, "Copied Trade"); } else if(action == "LIMIT") { if(type == "BUY_LIMIT") success = m_trade.BuyLimit(slaveLot, masterPrice, slaveSym, finalSL, finalTP, ORDER_TIME_GTC, 0, "Copied Limit"); else if(type == "SELL_LIMIT") success = m_trade.SellLimit(slaveLot, masterPrice, slaveSym, finalSL, finalTP, ORDER_TIME_GTC, 0, "Copied Limit"); if(success) { ulong placedTicket = m_trade.ResultOrder(); string mappedKey = "SLAVE_LIMIT_MAP_" + (string)AccountInfoInteger(ACCOUNT_LOGIN) + "_" + id; GlobalVariableSet(mappedKey, (double)placedTicket); } } if(success) { string msg = StringFormat("✅ *TRADE EXECUTED*\nAccount: %I64u\nPair: %s\nType: %s\nLot: %.2f\nEntry: %.5f\nSL: %.5f\nTP: %.5f\nRisk: %.2f%%", AccountInfoInteger(ACCOUNT_LOGIN), slaveSym, type, slaveLot, referencePrice, finalSL, finalTP, InpRiskPerTradePct); SendTelegramMessage(msg); } else { TriggerRejectionAlert("OrderSend Failed", StringFormat("Code: %d (%s)", m_trade.ResultRetcode(), m_trade.ResultRetcodeDescription())); } } //+------------------------------------------------------------------+ //| Expert Initialization Function | //+------------------------------------------------------------------+ int OnInit() { if(InpCopierRole == ROLE_MASTER) { m_trade.SetExpertMagicNumber(InpMasterMagic); m_trade.SetDeviationInPoints(20); g_initialEquity = AccountInfoDouble(ACCOUNT_BALANCE); EventSetMillisecondTimer(250); PrintFormat("[MASTER ACTIVE] Universal Trade Copier initialized on Account: %I64u", AccountInfoInteger(ACCOUNT_LOGIN)); } else { // 1. Immediately restore daily state across restarts double startBal = 0.0, netPnL = 0.0; CheckAndRestoreDailyRiskState(startBal, netPnL, g_dailyTargetHit, g_dailyLossLimitHit); g_dayStartBalance = startBal; if(g_dailyTargetHit) PrintFormat("[SAFETY LOCK] Terminal restarted: +%.1f%% target already hit today. Executions LOCKED.", InpMaxDailyProfitPct); if(g_dailyLossLimitHit) PrintFormat("[SAFETY LOCK] Terminal restarted: -%.1f%% daily drawdown cap breached. Executions LOCKED.", InpMaxDailyLossPct); m_trade.SetExpertMagicNumber(InpSlaveMagic); m_trade.SetDeviationInPoints(20); EventSetMillisecondTimer(100); PrintFormat("[SLAVE ACTIVE] Universal Trade Copier initialized on Account: %I64u | Daily Base: $%.2f", AccountInfoInteger(ACCOUNT_LOGIN), g_dayStartBalance); } return INIT_SUCCEEDED; } //+------------------------------------------------------------------+ //| Expert Deinitialization Function | //+------------------------------------------------------------------+ void OnDeinit(const int reason) { EventKillTimer(); } //+------------------------------------------------------------------+ //| Expert Timer Function | //+------------------------------------------------------------------+ void OnTimer() { // ==================== MASTER TIMER ROUTINE ==================== if(InpCopierRole == ROLE_MASTER) { PruneOldSignals(); if(InpMasterTargetClose && !g_masterTargetHit && g_initialEquity > EPSILON) { double currentEquity = AccountInfoDouble(ACCOUNT_EQUITY); double targetProfit = g_initialEquity * (InpMasterTargetPct / 100.0); if((currentEquity - g_initialEquity) >= targetProfit) { PrintFormat("[MASTER TARGET] +%.2f%% reached! Broadcasting CLOSE_ALL.", InpMasterTargetPct); datetime timestamp = TimeGMT(); BroadcastSignal(StringFormat("ACTION=CLOSE_ALL|ID=%I64u|TIME=%I64u", (ulong)timestamp, (long)timestamp)); CloseAllAccountTrades(InpMasterMagic); g_masterTargetHit = true; return; } } // Master Trailing Stop & 25-Pip BE Routine for(int i = PositionsTotal() - 1; i >= 0; i--) { ulong ticket = PositionGetTicket(i); if(ticket == 0) continue; string sym = PositionGetString(POSITION_SYMBOL); ENUM_POSITION_TYPE posType = (ENUM_POSITION_TYPE)PositionGetInteger(POSITION_TYPE); double openPrice = PositionGetDouble(POSITION_PRICE_OPEN); double curPrice = PositionGetDouble(POSITION_PRICE_CURRENT); double curSL = PositionGetDouble(POSITION_SL); double curTP = PositionGetDouble(POSITION_TP); double volume = PositionGetDouble(POSITION_VOLUME); double beDistance = PipsToPoints(sym, InpMasterBETrigger); double trailDist = PipsToPoints(sym, InpMasterTrailDist); double trailStep = PipsToPoints(sym, InpMasterTrailStep); double point = SymbolInfoDouble(sym, SYMBOL_POINT); if(point <= EPSILON) point = 0.0001; double stopsLevel = SymbolInfoInteger(sym, SYMBOL_TRADE_STOPS_LEVEL) * point; double freezeLevel = SymbolInfoInteger(sym, SYMBOL_TRADE_FREEZE_LEVEL) * point; double minBuffer = MathMax(stopsLevel, freezeLevel) + (point * 2.0); string beDoneMarker = "MASTER_BE_" + (string)ticket; bool isBeDone = GlobalVariableCheck(beDoneMarker); if(posType == POSITION_TYPE_BUY) { if(InpMasterBEPartial && !isBeDone && (curPrice - openPrice >= beDistance)) { double stepVol = SymbolInfoDouble(sym, SYMBOL_VOLUME_STEP); double minVol = SymbolInfoDouble(sym, SYMBOL_VOLUME_MIN); double closeVol = MathFloor((volume * 0.5) / stepVol) * stepVol; if(closeVol >= minVol) m_trade.PositionClosePartial(ticket, closeVol); double targetSL = openPrice + point; if((curPrice - targetSL) > minBuffer) { m_trade.PositionModify(ticket, targetSL, curTP); GlobalVariableSet(beDoneMarker, 1.0); } } else if(InpMasterTrailing && isBeDone) { if(curPrice - openPrice > trailDist) { double newSL = curPrice - trailDist; if(newSL > curSL + trailStep && (curPrice - newSL) > minBuffer) m_trade.PositionModify(ticket, newSL, curTP); } } } else if(posType == POSITION_TYPE_SELL) { if(InpMasterBEPartial && !isBeDone && (openPrice - curPrice >= beDistance)) { double stepVol = SymbolInfoDouble(sym, SYMBOL_VOLUME_STEP); double minVol = SymbolInfoDouble(sym, SYMBOL_VOLUME_MIN); double closeVol = MathFloor((volume * 0.5) / stepVol) * stepVol; if(closeVol >= minVol) m_trade.PositionClosePartial(ticket, closeVol); double targetSL = openPrice - point; if((targetSL - curPrice) > minBuffer) { m_trade.PositionModify(ticket, targetSL, curTP); GlobalVariableSet(beDoneMarker, 1.0); } } else if(InpMasterTrailing && isBeDone) { if(openPrice - curPrice > trailDist) { double newSL = curPrice + trailDist; if((curSL <= EPSILON || newSL < curSL - trailStep) && (newSL - curPrice) > minBuffer) m_trade.PositionModify(ticket, newSL, curTP); } } } } } // ==================== SLAVE TIMER ROUTINE ==================== else if(InpCopierRole == ROLE_SLAVE) { // 1. Recalculate daily profit/loss against midnight baseline double startBal = 0.0, netPnL = 0.0; CheckAndRestoreDailyRiskState(startBal, netPnL, g_dailyTargetHit, g_dailyLossLimitHit); g_dayStartBalance = startBal; // 2. Liquidate open positions if limits breached if(g_dailyTargetHit || g_dailyLossLimitHit) { CloseAllAccountTrades(InpSlaveMagic); } // 3. Read shared multi-slave queue (non-destructive) if(FileIsExist(InpBridgeFileName, FILE_COMMON)) { int handle = FileOpen(InpBridgeFileName, FILE_READ | FILE_TXT | FILE_COMMON | FILE_SHARE_READ | FILE_SHARE_WRITE); if(handle != INVALID_HANDLE) { while(!FileIsEnding(handle)) { string line = FileReadString(handle); StringTrimLeft(line); StringTrimRight(line); if(StringLen(line) > 0) { ProcessMasterSignal(line); } } FileClose(handle); } } // 4. Slave Trailing Stop & 25-Pip BE Routine (Skip if limits breached) if(g_dailyTargetHit || g_dailyLossLimitHit) return; for(int i = PositionsTotal() - 1; i >= 0; i--) { ulong ticket = PositionGetTicket(i); if(ticket == 0 || PositionGetInteger(POSITION_MAGIC) != InpSlaveMagic) continue; string sym = PositionGetString(POSITION_SYMBOL); ENUM_POSITION_TYPE pType = (ENUM_POSITION_TYPE)PositionGetInteger(POSITION_TYPE); double openPrice = PositionGetDouble(POSITION_PRICE_OPEN); double curPrice = PositionGetDouble(POSITION_PRICE_CURRENT); double curSL = PositionGetDouble(POSITION_SL); double curTP = PositionGetDouble(POSITION_TP); double volume = PositionGetDouble(POSITION_VOLUME); double beDistance = PipsToPoints(sym, InpSlaveBETrigger); double trailDist = PipsToPoints(sym, InpSlaveTrailDist); double trailStep = PipsToPoints(sym, InpSlaveTrailStep); double point = SymbolInfoDouble(sym, SYMBOL_POINT); if(point <= EPSILON) point = 0.0001; double stopsLevel = SymbolInfoInteger(sym, SYMBOL_TRADE_STOPS_LEVEL) * point; double freezeLevel = SymbolInfoInteger(sym, SYMBOL_TRADE_FREEZE_LEVEL) * point; double minBuffer = MathMax(stopsLevel, freezeLevel) + (point * 2.0); string beMarker = "SLAVE_BE_" + (string)ticket; bool isBeDone = GlobalVariableCheck(beMarker); if(pType == POSITION_TYPE_BUY) { if(!isBeDone && (curPrice - openPrice >= beDistance)) { double stepVol = SymbolInfoDouble(sym, SYMBOL_VOLUME_STEP); double minVol = SymbolInfoDouble(sym, SYMBOL_VOLUME_MIN); if(stepVol > EPSILON) { double closeVol = MathFloor((volume * 0.5) / stepVol) * stepVol; if(closeVol >= minVol) m_trade.PositionClosePartial(ticket, closeVol); } double spreadPoints = (double)SymbolInfoInteger(sym, SYMBOL_SPREAD) * point; double targetSL = openPrice + spreadPoints; if((curPrice - targetSL) > minBuffer) { m_trade.PositionModify(ticket, targetSL, curTP); GlobalVariableSet(beMarker, 1.0); } } else if(isBeDone) { if(curPrice - openPrice > trailDist) { double newSL = curPrice - trailDist; if(newSL > curSL + trailStep && (curPrice - newSL) > minBuffer) m_trade.PositionModify(ticket, newSL, curTP); } } } else if(pType == POSITION_TYPE_SELL) { if(!isBeDone && (openPrice - curPrice >= beDistance)) { double stepVol = SymbolInfoDouble(sym, SYMBOL_VOLUME_STEP); double minVol = SymbolInfoDouble(sym, SYMBOL_VOLUME_MIN); if(stepVol > EPSILON) { double closeVol = MathFloor((volume * 0.5) / stepVol) * stepVol; if(closeVol >= minVol) m_trade.PositionClosePartial(ticket, closeVol); } double spreadPoints = (double)SymbolInfoInteger(sym, SYMBOL_SPREAD) * point; double targetSL = openPrice - spreadPoints; if((targetSL - curPrice) > minBuffer) { m_trade.PositionModify(ticket, targetSL, curTP); GlobalVariableSet(beMarker, 1.0); } } else if(isBeDone) { if(openPrice - curPrice > trailDist) { double newSL = curPrice + trailDist; if((curSL <= EPSILON || newSL < curSL - trailStep) && (newSL - curPrice) > minBuffer) m_trade.PositionModify(ticket, newSL, curTP); } } } } } } //+------------------------------------------------------------------+ //| Trade Transactions Handler | //+------------------------------------------------------------------+ void OnTradeTransaction(const MqlTradeTransaction &trans, const MqlTradeRequest &request, const MqlTradeResult &result) { // ==================== MASTER TRANSACTIONS ==================== if(InpCopierRole == ROLE_MASTER) { // Catch Market Executions if(trans.type == TRADE_TRANSACTION_DEAL_ADD) { ulong dealTicket = trans.deal; if(HistoryDealSelect(dealTicket)) { ENUM_DEAL_ENTRY entry = (ENUM_DEAL_ENTRY)HistoryDealGetInteger(dealTicket, DEAL_ENTRY); if(entry == DEAL_ENTRY_IN) { ulong parentOrder = (ulong)HistoryDealGetInteger(dealTicket, DEAL_ORDER); string limitMarker = "TX_LIMIT_ACTIVE_" + (string)parentOrder; if(GlobalVariableCheck(limitMarker)) { GlobalVariableDel(limitMarker); PrintFormat("[MASTER] Limit order %I64u filled. Re-broadcast suppressed.", parentOrder); return; } string marker = "TX_DEAL_" + (string)dealTicket; if(!GlobalVariableCheck(marker)) { GlobalVariableSet(marker, 1.0); string sym = HistoryDealGetString(dealTicket, DEAL_SYMBOL); ENUM_DEAL_TYPE type = (ENUM_DEAL_TYPE)HistoryDealGetInteger(dealTicket, DEAL_TYPE); double vol = HistoryDealGetDouble(dealTicket, DEAL_VOLUME); double price = HistoryDealGetDouble(dealTicket, DEAL_PRICE); ulong posID = HistoryDealGetInteger(dealTicket, DEAL_POSITION_ID); double sl = 0.0, tp = 0.0; if(PositionSelectByTicket(posID)) { sl = PositionGetDouble(POSITION_SL); tp = PositionGetDouble(POSITION_TP); } string cmd = (type == DEAL_TYPE_BUY) ? "BUY" : (type == DEAL_TYPE_SELL) ? "SELL" : "UNKNOWN"; if(cmd != "UNKNOWN") { datetime timestamp = TimeGMT(); string payload = StringFormat("ACTION=MARKET|TYPE=%s|SYMBOL=%s|VOL=%.2f|PRICE=%.5f|SL=%.5f|TP=%.5f|ID=%I64u|TIME=%I64u", cmd, sym, vol, price, sl, tp, posID, (long)timestamp); BroadcastSignal(payload); } } } } } // Catch Pending Order Placement if(trans.type == TRADE_TRANSACTION_ORDER_ADD) { ulong orderTicket = trans.order; if(OrderSelect(orderTicket)) { ENUM_ORDER_TYPE ordType = (ENUM_ORDER_TYPE)OrderGetInteger(ORDER_TYPE); if(ordType == ORDER_TYPE_BUY_LIMIT || ordType == ORDER_TYPE_SELL_LIMIT) { string marker = "TX_ORD_" + (string)orderTicket; if(!GlobalVariableCheck(marker)) { GlobalVariableSet(marker, 1.0); GlobalVariableSet("TX_LIMIT_ACTIVE_" + (string)orderTicket, 1.0); string sym = OrderGetString(ORDER_SYMBOL); double vol = OrderGetDouble(ORDER_VOLUME_INITIAL); double price = OrderGetDouble(ORDER_PRICE_OPEN); double sl = OrderGetDouble(ORDER_SL); double tp = OrderGetDouble(ORDER_TP); string cmd = (ordType == ORDER_TYPE_BUY_LIMIT) ? "BUY_LIMIT" : "SELL_LIMIT"; datetime timestamp = TimeGMT(); string payload = StringFormat("ACTION=LIMIT|TYPE=%s|SYMBOL=%s|VOL=%.2f|PRICE=%.5f|SL=%.5f|TP=%.5f|ID=%I64u|TIME=%I64u", cmd, sym, vol, price, sl, tp, orderTicket, (long)timestamp); BroadcastSignal(payload); } } } } // Catch Pending Order Cancellation if(trans.type == TRADE_TRANSACTION_ORDER_DELETE) { ulong orderTicket = trans.order; string limitMarker = "TX_LIMIT_ACTIVE_" + (string)orderTicket; if(GlobalVariableCheck(limitMarker)) { GlobalVariableDel(limitMarker); datetime timestamp = TimeGMT(); string payload = StringFormat("ACTION=CANCEL_LIMIT|ID=%I64u|TIME=%I64u", orderTicket, (long)timestamp); BroadcastSignal(payload); PrintFormat("[MASTER] Cancelled limit order %I64u synced to slaves.", orderTicket); } } } // ==================== SLAVE TRANSACTIONS ==================== else if(InpCopierRole == ROLE_SLAVE) { if(trans.type == TRADE_TRANSACTION_DEAL_ADD) { ulong dealTicket = trans.deal; if(HistoryDealSelect(dealTicket)) { ENUM_DEAL_ENTRY entry = (ENUM_DEAL_ENTRY)HistoryDealGetInteger(dealTicket, DEAL_ENTRY); if(entry == DEAL_ENTRY_OUT) { ulong dealMagic = HistoryDealGetInteger(dealTicket, DEAL_MAGIC); if(dealMagic == InpSlaveMagic) { string sym = HistoryDealGetString(dealTicket, DEAL_SYMBOL); double vol = HistoryDealGetDouble(dealTicket, DEAL_VOLUME); double price = HistoryDealGetDouble(dealTicket, DEAL_PRICE); double profit= HistoryDealGetDouble(dealTicket, DEAL_PROFIT) + HistoryDealGetDouble(dealTicket, DEAL_SWAP) + HistoryDealGetDouble(dealTicket, DEAL_COMMISSION); string msg = StringFormat("🔴 *TRADE CLOSED*\nAccount: %I64u\nPair: %s\nLot: %.2f\nClose Price: %.5f\nPnL: $%.2f", AccountInfoInteger(ACCOUNT_LOGIN), sym, vol, price, profit); SendTelegramMessage(msg); } } } } } }