//+------------------------------------------------------------------+ //| Bridge EA:網站(TradingView 警報)→ MT5 下單 | //| | //| 安裝: | //| 1. 檔案放到 MT5「檔案 → 開啟資料夾 → MQL5/Experts」,MetaEditor 編譯 | //| 2. 工具 → 選項 → EA 交易:勾「允許演算法交易」與「允許 WebRequest」, | //| 網址清單加入你的網站(例如 https://bridge.example.com) | //| 3. 拖到任一張圖(只要一張),填網站網址、授權碼、EA 金鑰 | //| 一個 MT5 帳戶只掛一個本 EA;它會處理所有商品。 | //+------------------------------------------------------------------+ #property version "1.00" #property description "TradingView → 網站 → MT5。相容 PineConnector 警報語法,另支援策略訂閱與部位同步。" #include #define EA_VER "1.8.0" #define DIR_NAME "BridgeEA" //──────────────────────────── 輸入 ──────────────────────────── enum ENUM_BR_VOL { BR_VOL_LOTS = 0, // 手數 BR_VOL_PCT_BAL_LOSS = 1, // 停損時虧餘額的 % BR_VOL_PCT_EQ_LOSS = 2, // 停損時虧權益的 % BR_VOL_DOLLAR_LOSS = 3, // 停損時虧多少錢 BR_VOL_PCT_BAL_MARGIN = 4, // 餘額的 % 當保證金 BR_VOL_PCT_EQ_NOTIONAL = 5 // 名目部位 = 權益的 % }; enum ENUM_BR_TGT { BR_TGT_PIPS = 0, // pips(1 pip = 10 points) BR_TGT_PRICE = 1, // 價格 BR_TGT_PCT = 2 // 進場價的 % }; enum ENUM_BR_PYR { BR_PYR_ON = 0, // 允許同方向加碼 BR_PYR_OFF = 1, // 同方向最多一張 BR_PYR_OFF_ANY = 2 // 每個商品最多一張(不分方向) }; enum ENUM_BR_REV { BR_REV_OFF = 0, // 不處理(對沖帳戶會同時有多空) BR_REV_CLOSE_OPEN = 1, // 先平反向部位,再進場 BR_REV_CLOSE_ONLY = 2 // 只平反向部位,不進場 }; enum ENUM_BR_BASE { BR_BASE_EQUITY = 0, // 權益 BR_BASE_BALANCE = 1, // 餘額 BR_BASE_FIXED = 2 // 固定金額(例如 FTMO 初始資金) }; enum ENUM_BR_WHERE { BR_WHERE_ANY = 0, // 本機、VPS 都執行 BR_WHERE_VPS = 1 // 只在 MQL5 VPS 執行(本機這份待命) }; input group "連線" input string InpServerURL = "https://bridge.example.com"; // 網站網址(要加進「允許 WebRequest」清單) input string InpLicense = ""; // 授權碼 License ID(網站「帳戶」頁) input string InpEAKey = ""; // EA 金鑰(網站「帳戶」頁;不要放進 TradingView) input ENUM_BR_WHERE InpRunWhere = BR_WHERE_ANY; // 在哪裡執行(搬到 MQL5 VPS 前改成「只在 MQL5 VPS」) input int InpPollWait = 2; // 長輪詢等待秒數(0 = 一般輪詢) input int InpPollMs = 50; // 輪詢間隔(毫秒):上一輪回來後多久再問(越短,訊號等得越少) input int InpHeartbeatSec = 10; // 回報帳戶狀態的間隔(秒) input group "部位" input ENUM_BR_VOL InpVolType = BR_VOL_LOTS; // 舊語法 risk= 的意思(Volume Type) input ENUM_BR_TGT InpTgtType = BR_TGT_PIPS; // 舊語法 sl= / tp= 的意思(Target Type) input double InpDefaultLots = 0; // 訊息沒帶部位時的手數(0 = 不下單) input ENUM_BR_BASE InpBase = BR_BASE_EQUITY; // 部位基準(策略訂閱、部位同步用) input double InpBaseFixed = 100000; // 固定金額(部位基準選「固定金額」時) input double InpMaxLots = 50; // 單筆最多幾手(安全上限) input group "執行" input long InpMagic = 20261115; // 直接警報的 magic number input ENUM_BR_PYR InpPyramid = BR_PYR_ON; // 同方向加碼(Pyramiding) input ENUM_BR_REV InpReverse = BR_REV_OFF; // 反向訊號(Close on Reverse) input int InpSlippage = 30; // 允許滑價(points) input int InpRetries = 3; // 報價變動時重試次數 input int InpMaxAgeSec = 120; // 進場訊號最久幾秒內有效 input double InpMaxSpreadPips = 0; // 點差上限(pips,0 = 不限) input double InpSyncTolPct = 2; // 部位同步:差距小於目標的幾 % 就不調整 input int InpSyncMaxAgeSec = 900; // 部位同步:超過幾秒的訊號只減碼、不加碼(0 = 不限) input double InpMaxSyncPct = 1000; // 部位同步:目標名目超過部位基準幾 % 就不做(0 = 不限) input string InpSymPrefix = ""; // 商品代號前綴 input string InpSymSuffix = ""; // 商品代號後綴(例如 .r、.cash) input string InpSymMap = ""; // 商品對照,例:US100=US100.cash;XAUUSD=GOLD input group "風控" input double InpDailyLossPct = 0; // 當天虧損達起始權益的 % 就停止開新倉(0 = 關) input bool InpDailyFlatten = false; // 達到時也全部平倉 input int InpDayStartHour = 0; // 換日:0 = 跟網站的「一天」(FTMO 布拉格午夜,夏令時間自動);1~23 = 改用 MT5 伺服器時間的幾點 input double InpMaxOrderPct = 1000; // 安全上限:單筆名目最多是權益的幾 %(0 = 不限) input double InpMaxTotalPct = 2500; // 安全上限:所有部位合計名目最多是權益的幾 %(0 = 不限) input int InpMaxEntriesMin = 30; // 安全上限:1 分鐘內最多送幾筆新倉/加碼/掛單(0 = 不限) input group "通知" input bool InpPushAlerts = true; // 連不上網站/被拒絕時推播到手機 MT5(要在 MT5 選項 → 通知 填 MetaQuotes ID) input int InpAlertAfterSec = 60; // 連續失敗幾秒才通知(短暫斷線不吵你) //──────────────────────────── 狀態 ──────────────────────────── struct SSig { string id; long age; string cmd; string sym; string k[]; string v[]; }; struct SRes { string status; long retcode; ulong ticket; double price; double volume; string msg; }; struct SManage { ulong ticket; double beTrig; double beOff; double trTrig; double trDist; double trStep; bool beDone; datetime expire; // 掛單到期(0 = 不會到期) ulong lastTry; // 上次「失敗」的時間(不存檔);0 = 可以馬上試 double wantSL; // 進場時沒掛上的停損(0 = 沒有) double wantTP; // 進場時沒掛上的停利 ulong born; // 加入的時間(不存檔):剛成交時部位清單可能還沒更新,1 分鐘內找不到也先不移除 int fails; // 連續失敗幾次(不存檔):重試間隔 10 秒起跳、每次加倍,最多 5 分鐘 ulong lastMod; // 上次成功改停損的時間(不存檔):移動停損至少隔 5 秒才再改 }; CTrade g_trade; string g_base = ""; string g_acks[]; string g_doneId[]; string g_doneAck[]; ulong g_tagT[]; string g_tagC[]; SManage g_man[]; long g_magics[]; ulong g_lastPoll = 0, g_lastHb = 0, g_lastClean = 0; int g_backoff = 0; bool g_paused = false; bool g_dayBlocked = false; bool g_dayFlattened = false; int g_dayKey = 0; double g_dayStart = 0; int g_dayOff = 0; // 換日時區(網站的 BRIDGE_DAY_TZ,FTMO = 布拉格)的 UTC 偏移秒數:網站每次輪詢的 CFG 帶來 bool g_dayOffOk = false; // 收過網站的換日時區了沒(還沒收到:照歐盟夏令時間規則算布拉格) long g_dayStartUtc = 0; // 網站給的:它的「今天」從什麼時候開始(UTC 秒;夏令時間切換那天也準) int g_dayStartKey = 0; // 上面那個是哪一天的(跟 DayKey() 一樣才用) bool g_polledOk = false; // 這次啟動後輪詢成功過了沒:之前不做預約的單(還不知道網站的暫停設定、網站識別碼) ulong g_pollAt = 0; // 這批訊號從網站拿到的時間:排在後面才執行的,等的時間也算進訊號年齡 string g_status = "啟動中"; string g_lastErr = ""; long g_processed = 0; ulong g_lastRtt = 0; string g_lastSignal = ""; string g_login = "0"; bool g_ready = false; // MT5 已連上券商、部位已同步、存檔已讀進來 ulong g_connSince = 0; string g_instance = ""; // 網站資料庫的識別碼:網站重裝後訊號編號會從頭算,去重要分開 ulong g_lastFlatTry = 0; ulong g_knownDeals[]; // 這個 EA 自己確認過的成交(結果不明時排除) ulong g_knownOrders[]; // 這個 EA 自己掛上的掛單(結果不明時排除) string g_session = ""; // 這次啟動的身分碼:網站用它擋「同一個授權碼掛了兩個 EA」 ulong g_failSince = 0; // 這一輪連線失敗從什麼時候開始(0 = 正常) bool g_failNotified = false; string g_schLine[]; // 預約的訊號(原始 S 行;at= 的時間到才執行) long g_schAt[]; // 預約時間(UTC 毫秒) string g_schKey[]; // 去重用的 key long g_srvOffset = 0; // 網站時鐘(UTC 毫秒)− GetTickCount64():用心跳量,預約的單照這個時鐘準時執行 ulong g_srvRtt = 0; // 量時鐘那次的來回時間(越短越準) ulong g_srvAt = 0; // 上次量時鐘的時間(0 = 還沒量過) long g_pollOver = 300; // 一次輪詢本身(連線、來回)要多少毫秒:預約的單快到時,長輪詢要提早這麼多回來 bool g_runDue = false; // RunScheduled 正在做到期的單:HandleSignal 不要再預約一次(時鐘還沒對準時只有 1 秒精度) string g_cfgMagics = ";"; // 網站說這個帳戶訂閱的策略 magic(;1000101;1000102;):這些不是直接警報 string g_capNote = ""; // 這筆超過 EA 單筆上限被截的說明(附在回報前面) bool g_owner = true; // 網站回 409(同一個授權碼另一個 EA 在用)就 false:不顧單、不寫存檔,免得蓋掉那個 EA 的 string g_syms = ""; // 網站要檢查的商品(訂閱用到的,分號隔開) bool g_symDirty = false; // 清單變了:下一次心跳就回報 ulong g_lastSymRep = 0; // 上次回報商品規格的時間 uint g_closeRc = 0; // 這個訊號最近一次平倉失敗的回傳碼(回報網站,休市/斷線它會自動重試) bool g_dayOrdersClean = true; // 每日風控觸發後,掛單刪乾淨了沒 ulong g_lastOrdTry = 0; ulong g_entryTs[]; // 最近 1 分鐘送出的新倉/加碼/掛單(安全上限用) ulong g_capAlertAt = 0; // 上次推播「安全上限擋單」的時間(10 分鐘最多一則) //──────────────────────────── 小工具 ──────────────────────────── string Trim(string s) { StringTrimLeft(s); StringTrimRight(s); return s; } string Lower(string s) { StringToLower(s); return s; } //──────────────────────────── 換日(每日虧損保護用)──────────────────────────── // 布拉格的夏令時間(歐盟規則):三月最後一個星期日 01:00 UTC 到十月最後一個星期日 01:00 UTC long LastSundayUtc(const int year, const int mon) { MqlDateTime d; ZeroMemory(d); d.year = year; d.mon = mon; d.day = 31; // 三月、十月都有 31 天 d.hour = 1; long t = (long)StructToTime(d); MqlDateTime x; TimeToStruct((datetime)t, x); return t - (long)x.day_of_week * 86400; // 往回推到星期日(day_of_week:0 = 星期日) } // 布拉格在某個時刻(UTC 秒)的偏移 long PragueOffAt(const long u) { MqlDateTime d; TimeToStruct((datetime)u, d); return (u >= LastSundayUtc(d.year, 3) && u < LastSundayUtc(d.year, 10)) ? 7200 : 3600; } // 現在的 UTC 秒數:量過網站的時鐘就用網站的(電腦的時鐘或 Windows 時區設錯也不影響換日),還沒量過用電腦的 long UtcNow() { if(g_srvAt == 0) return (long)TimeGMT(); return ((long)GetTickCount64() + g_srvOffset) / 1000; } // 「一天」現在的時區偏移(秒):網站告訴我們的(BRIDGE_DAY_TZ);還沒收到就用布拉格(FTMO) long DayOffset() { if(g_dayOffOk) return g_dayOff; return PragueOffAt(UtcNow()); } int DayKey() { MqlDateTime d; if(InpDayStartHour != 0) TimeToStruct(TimeCurrent() - (datetime)(InpDayStartHour * 3600), d); else TimeToStruct((datetime)(UtcNow() + DayOffset()), d); // 跟網站的每日紀錄同一個「一天」(FTMO:布拉格午夜) return d.year * 10000 + d.mon * 100 + d.day; } // 今天從什麼時候開始(MT5 伺服器時間;成交紀錄的時間是伺服器時間) datetime DayStartServer() { if(InpDayStartHour != 0) { long sh = (long)TimeCurrent() - (long)InpDayStartHour * 3600; return (datetime)(sh - sh % 86400 + (long)InpDayStartHour * 3600); } long now = UtcNow(), off = DayOffset(); long srvOff = (long)MathRound(((long)TimeTradeServer() - (long)TimeGMT()) / 900.0) * 900; // 伺服器的時區(取整到 15 分) if(g_dayStartUtc > 0 && g_dayStartKey == DayKey()) return (datetime)(g_dayStartUtc + srvOff); // 網站算好的(夏令時間切換那天也準) long local = now + off; long midLocal = local - local % 86400; long offMid = g_dayOffOk ? off : PragueOffAt(midLocal - off); // 切換那天,午夜時的偏移跟現在不一樣 return (datetime)(midLocal - offMid + srvOff); } // 換日之後已經實現的損益(平倉損益+手續費+隔夜費+其他費用;入金、出金不算) double ClosedToday() { datetime from = DayStartServer(); if(!HistorySelect(from, TimeTradeServer() + 86400)) return 0; double sum = 0; int n = HistoryDealsTotal(); for(int i = 0; i < n; i++) { ulong t = HistoryDealGetTicket(i); if(t == 0) continue; long typ = HistoryDealGetInteger(t, DEAL_TYPE); if(typ != DEAL_TYPE_BUY && typ != DEAL_TYPE_SELL) continue; if((datetime)HistoryDealGetInteger(t, DEAL_TIME) < from) continue; sum += HistoryDealGetDouble(t, DEAL_PROFIT) + HistoryDealGetDouble(t, DEAL_SWAP) + HistoryDealGetDouble(t, DEAL_COMMISSION) + HistoryDealGetDouble(t, DEAL_FEE); } return sum; } // 放進 HTTP 標頭的值:只留看得見的 ASCII(券商伺服器名稱),不會帶進換行 string HeaderSafe(const string v) { string out = ""; int n = (int)MathMin(StringLen(v), 64); for(int i = 0; i < n; i++) { ushort c = StringGetCharacter(v, i); if(c >= 32 && c <= 126) out += ShortToString(c); } return Trim(out); } string Clean(string s) { StringReplace(s, ",", " "); StringReplace(s, "\r", " "); StringReplace(s, "\n", " "); StringReplace(s, "|", " "); return s; } string D2S(double x, int digits = 8) { string s = DoubleToString(x, digits); if(StringFind(s, ".") >= 0) { int n = StringLen(s); while(n > 0 && StringGetCharacter(s, n - 1) == '0') n--; if(n > 0 && StringGetCharacter(s, n - 1) == '.') n--; s = StringSubstr(s, 0, n); } if(s == "" || s == "-0") s = "0"; return s; } bool Has(SSig &s, const string key) { for(int i = 0; i < ArraySize(s.k); i++) if(s.k[i] == key) return true; return false; } string PS(SSig &s, const string key, const string def = "") { for(int i = 0; i < ArraySize(s.k); i++) if(s.k[i] == key) return s.v[i]; return def; } double PD(SSig &s, const string key, const double def = 0.0) { for(int i = 0; i < ArraySize(s.k); i++) if(s.k[i] == key) return StringToDouble(s.v[i]); return def; } void Res(SRes &r, const string status, const long rc, const string msg) { r.status = status; r.retcode = rc; r.msg = msg; } bool IsHedging() { return AccountInfoInteger(ACCOUNT_MARGIN_MODE) == ACCOUNT_MARGIN_MODE_RETAIL_HEDGING; } double Pip(const string sym) { return 10.0 * SymbolInfoDouble(sym, SYMBOL_POINT); } double VolStep(const string sym) { double st = SymbolInfoDouble(sym, SYMBOL_VOLUME_STEP); return st > 0 ? st : 0.01; } int VolDigits(const string sym) { double st = VolStep(sym); int d = 0; while(d < 8 && MathAbs(st - MathRound(st)) > 1e-9) { st *= 10.0; d++; } return d; } bool IsStrategyMagic(const long m) { return StringFind(g_cfgMagics, ";" + IntegerToString(m) + ";") >= 0; } // 失敗後多久再試:10 秒、20 秒、40 秒…最多 5 分鐘(休市、停損太近時不要每 5 秒打一次券商) ulong Backoff(const int fails) { ulong w = 5000; for(int k = 0; k < fails && w < 300000; k++) w *= 2; if(w > 300000) w = 300000; return w; } // 無條件捨去到最小單位;小於最小手數回傳 0 double NormLots(const string sym, double lots) { if(lots <= 0) return 0; double st = VolStep(sym); double vmin = SymbolInfoDouble(sym, SYMBOL_VOLUME_MIN); double cap = InpMaxLots > 0 ? InpMaxLots : lots; lots = MathMin(lots, cap); lots = MathFloor(lots / st + 1e-7) * st; if(lots < vmin - 1e-9) return 0; return NormalizeDouble(lots, VolDigits(sym)); } // 四捨五入到最小單位(減碼用) double RoundLots(const string sym, double lots) { if(lots <= 0) return 0; double st = VolStep(sym); return NormalizeDouble(MathRound(lots / st) * st, VolDigits(sym)); } double NormPrice(const string sym, double price) { double ts = SymbolInfoDouble(sym, SYMBOL_TRADE_TICK_SIZE); if(ts > 0) price = MathRound(price / ts) * ts; return NormalizeDouble(price, (int)SymbolInfoInteger(sym, SYMBOL_DIGITS)); } // 往上或往下對齊跳動單位(把停損停利推離現價時用,免得四捨五入又推回太近) double NormPriceDir(const string sym, double price, const bool up) { double ts = SymbolInfoDouble(sym, SYMBOL_TRADE_TICK_SIZE); if(ts > 0) price = (up ? MathCeil(price / ts - 1e-9) : MathFloor(price / ts + 1e-9)) * ts; return NormalizeDouble(price, (int)SymbolInfoInteger(sym, SYMBOL_DIGITS)); } double Base() { if(InpBase == BR_BASE_BALANCE) return AccountInfoDouble(ACCOUNT_BALANCE); if(InpBase == BR_BASE_FIXED) return InpBaseFixed; return AccountInfoDouble(ACCOUNT_EQUITY); } string BaseName() { if(InpBase == BR_BASE_BALANCE) return "balance"; if(InpBase == BR_BASE_FIXED) return "fixed"; return "equity"; } double SpreadPips(const string sym) { MqlTick tk; if(!SymbolInfoTick(sym, tk)) return 0; double pip = Pip(sym); return pip > 0 ? (tk.ask - tk.bid) / pip : 0; } // 名目:1 手對應多少帳戶幣別(價格 × 合約大小,含匯率換算) double NotionalPerLot(const string sym, const double price) { double p = 0; if(price > 0 && OrderCalcProfit(ORDER_TYPE_BUY, sym, 1.0, price, price * 1.01, p) && p > 0) return p * 100.0; double tv = SymbolInfoDouble(sym, SYMBOL_TRADE_TICK_VALUE); double ts = SymbolInfoDouble(sym, SYMBOL_TRADE_TICK_SIZE); if(tv > 0 && ts > 0) return price * tv / ts; return 0; } // 1 手打到停損會虧多少(帳戶幣別) double LossPerLot(const string sym, const bool isBuy, const double entry, const double sl) { double p = 0; if(OrderCalcProfit(isBuy ? ORDER_TYPE_BUY : ORDER_TYPE_SELL, sym, 1.0, entry, sl, p) && p != 0) return MathAbs(p); double tv = SymbolInfoDouble(sym, SYMBOL_TRADE_TICK_VALUE); double ts = SymbolInfoDouble(sym, SYMBOL_TRADE_TICK_SIZE); if(ts > 0) return MathAbs(entry - sl) / ts * tv; return 0; } bool IsDone(const uint rc) { return rc == TRADE_RETCODE_DONE || rc == TRADE_RETCODE_DONE_PARTIAL || rc == TRADE_RETCODE_PLACED; } bool IsRetryable(const uint rc) { return rc == TRADE_RETCODE_REQUOTE || rc == TRADE_RETCODE_PRICE_CHANGED || rc == TRADE_RETCODE_PRICE_OFF || rc == TRADE_RETCODE_TIMEOUT || rc == TRADE_RETCODE_CONNECTION || rc == TRADE_RETCODE_TOO_MANY_REQUESTS || rc == 0; } // 逾時、斷線、沒回應:單子可能其實已經成交,重試前要先確認 bool Uncertain(const uint rc) { return rc == TRADE_RETCODE_TIMEOUT || rc == TRADE_RETCODE_CONNECTION || rc == 0; } // 記下這個 EA 自己確認過的成交/掛單編號(最多 300 筆) void Remember(ulong &list[], const ulong t) { if(t == 0) return; int n = ArraySize(list); if(n >= 300) { for(int i = 0; i < n - 1; i++) list[i] = list[i + 1]; n--; } ArrayResize(list, n + 1); list[n] = t; } bool Known(const ulong &list[], const ulong t) { for(int i = 0; i < ArraySize(list); i++) if(list[i] == t) return true; return false; } // EA 送出的進場成交:同商品、magic、方向,sinceMsc 之後(停損停利打到的、平倉的都不算) bool EntryDeal(const ulong d, const string sym, const long magic, const bool isBuy, const long sinceMsc) { if(HistoryDealGetString(d, DEAL_SYMBOL) != sym || HistoryDealGetInteger(d, DEAL_MAGIC) != magic) return false; if(HistoryDealGetInteger(d, DEAL_TIME_MSC) < sinceMsc || HistoryDealGetInteger(d, DEAL_REASON) != DEAL_REASON_EXPERT) return false; long en = HistoryDealGetInteger(d, DEAL_ENTRY); if(en != DEAL_ENTRY_IN && en != DEAL_ENTRY_INOUT) return false; // 反手時剛平掉反向部位的那筆也是同方向,但它是出場 long dt = HistoryDealGetInteger(d, DEAL_TYPE); return isBuy ? dt == DEAL_TYPE_BUY : dt == DEAL_TYPE_SELL; } // 結果不明的市價單:找還沒算過的新進場成交;同一張單分好幾筆成交時加總手數、算均價,全部記為算過 bool FindNewDeal(const string sym, const long magic, const bool isBuy, const long sinceMsc, ulong &deal, double &vol, double &px, ulong &posId) { if(!HistorySelect((datetime)(sinceMsc / 1000) - 5, TimeTradeServer() + 3600)) return false; int n = HistoryDealsTotal(); for(int i = n - 1; i >= 0; i--) { ulong d = HistoryDealGetTicket(i); if(d == 0 || Known(g_knownDeals, d) || !EntryDeal(d, sym, magic, isBuy, sinceMsc)) continue; long ord = HistoryDealGetInteger(d, DEAL_ORDER); if(Known(g_knownOrders, (ulong)ord)) continue; // 之前那張市價單的其他成交、或 EA 自己的掛單被觸發 double pv = 0; vol = 0; for(int j = 0; j < n; j++) { ulong d2 = HistoryDealGetTicket(j); if(d2 == 0 || Known(g_knownDeals, d2) || HistoryDealGetInteger(d2, DEAL_ORDER) != ord || !EntryDeal(d2, sym, magic, isBuy, sinceMsc)) continue; double v2 = HistoryDealGetDouble(d2, DEAL_VOLUME); vol += v2; pv += v2 * HistoryDealGetDouble(d2, DEAL_PRICE); Remember(g_knownDeals, d2); } Remember(g_knownOrders, (ulong)ord); deal = d; px = vol > 0 ? pv / vol : HistoryDealGetDouble(d, DEAL_PRICE); posId = (ulong)HistoryDealGetInteger(d, DEAL_POSITION_ID); return true; } return false; } // 逾時/斷線:最多等 6 秒,從成交紀錄確認到底有沒有成交 bool ConfirmDeal(const string sym, const long magic, const bool isBuy, const long sinceMsc, ulong &deal, double &vol, double &px, ulong &posId) { for(int w = 0; w < 12; w++) { Sleep(500); if(FindNewDeal(sym, magic, isBuy, sinceMsc, deal, vol, px, posId)) return true; } return false; } bool TradeAllowed(SRes &r) { if(!TerminalInfoInteger(TERMINAL_TRADE_ALLOWED) || !MQLInfoInteger(MQL_TRADE_ALLOWED)) { Res(r, "failed", 0, "MT5 沒開「演算法交易」(工具列按鈕或 EA 設定的允許交易)"); return false; } if(!AccountInfoInteger(ACCOUNT_TRADE_ALLOWED) || !AccountInfoInteger(ACCOUNT_TRADE_EXPERT)) { Res(r, "failed", 0, "這個帳戶不允許 EA 交易(投資人密碼登入?)"); return false; } return true; } string FilePath(const string what) { return DIR_NAME + "\\" + g_login + "_" + what + ".txt"; } void SaveMagics() { int h = FileOpen(FilePath("magics"), FILE_WRITE | FILE_TXT | FILE_ANSI, '\t', CP_UTF8); if(h == INVALID_HANDLE) return; for(int i = 0; i < ArraySize(g_magics); i++) FileWriteString(h, IntegerToString(g_magics[i]) + "\r\n"); FileClose(h); } void LoadMagics() { ArrayResize(g_magics, 0); int h = FileOpen(FilePath("magics"), FILE_READ | FILE_TXT | FILE_ANSI, '\t', CP_UTF8); if(h == INVALID_HANDLE) return; while(!FileIsEnding(h)) { string line = Trim(FileReadString(h)); if(line == "") continue; long m = StringToInteger(line); bool seen = false; for(int i = 0; i < ArraySize(g_magics); i++) if(g_magics[i] == m) seen = true; if(!seen) { int n = ArraySize(g_magics); ArrayResize(g_magics, n + 1); g_magics[n] = m; } } FileClose(h); } // 記住這個 EA 下過單的 magic(flatten 沒指定 magic 時用),存檔免得重開後忘記 void RememberMagic(const long m) { for(int i = 0; i < ArraySize(g_magics); i++) if(g_magics[i] == m) return; int n = ArraySize(g_magics); ArrayResize(g_magics, n + 1); g_magics[n] = m; if(g_ready) SaveMagics(); } void PrepTrade(const string sym, const long magic) { g_trade.SetExpertMagicNumber((ulong)magic); g_trade.SetDeviationInPoints((ulong)MathMax(0, InpSlippage)); g_trade.SetTypeFillingBySymbol(sym); } //──────────────────────────── 商品代號 ──────────────────────────── string ResolveSymbol(const string raw) { string sym = raw; string maps[]; int n = StringSplit(InpSymMap, ';', maps); bool mapped = false; for(int i = 0; i < n; i++) { string kv[]; if(StringSplit(maps[i], '=', kv) == 2 && Trim(kv[0]) == raw) { sym = Trim(kv[1]); mapped = true; break; } } if(!mapped) { string full = InpSymPrefix + raw + InpSymSuffix; if(SymbolSelect(full, true)) return full; } if(SymbolSelect(sym, true)) return sym; return ""; } //──────────────────────────── 單子註解、BE/追蹤設定(存檔)──────────────────────────── void SaveTags() { int h = FileOpen(FilePath("tags"), FILE_WRITE | FILE_TXT | FILE_ANSI, '\t', CP_UTF8); if(h == INVALID_HANDLE) return; for(int i = 0; i < ArraySize(g_tagT); i++) FileWriteString(h, IntegerToString((long)g_tagT[i]) + "\t" + g_tagC[i] + "\r\n"); FileClose(h); } void LoadTags() { ArrayResize(g_tagT, 0); ArrayResize(g_tagC, 0); int h = FileOpen(FilePath("tags"), FILE_READ | FILE_TXT | FILE_ANSI, '\t', CP_UTF8); if(h == INVALID_HANDLE) return; while(!FileIsEnding(h)) { string line = FileReadString(h); int p = StringFind(line, "\t"); if(p <= 0) continue; int n = ArraySize(g_tagT); ArrayResize(g_tagT, n + 1); ArrayResize(g_tagC, n + 1); g_tagT[n] = (ulong)StringToInteger(StringSubstr(line, 0, p)); g_tagC[n] = Trim(StringSubstr(line, p + 1)); } FileClose(h); } void AddTag(const ulong ticket, const string cm) { if(ticket == 0 || cm == "") return; for(int i = 0; i < ArraySize(g_tagT); i++) if(g_tagT[i] == ticket) { g_tagC[i] = cm; SaveTags(); return; } int n = ArraySize(g_tagT); ArrayResize(g_tagT, n + 1); ArrayResize(g_tagC, n + 1); g_tagT[n] = ticket; g_tagC[n] = cm; SaveTags(); } // 單子的 comment:先看 EA 自己記的(券商可能改掉註解),沒有才用券商的 string TagOf(const ulong ticket, const string brokerComment) { for(int i = 0; i < ArraySize(g_tagT); i++) if(g_tagT[i] == ticket) return g_tagC[i]; return brokerComment; } void SaveManage() { int h = FileOpen(FilePath("manage"), FILE_WRITE | FILE_TXT | FILE_ANSI, '\t', CP_UTF8); if(h == INVALID_HANDLE) return; for(int i = 0; i < ArraySize(g_man); i++) FileWriteString(h, IntegerToString((long)g_man[i].ticket) + "\t" + D2S(g_man[i].beTrig) + "\t" + D2S(g_man[i].beOff) + "\t" + D2S(g_man[i].trTrig) + "\t" + D2S(g_man[i].trDist) + "\t" + D2S(g_man[i].trStep) + "\t" + (g_man[i].beDone ? "1" : "0") + "\t" + IntegerToString((long)g_man[i].expire) + "\t" + D2S(g_man[i].wantSL) + "\t" + D2S(g_man[i].wantTP) + "\r\n"); FileClose(h); } void LoadManage() { ArrayResize(g_man, 0); int h = FileOpen(FilePath("manage"), FILE_READ | FILE_TXT | FILE_ANSI, '\t', CP_UTF8); if(h == INVALID_HANDLE) return; while(!FileIsEnding(h)) { string f[]; if(StringSplit(FileReadString(h), '\t', f) < 8) continue; int n = ArraySize(g_man); ArrayResize(g_man, n + 1); g_man[n].ticket = (ulong)StringToInteger(f[0]); g_man[n].beTrig = StringToDouble(f[1]); g_man[n].beOff = StringToDouble(f[2]); g_man[n].trTrig = StringToDouble(f[3]); g_man[n].trDist = StringToDouble(f[4]); g_man[n].trStep = StringToDouble(f[5]); g_man[n].beDone = (Trim(f[6]) == "1"); g_man[n].expire = (datetime)StringToInteger(Trim(f[7])); g_man[n].lastTry = 0; g_man[n].wantSL = ArraySize(f) >= 10 ? StringToDouble(f[8]) : 0; g_man[n].wantTP = ArraySize(f) >= 10 ? StringToDouble(Trim(f[9])) : 0; g_man[n].born = GetTickCount64(); // 剛啟動時部位清單可能還沒載入:1 分鐘內找不到先不移除 g_man[n].fails = 0; g_man[n].lastMod = 0; } FileClose(h); } void AddManage(const ulong ticket, SSig &s) { double be = PD(s, "be_trigger"), tr = PD(s, "trail_trig"); double expMin = PD(s, "expiry"); if(ticket == 0 || (be <= 0 && tr <= 0 && expMin <= 0)) return; int n = -1; for(int i = 0; i < ArraySize(g_man); i++) // 同一張已經有紀錄(例如停損停利待補)→ 合併成一筆 if(g_man[i].ticket == ticket) n = i; if(n < 0) { n = ArraySize(g_man); ArrayResize(g_man, n + 1); g_man[n].ticket = ticket; g_man[n].lastTry = 0; g_man[n].wantSL = 0; g_man[n].wantTP = 0; g_man[n].fails = 0; g_man[n].lastMod = 0; } g_man[n].beTrig = be; g_man[n].beOff = PD(s, "be_offset"); g_man[n].trTrig = tr; g_man[n].trDist = PD(s, "trail_dist"); g_man[n].trStep = PD(s, "trail_step"); g_man[n].beDone = false; g_man[n].born = GetTickCount64(); g_man[n].expire = (datetime)0; if(expMin > 0) g_man[n].expire = (datetime)(TimeCurrent() + (long)(expMin * 60.0)); SaveManage(); } // 停損停利沒掛上:記下來,Manage() 自動重試(推離現價後再掛;間隔漸增,價格越過停損就每 5 秒試著平倉) void WantStops(const ulong ticket, const double sl, const double tp) { if(ticket == 0 || (sl <= 0 && tp <= 0)) return; int k = -1; for(int i = 0; i < ArraySize(g_man); i++) if(g_man[i].ticket == ticket) k = i; if(k < 0) { k = ArraySize(g_man); ArrayResize(g_man, k + 1); g_man[k].ticket = ticket; g_man[k].beTrig = 0; g_man[k].beOff = 0; g_man[k].trTrig = 0; g_man[k].trDist = 0; g_man[k].trStep = 0; g_man[k].beDone = false; g_man[k].expire = (datetime)0; g_man[k].fails = 0; g_man[k].lastMod = 0; } g_man[k].wantSL = sl; g_man[k].wantTP = tp; g_man[k].lastTry = 0; g_man[k].born = GetTickCount64(); SaveManage(); } void RegisterTicket(const ulong ticket, const string cm, SSig &s) { AddTag(ticket, cm); AddManage(ticket, s); } //──────────────────────────── 已執行的訊號(去重,存檔)──────────────────────────── void SaveDone() { string fin = FilePath("done"), tmp = fin + ".tmp"; // 先寫暫存檔再換名:寫到一半當機不會留下壞掉的去重紀錄 int h = FileOpen(tmp, FILE_WRITE | FILE_TXT | FILE_ANSI, '\t', CP_UTF8); if(h == INVALID_HANDLE) return; for(int i = 0; i < ArraySize(g_doneId); i++) FileWriteString(h, g_doneId[i] + "\t" + g_doneAck[i] + "\r\n"); FileClose(h); if(!FileMove(tmp, 0, fin, FILE_REWRITE)) Print("[Bridge] 去重紀錄存檔失敗(錯誤 ", GetLastError(), ")"); } void LoadDone() { ArrayResize(g_doneId, 0); ArrayResize(g_doneAck, 0); int h = FileOpen(FilePath("done"), FILE_READ | FILE_TXT | FILE_ANSI, '\t', CP_UTF8); if(h == INVALID_HANDLE) return; while(!FileIsEnding(h)) { string line = FileReadString(h); int p = StringFind(line, "\t"); if(p <= 0) continue; int n = ArraySize(g_doneId); ArrayResize(g_doneId, n + 1); ArrayResize(g_doneAck, n + 1); g_doneId[n] = StringSubstr(line, 0, p); g_doneAck[n] = Trim(StringSubstr(line, p + 1)); } FileClose(h); } bool FindDone(const string id, string &ack) { for(int i = ArraySize(g_doneId) - 1; i >= 0; i--) if(g_doneId[i] == id) { ack = g_doneAck[i]; return true; } return false; } void RememberDone(const string id, const string ack) { for(int i = ArraySize(g_doneId) - 1; i >= 0; i--) if(g_doneId[i] == id) { g_doneAck[i] = ack; SaveDone(); return; } int n = ArraySize(g_doneId); if(n >= 300) { for(int i = 0; i < n - 1; i++) { g_doneId[i] = g_doneId[i + 1]; g_doneAck[i] = g_doneAck[i + 1]; } n--; } ArrayResize(g_doneId, n + 1); ArrayResize(g_doneAck, n + 1); g_doneId[n] = id; g_doneAck[n] = ack; SaveDone(); } //──────────────────────────── 停損停利、手數 ──────────────────────────── bool HasSL(SSig &s) { return Has(s, "sl_pips") || Has(s, "sl_price") || Has(s, "sl_pct") || Has(s, "sl"); } bool HasTP(SSig &s) { return Has(s, "tp_pips") || Has(s, "tp_price") || Has(s, "tp_pct") || Has(s, "tp"); } // 方向 dir:+1 停利那側、−1 停損那側(以多單為準,空單會反過來) double StopPrice(SSig &s, const string leg, const string sym, const bool isBuy, const double entry) { double pip = Pip(sym); double d = 0, px = 0; bool above = (leg == "tp") == isBuy; // 多單停利在上、停損在下 if(Has(s, leg + "_price")) px = PD(s, leg + "_price"); else { if(Has(s, leg + "_pips")) d = PD(s, leg + "_pips") * pip; else if(Has(s, leg + "_pct")) d = entry * PD(s, leg + "_pct") / 100.0; else if(Has(s, leg)) { double v = PD(s, leg); if(InpTgtType == BR_TGT_PRICE) px = v; else if(InpTgtType == BR_TGT_PCT) d = entry * v / 100.0; else d = v * pip; } if(d > 0) px = above ? entry + d : entry - d; } if(px <= 0) return 0; return NormPrice(sym, px); } // entry:算距離的基準(市價單 = 進場價、掛單 = 掛單價、改停損 = 開倉價) // ref:券商檢查停損停利用的價(多單看 Bid、空單看 Ask;掛單看掛單價) bool CalcStops(SSig &s, const string sym, const bool isBuy, const double entry, const double ref, double &sl, double &tp, string &err) { sl = StopPrice(s, "sl", sym, isBuy, entry); tp = StopPrice(s, "tp", sym, isBuy, entry); if(sl > 0 && ((isBuy && sl >= ref) || (!isBuy && sl <= ref))) { err = "停損價在錯的一邊(" + D2S(sl) + ",現價 " + D2S(ref) + ")"; return false; } if(tp > 0 && ((isBuy && tp <= ref) || (!isBuy && tp >= ref))) { err = "停利價在錯的一邊(" + D2S(tp) + ",現價 " + D2S(ref) + ")"; return false; } double pt = SymbolInfoDouble(sym, SYMBOL_POINT); double minDist = (double)SymbolInfoInteger(sym, SYMBOL_TRADE_STOPS_LEVEL) * pt; if(minDist > 0) { minDist += pt; // 多留 1 point,免得剛好壓在邊界上被拒 if(sl > 0 && MathAbs(ref - sl) < minDist) sl = NormPriceDir(sym, isBuy ? ref - minDist : ref + minDist, !isBuy); if(tp > 0 && MathAbs(tp - ref) < minDist) tp = NormPriceDir(sym, isBuy ? ref + minDist : ref - minDist, isBuy); } return true; } bool LossLots(const string sym, const bool isBuy, const double entry, const double sl, const double budget, double &lots, string &err) { if(sl <= 0) { err = "依停損算手數,但沒有停損"; return false; } double lpl = LossPerLot(sym, isBuy, entry, sl); if(lpl <= 0) { err = "算不出每手虧損"; return false; } lots = budget / lpl; return true; } bool CalcVolumeRaw(SSig &s, const string sym, const bool isBuy, const double entry, const double sl, double &lots, string &err) { double bal = AccountInfoDouble(ACCOUNT_BALANCE), eq = AccountInfoDouble(ACCOUNT_EQUITY); ENUM_ORDER_TYPE ot = isBuy ? ORDER_TYPE_BUY : ORDER_TYPE_SELL; lots = 0; if(Has(s, "vol_lots")) { lots = PD(s, "vol_lots"); return true; } if(Has(s, "lots_per_1k")) { lots = PD(s, "lots_per_1k") * Base() / 1000.0; double ref = PD(s, "ref_pv"); if(ref > 0) // 策略的手數照參考券商(FTMO)的合約規格算:換成這個券商的規格 { double pv = entry > 0 ? NotionalPerLot(sym, entry) / entry : 0; // 1 手、價格動 1 的價值(帳戶幣別) if(pv <= 0) { err = "算不出 " + sym + " 每手的價值,不知道怎麼換算合約規格"; return false; } double k = ref / pv; // 含匯率(帳戶不是美元時,pv 是帳戶幣別) double cs = SymbolInfoDouble(sym, SYMBOL_TRADE_CONTRACT_SIZE); if(cs > 0 && SymbolInfoString(sym, SYMBOL_CURRENCY_PROFIT) == "USD") { double spec = ref / cs; // 只看合約規格(不含匯率) double fx = AccountInfoString(ACCOUNT_CURRENCY) == "USD" ? 1.0 : cs / pv; // 1 美元 = 幾單位帳戶幣別 if(MathAbs(spec - 1.0) <= 0.02) spec = 1.0; // 同樣的規格:不要因為進位少一個最小單位 else PrintFormat("[Bridge] %s 的合約規格跟策略的參考不同(合約大小 %.6g,參考 %.6g):手數 × %.4g", sym, cs, ref, spec); if(spec < 0.05 || spec > 20) { err = sym + " 的合約規格跟策略的參考差太多(× " + D2S(spec, 4) + "):請確認商品對照沒有對錯商品"; return false; } k = spec * fx; } else if(MathAbs(k - 1.0) <= 0.02) k = 1.0; lots *= k; } return true; } if(Has(s, "vol_pct_eq_notional")) { double npl = NotionalPerLot(sym, entry); if(npl <= 0) { err = "算不出名目"; return false; } lots = eq * PD(s, "vol_pct_eq_notional") / 100.0 / npl; return true; } if(Has(s, "vol_pct_bal_margin")) { double m = 0; if(!OrderCalcMargin(ot, sym, 1.0, entry, m) || m <= 0) { err = "算不出保證金"; return false; } lots = bal * PD(s, "vol_pct_bal_margin") / 100.0 / m; return true; } if(Has(s, "vol_pct_bal_loss")) return LossLots(sym, isBuy, entry, sl, bal * PD(s, "vol_pct_bal_loss") / 100.0, lots, err); if(Has(s, "vol_pct_eq_loss")) return LossLots(sym, isBuy, entry, sl, eq * PD(s, "vol_pct_eq_loss") / 100.0, lots, err); if(Has(s, "vol_pct_base_loss")) return LossLots(sym, isBuy, entry, sl, Base() * PD(s, "vol_pct_base_loss") / 100.0, lots, err); if(Has(s, "vol_dollar")) return LossLots(sym, isBuy, entry, sl, PD(s, "vol_dollar"), lots, err); if(Has(s, "risk")) { double r = PD(s, "risk"); switch(InpVolType) { case BR_VOL_PCT_BAL_LOSS: return LossLots(sym, isBuy, entry, sl, bal * r / 100.0, lots, err); case BR_VOL_PCT_EQ_LOSS: return LossLots(sym, isBuy, entry, sl, eq * r / 100.0, lots, err); case BR_VOL_DOLLAR_LOSS: return LossLots(sym, isBuy, entry, sl, r, lots, err); case BR_VOL_PCT_BAL_MARGIN: { double m = 0; if(!OrderCalcMargin(ot, sym, 1.0, entry, m) || m <= 0) { err = "算不出保證金"; return false; } lots = bal * r / 100.0 / m; return true; } case BR_VOL_PCT_EQ_NOTIONAL: { double npl = NotionalPerLot(sym, entry); if(npl <= 0) { err = "算不出名目"; return false; } lots = eq * r / 100.0 / npl; return true; } default: lots = r; return true; } } if(InpDefaultLots > 0) { lots = InpDefaultLots; return true; } err = "訊息沒帶部位參數,EA 也沒設預設手數"; return false; } // 算手數,再套策略的單筆名目上限(max_pct,網站對有設上限的策略每一筆開倉都會帶,不管用哪種方式算部位): // Pine 的初始資金或合約大小填錯、或頻道 ID 外流被拿來亂下單時,擋掉大好幾倍的單 bool CalcVolume(SSig &s, const string sym, const bool isBuy, const double entry, const double sl, double &lots, string &err) { if(!CalcVolumeRaw(s, sym, isBuy, entry, sl, lots, err)) return false; double mx = PD(s, "max_pct"); if(mx > 0 && entry > 0 && lots > 0) { double npl = NotionalPerLot(sym, entry), b = Base(); if(b <= 0) { err = "部位基準是 0(EA 設定的「固定金額」沒填?),策略的單筆上限沒辦法檢查,沒有下單"; return false; } if(npl <= 0) { err = "算不出 " + sym + " 這筆的名目(沒有報價或匯率?),策略的單筆上限沒辦法檢查,沒有下單"; return false; } if(lots * npl / b * 100.0 > mx) { err = "這筆的名目是部位基準的 " + D2S(lots * npl / b * 100.0, 0) + "%,超過策略的上限 " + D2S(mx, 0) + "%:" + (Has(s, "lots_per_1k") ? "Pine 的「FTMO 帳戶初始資金」或合約大小可能填錯" : "策略送來的部位比平常大太多(頻道 ID 外流?)") + ",沒有下單"; return false; } } return true; } //──────────────────────────── 部位查詢 ──────────────────────────── bool MatchPos(const string sym, const long magic, const int type, const string cf) { if(sym != "" && PositionGetString(POSITION_SYMBOL) != sym) return false; if(PositionGetInteger(POSITION_MAGIC) != magic) return false; if(type >= 0 && PositionGetInteger(POSITION_TYPE) != type) return false; if(cf != "" && TagOf((ulong)PositionGetInteger(POSITION_TICKET), PositionGetString(POSITION_COMMENT)) != cf) return false; return true; } int CountPos(const string sym, const long magic, const int type) { int n = 0; for(int i = PositionsTotal() - 1; i >= 0; i--) { ulong t = PositionGetTicket(i); if(t > 0 && MatchPos(sym, magic, type, "")) n++; } return n; } double SumVol(const string sym, const long magic, const int type, const string cf = "") { double v = 0; for(int i = PositionsTotal() - 1; i >= 0; i--) { ulong t = PositionGetTicket(i); if(t > 0 && MatchPos(sym, magic, type, cf)) v += PositionGetDouble(POSITION_VOLUME); } return v; } // 剛成交的部位:對沖帳戶 = 下單的 ticket 或成交紀錄的 position id;淨額帳戶 = 那個商品唯一的部位。 // 找不到就回 0(不要猜,免得把設定掛到別張舊單上) ulong FindPositionTicket(const ulong orderTicket, const ulong dealTicket, const string sym) { for(int a = 0; a < 10; a++) { if(orderTicket > 0 && PositionSelectByTicket(orderTicket)) return orderTicket; if(dealTicket > 0 && HistoryDealSelect(dealTicket)) { ulong pid = (ulong)HistoryDealGetInteger(dealTicket, DEAL_POSITION_ID); if(pid > 0 && PositionSelectByTicket(pid)) return pid; } if(!IsHedging() && PositionSelect(sym)) return (ulong)PositionGetInteger(POSITION_TICKET); Sleep(50); } return 0; } // 逾時後確認有成交時,找那張新部位(對沖:sinceMsc 之後開的最新一張;淨額:那個商品的部位) ulong NewestPosition(const string sym, const long magic, const int type, const long sinceMsc) { if(!IsHedging()) return PositionSelect(sym) ? (ulong)PositionGetInteger(POSITION_TICKET) : 0; ulong best = 0; long bestTime = sinceMsc; for(int i = PositionsTotal() - 1; i >= 0; i--) { ulong t = PositionGetTicket(i); if(t == 0 || !MatchPos(sym, magic, type, "")) continue; long tm = PositionGetInteger(POSITION_TIME_MSC); if(tm >= bestTime) { bestTime = tm; best = t; } } return best; } //──────────────────────────── 平倉 ──────────────────────────── bool CloseTicket(const ulong t, string &err) { if(!PositionSelectByTicket(t)) return true; string sym = PositionGetString(POSITION_SYMBOL); PrepTrade(sym, PositionGetInteger(POSITION_MAGIC)); for(int a = 0; a <= InpRetries; a++) { if(g_trade.PositionClose(t) && IsDone(g_trade.ResultRetcode())) return true; uint rc = g_trade.ResultRetcode(); if(Uncertain(rc)) { for(int w = 0; w < 12 && PositionSelectByTicket(t) && TerminalInfoInteger(TERMINAL_CONNECTED); w++) Sleep(500); // 可能其實平掉了:等部位清單更新 } if(!PositionSelectByTicket(t)) return true; // 已經不在了(平掉了,或停損剛好打到) g_closeRc = rc; if(!TerminalInfoInteger(TERMINAL_CONNECTED)) { g_closeRc = TRADE_RETCODE_CONNECTION; err = "平倉失敗:MT5 跟券商斷線"; return false; // 斷線時一直重試只會卡住 EA;網站之後會重送 } if(!IsRetryable(rc)) { err = "平倉失敗 " + IntegerToString(rc) + " " + g_trade.ResultRetcodeDescription(); return false; } Sleep(250); } err = "平倉失敗(重試 " + IntegerToString(InpRetries) + " 次)"; return false; } // 部分平倉:對沖帳戶用 PositionClosePartial;淨額帳戶送反向單 bool CloseTicketPartial(const ulong t, const double vol, string &err) { if(!PositionSelectByTicket(t)) return true; string sym = PositionGetString(POSITION_SYMBOL); long magic = PositionGetInteger(POSITION_MAGIC); bool isBuy = PositionGetInteger(POSITION_TYPE) == POSITION_TYPE_BUY; double before = PositionGetDouble(POSITION_VOLUME); if(vol >= before - 1e-9) return CloseTicket(t, err); PrepTrade(sym, magic); for(int a = 0; a <= InpRetries; a++) { bool ok; if(IsHedging()) ok = g_trade.PositionClosePartial(t, vol); else ok = isBuy ? g_trade.Sell(vol, sym) : g_trade.Buy(vol, sym); uint rc = g_trade.ResultRetcode(); if(ok && IsDone(rc)) return true; g_closeRc = rc; if(Uncertain(rc)) { for(int w = 0; w < 12 && TerminalInfoInteger(TERMINAL_CONNECTED); w++) // 可能其實已經成交:最多等 6 秒看部位有沒有變小 { Sleep(500); if(!PositionSelectByTicket(t) || PositionGetDouble(POSITION_VOLUME) <= before - vol + 1e-9) return true; } err = "部分平倉結果不明(逾時/斷線),為了不平過頭沒有重送:請到 MT5 確認"; return false; } if(!IsRetryable(rc)) { err = "部分平倉失敗 " + IntegerToString(rc) + " " + g_trade.ResultRetcodeDescription(); return false; } Sleep(250); } err = "部分平倉失敗(重試 " + IntegerToString(InpRetries) + " 次)"; return false; } // 平掉符合條件的部位:type = POSITION_TYPE_BUY/SELL,−1 = 不分方向 int CloseMatching(const string sym, const long magic, const int type, const string cf, double &vol, string &err) { ulong list[]; double vols[]; for(int i = PositionsTotal() - 1; i >= 0; i--) { ulong t = PositionGetTicket(i); if(t > 0 && MatchPos(sym, magic, type, cf)) { int n = ArraySize(list); ArrayResize(list, n + 1); ArrayResize(vols, n + 1); list[n] = t; vols[n] = PositionGetDouble(POSITION_VOLUME); } } int closed = 0; vol = 0; for(int i = 0; i < ArraySize(list); i++) { string e = ""; if(CloseTicket(list[i], e)) { closed++; vol += vols[i]; } else err = e; } return closed; } // 照開倉時間先後(先進先出)減掉 cut 手 bool ReduceSide(const string sym, const long magic, const int type, const string cf, double cut, string &err) { ulong list[]; long times[]; for(int i = PositionsTotal() - 1; i >= 0; i--) { ulong t = PositionGetTicket(i); if(t > 0 && MatchPos(sym, magic, type, cf)) { int n = ArraySize(list); ArrayResize(list, n + 1); ArrayResize(times, n + 1); list[n] = t; times[n] = PositionGetInteger(POSITION_TIME_MSC); } } int n = ArraySize(list); for(int i = 0; i < n - 1; i++) // 依時間排序(筆數少,簡單排序就好) for(int j = i + 1; j < n; j++) if(times[j] < times[i]) { long tt = times[i]; times[i] = times[j]; times[j] = tt; ulong tk = list[i]; list[i] = list[j]; list[j] = tk; } double vmin = SymbolInfoDouble(sym, SYMBOL_VOLUME_MIN); bool ok = true; for(int i = 0; i < n && cut > 1e-9; i++) { if(!PositionSelectByTicket(list[i])) continue; double v = PositionGetDouble(POSITION_VOLUME); string e = ""; if(cut >= v - 1e-9) { if(CloseTicket(list[i], e)) cut -= v; else { ok = false; err = e; break; // 結果不明時換下一張會減過頭:停下來回報 } } else { double part = RoundLots(sym, cut); if(part < vmin) part = vmin; if(v - part < vmin - 1e-9) // 剩下的比最小手數還小 → 整張平 part = v; if(CloseTicketPartial(list[i], part, e)) cut -= part; else { ok = false; err = e; break; } } } return ok; } int DeleteOrders(const string sym, const long magic, const bool buyLimit, const bool buyStop, const bool sellLimit, const bool sellStop, const string cf, string &err) { ulong list[]; for(int i = OrdersTotal() - 1; i >= 0; i--) { ulong t = OrderGetTicket(i); if(t == 0) continue; if(sym != "" && OrderGetString(ORDER_SYMBOL) != sym) continue; if(OrderGetInteger(ORDER_MAGIC) != magic) continue; if(cf != "" && TagOf(t, OrderGetString(ORDER_COMMENT)) != cf) continue; long ty = OrderGetInteger(ORDER_TYPE); bool hit = (ty == ORDER_TYPE_BUY_LIMIT && buyLimit) || (ty == ORDER_TYPE_BUY_STOP && buyStop) || (ty == ORDER_TYPE_SELL_LIMIT && sellLimit) || (ty == ORDER_TYPE_SELL_STOP && sellStop) || (ty == ORDER_TYPE_BUY_STOP_LIMIT && buyStop) || (ty == ORDER_TYPE_SELL_STOP_LIMIT && sellStop); if(hit) { int n = ArraySize(list); ArrayResize(list, n + 1); list[n] = t; } } int done = 0; for(int i = 0; i < ArraySize(list); i++) { if(g_trade.OrderDelete(list[i]) && IsDone(g_trade.ResultRetcode())) done++; else if(OrderSelect(list[i])) err = "刪單失敗 " + IntegerToString(g_trade.ResultRetcode()); } return done; } //──────────────────────────── 開倉 ──────────────────────────── // 用實際成交價重算停損停利並掛上去(停損太近被拒時用);掛不上回傳 false bool FixStops(const ulong pt, const string sym, const bool isBuy, const double fill, SSig &s, string &err) { double sl = 0, tp = 0; MqlTick tk; if(pt == 0 || !SymbolInfoTick(sym, tk)) { err = "找不到部位或報價"; return false; } if(!CalcStops(s, sym, isBuy, fill, isBuy ? tk.bid : tk.ask, sl, tp, err)) return false; if(sl <= 0 && tp <= 0) return true; for(int a = 0; a <= InpRetries; a++) { if(g_trade.PositionModify(pt, sl, tp) && IsDone(g_trade.ResultRetcode())) return true; Sleep(250); } err = "補停損停利失敗 " + IntegerToString(g_trade.ResultRetcode()) + " " + g_trade.ResultRetcodeDescription(); return false; } // 價格已經越過停損了嗎(多單看 Bid、空單看 Ask) bool StopPassed(const string sym, const bool isBuy, const double sl) { MqlTick tk; if(sl <= 0 || !SymbolInfoTick(sym, tk)) return false; return isBuy ? tk.bid <= sl : tk.ask >= sl; } // 停損停利沒掛上:交給 Manage() 自動重試(停損被穿過就平倉);連部位編號都找不到只能請人處理 string StopsPending(const ulong t, const string sym, const double sl, const double tp, const string why) { if(t > 0) { WantStops(t, sl, tp); Alert("Bridge EA:", sym, " #", t, " 停損停利沒掛上(", why, "),EA 會自動重試,請檢查"); return "已進場,但停損停利還沒掛上(" + why + "),EA 會自動重試"; } Alert("Bridge EA:", sym, " 停損停利沒掛上,也找不到部位編號,請到 MT5 手動設定"); return "已進場,但停損停利沒掛上(" + why + "),也找不到部位編號:請到 MT5 手動設定"; } void SendMarket(const string sym, const bool isBuy, const double lots, const double sl, const double tp, const string cm, const long magic, SSig &s, SRes &r) { PrepTrade(sym, magic); double vmax = SymbolInfoDouble(sym, SYMBOL_VOLUME_MAX); if(vmax <= 0) vmax = lots; int side = isBuy ? POSITION_TYPE_BUY : POSITION_TYPE_SELL; double left = lots, filled = 0, wsum = 0, wvol = 0; string err = "", warn = ""; uint lastRc = 0; int guard = 0; while(left > VolStep(sym) * 0.5 && guard++ < 50) { double chunk = NormLots(sym, MathMin(left, vmax)); if(chunk <= 0) break; bool ok = false, needFix = false, guessed = false, unsure = false; uint rc = 0; long sinceMsc = (long)TimeTradeServer() * 1000 - 3000; ulong gDeal = 0, gPos = 0; double gVol = 0, gPx = 0; for(int a = 0; a <= InpRetries; a++) { ok = isBuy ? g_trade.Buy(chunk, sym, 0.0, sl, tp, cm) : g_trade.Sell(chunk, sym, 0.0, sl, tp, cm); rc = g_trade.ResultRetcode(); if(rc == TRADE_RETCODE_INVALID_STOPS && (sl > 0 || tp > 0)) { // 停損停利離現價太近被拒 → 先進場,再用成交價補停損停利 ok = isBuy ? g_trade.Buy(chunk, sym, 0.0, 0.0, 0.0, cm) : g_trade.Sell(chunk, sym, 0.0, 0.0, 0.0, cm); rc = g_trade.ResultRetcode(); needFix = true; } if(ok && IsDone(rc)) break; if(Uncertain(rc)) { // 逾時/斷線:可能其實成交了。查成交紀錄確認;查不到也不重送(寧可少一筆,不要下兩次) if(ConfirmDeal(sym, magic, isBuy, sinceMsc, gDeal, gVol, gPx, gPos)) { ok = true; guessed = true; rc = TRADE_RETCODE_DONE; } else unsure = true; break; } needFix = false; if(!IsRetryable(rc)) break; Sleep(250); } if(!(ok && IsDone(rc))) { lastRc = rc; err = unsure ? "結果不明(逾時/斷線),為了不重複下單沒有重送:請到 MT5 確認有沒有成交" : IntegerToString(rc) + " " + g_trade.ResultRetcodeDescription(); break; } ulong pt = 0, regT = 0; double px = 0, v = chunk; if(guessed) { v = gVol > 0 ? gVol : chunk; // 同一張單的成交加總(FindNewDeal 已記為算過) px = gPx; pt = (gPos > 0 && PositionSelectByTicket(gPos)) ? gPos : NewestPosition(sym, magic, side, sinceMsc); regT = pt > 0 ? pt : gPos; } else { Remember(g_knownDeals, g_trade.ResultDeal()); Remember(g_knownOrders, g_trade.ResultOrder()); // 同一張單分好幾筆成交時,其他筆也不會被誤認 px = g_trade.ResultPrice(); v = g_trade.ResultVolume(); if(v <= 0) v = chunk; ulong ot = g_trade.ResultOrder(); pt = FindPositionTicket(ot, g_trade.ResultDeal(), sym); if(px <= 0 && pt > 0 && PositionSelectByTicket(pt)) px = PositionGetDouble(POSITION_PRICE_OPEN); regT = pt > 0 ? pt : ot; } ulong wt = pt > 0 ? pt : regT; // 找不到部位時:對沖帳戶的部位編號就是開倉的單號 bool opp = pt > 0 && PositionSelectByTicket(pt) && PositionGetInteger(POSITION_TYPE) != side; if(opp) // 淨額帳戶:這筆抵銷了反向部位(反向訊號設「不處理」或別的 magic) warn = "淨額帳戶:這筆抵銷了既有的反向部位,沒有新部位,停損停利沒有套用"; else if(needFix && (sl > 0 || tp > 0)) { string fe = ""; if(!FixStops(pt, sym, isBuy, px, s, fe)) { double dsl = StopPrice(s, "sl", sym, isBuy, px), dtp = StopPrice(s, "tp", sym, isBuy, px); if(dsl <= 0) dsl = sl; if(dtp <= 0) dtp = tp; string ce = ""; if(pt > 0 && StopPassed(sym, isBuy, dsl) && CloseTicket(pt, ce)) warn = "進場後價格已經越過停損,已立即平倉"; // 本來就該停損出場了 else warn = StopsPending(wt, sym, dsl, dtp, ce != "" ? "價格已越過停損,但" + ce : fe); } } else if((sl > 0 || tp > 0) && pt > 0 && PositionSelectByTicket(pt) && ((sl > 0 && PositionGetDouble(POSITION_SL) <= 0) || (tp > 0 && PositionGetDouble(POSITION_TP) <= 0))) warn = StopsPending(pt, sym, sl, tp, "成交了但部位上沒有"); // 逾時後確認的單特別要看 if(!opp) RegisterTicket(regT, cm, s); if(r.ticket == 0) r.ticket = regT; filled += v; if(px > 0) { wsum += v * px; wvol += v; } left -= v; // 部分成交(DONE_PARTIAL)時剩下的再送 if(guessed && left > VolStep(sym) * 0.5) { lastRc = TRADE_RETCODE_TIMEOUT; // 逾時後確認只成交一部分:剩下的不再送,免得重複 err = "逾時後從成交紀錄確認成交 " + D2S(v) + " 手,剩下的為了不重複下單沒有再送"; break; } } r.volume = filled; r.price = wvol > 0 ? wsum / wvol : 0; double asl = 0, atp = 0; // 實際掛上的停損停利(訊息用) if(r.ticket > 0 && PositionSelectByTicket(r.ticket)) { asl = PositionGetDouble(POSITION_SL); atp = PositionGetDouble(POSITION_TP); } string what = (isBuy ? "買進 " : "賣出 ") + D2S(filled) + " 手 @ " + D2S(r.price) + (asl > 0 ? " SL " + D2S(asl) : "") + (atp > 0 ? " TP " + D2S(atp) : ""); if(filled <= 0) Res(r, "failed", (long)lastRc, "下單失敗:" + err); else if(left > VolStep(sym) * 0.5) Res(r, "partial", (long)lastRc, "只成交 " + D2S(filled) + " / " + D2S(lots) + " 手:" + err + (warn != "" ? ";" + warn : "")); else if(warn != "") Res(r, "partial", (long)TRADE_RETCODE_DONE, what + ";" + warn); else Res(r, "done", (long)TRADE_RETCODE_DONE, what); } bool EntryChecks(SSig &s, SRes &r) { if(!TradeAllowed(r)) return false; if(g_paused) { Res(r, "skipped", 0, "帳戶在網站上暫停中,不開新倉"); return false; } if(g_dayBlocked) { Res(r, "skipped", 0, "今天虧損達上限(" + D2S(InpDailyLossPct, 2) + "%),停止開新倉"); return false; } if(InpMaxAgeSec > 0 && s.age > (long)InpMaxAgeSec * 1000) { Res(r, "expired", 0, "訊號已經過 " + IntegerToString(s.age / 1000) + " 秒(上限 " + IntegerToString(InpMaxAgeSec) + "),不進場"); return false; } return true; } // 所有部位+掛單的名目合計(帳戶幣別,多空都算)。掛單也算:成交了就是部位,不算的話一次掛很多張就繞過合計上限 double GrossNotional() { double sum = 0; for(int i = PositionsTotal() - 1; i >= 0; i--) { if(PositionGetTicket(i) == 0) continue; string ps = PositionGetString(POSITION_SYMBOL); double pv = PositionGetDouble(POSITION_VOLUME), px = PositionGetDouble(POSITION_PRICE_CURRENT); sum += pv * NotionalPerLot(ps, px); } for(int i = OrdersTotal() - 1; i >= 0; i--) { if(OrderGetTicket(i) == 0) continue; ENUM_ORDER_TYPE ot = (ENUM_ORDER_TYPE)OrderGetInteger(ORDER_TYPE); if(ot != ORDER_TYPE_BUY_LIMIT && ot != ORDER_TYPE_SELL_LIMIT && ot != ORDER_TYPE_BUY_STOP && ot != ORDER_TYPE_SELL_STOP && ot != ORDER_TYPE_BUY_STOP_LIMIT && ot != ORDER_TYPE_SELL_STOP_LIMIT) continue; string os = OrderGetString(ORDER_SYMBOL); double ov = OrderGetDouble(ORDER_VOLUME_CURRENT), op = OrderGetDouble(ORDER_PRICE_OPEN); sum += ov * NotionalPerLot(os, op); } return sum; } // 安全上限:網站被入侵、策略或倍數設錯時,最多只會錯到這裡。開倉、加碼、掛單送出前檢查;平倉、減碼不受限。 bool CapCheck(const string sym, const double lots, const double price, SRes &r, const string note) { string why = ""; double eq = AccountInfoDouble(ACCOUNT_EQUITY); double npl = price > 0 ? NotionalPerLot(sym, price) : 0; if(InpMaxOrderPct > 0 || InpMaxTotalPct > 0) { if(npl <= 0) why = "算不出 " + sym + " 的名目(沒有報價或匯率?),安全上限沒辦法檢查"; else if(eq > 0) { double pct = lots * npl / eq * 100.0; if(InpMaxOrderPct > 0 && pct > InpMaxOrderPct) why = "這筆名目是權益的 " + D2S(pct, 0) + "%,超過 EA 的單筆上限 " + D2S(InpMaxOrderPct, 0) + "%"; else if(InpMaxTotalPct > 0) { double tot = GrossNotional() / eq * 100.0 + pct; if(tot > InpMaxTotalPct) why = "下了這筆,所有部位合計名目(含掛單)會是權益的 " + D2S(tot, 0) + "%,超過 EA 的合計上限 " + D2S(InpMaxTotalPct, 0) + "%"; } } } ulong now = GetTickCount64(); int n = 0; for(int i = 0; i < ArraySize(g_entryTs); i++) if(now - g_entryTs[i] < 60000) g_entryTs[n++] = g_entryTs[i]; ArrayResize(g_entryTs, n); if(why == "" && InpMaxEntriesMin > 0 && n >= InpMaxEntriesMin) why = "1 分鐘內已經送了 " + IntegerToString(n) + " 筆新倉/加碼/掛單,超過 EA 的上限 " + IntegerToString(InpMaxEntriesMin) + " 筆"; if(why != "") { Res(r, note != "" ? "partial" : "failed", 0, note + why + ":沒有下單(網站被入侵?策略或倍數設錯?確認沒問題再到 EA 設定調高上限)"); Print("[Bridge] 安全上限擋下 ", sym, ":", why); if(InpPushAlerts && (g_capAlertAt == 0 || now - g_capAlertAt > 600000)) { g_capAlertAt = now; Alert("Bridge EA:安全上限擋下 ", sym, ":", why); if(TerminalInfoInteger(TERMINAL_NOTIFICATIONS_ENABLED)) SendNotification(StringSubstr("Bridge EA:安全上限擋下 " + sym + ":" + why, 0, 250)); } return false; } ArrayResize(g_entryTs, n + 1); g_entryTs[n] = now; return true; } void OpenMarket(SSig &s, const string sym, const bool isBuy, const long magic, SRes &r) { if(!EntryChecks(s, r)) return; double maxSpr = Has(s, "spread") ? PD(s, "spread") : InpMaxSpreadPips; if(maxSpr > 0) { double sp = SpreadPips(sym); if(sp > maxSpr) { Res(r, "skipped", 0, "點差 " + D2S(sp, 1) + " pips 超過上限 " + D2S(maxSpr, 1)); return; } } int sameType = isBuy ? POSITION_TYPE_BUY : POSITION_TYPE_SELL; int oppType = isBuy ? POSITION_TYPE_SELL : POSITION_TYPE_BUY; int opp = CountPos(sym, magic, oppType); string note = ""; bool direct = !IsStrategyMagic(magic); // 反向/加碼設定只管直接警報:策略訊號有自己的多條腿(例如 NQ 拆兩張) if(opp > 0 && InpReverse != BR_REV_OFF && direct) { double v = 0; string e = ""; int n = CloseMatching(sym, magic, oppType, "", v, e); note = "先平反向 " + IntegerToString(n) + " 張;"; if(InpReverse == BR_REV_CLOSE_ONLY) { Res(r, e == "" ? "done" : (n > 0 ? "partial" : "failed"), e == "" ? 0 : (long)g_closeRc, note + "設定為只平不進場" + (e != "" ? ":" + e : "")); return; } if(e != "") { Res(r, n > 0 ? "partial" : "failed", (long)g_closeRc, note + "反向部位沒平乾淨,先不進場:" + e); return; } opp = CountPos(sym, magic, oppType); } int same = CountPos(sym, magic, sameType); if(InpPyramid == BR_PYR_OFF && same > 0 && direct) { Res(r, "skipped", 0, note + "已有同方向部位(加碼設定:同方向最多一張)"); return; } if(InpPyramid == BR_PYR_OFF_ANY && same + opp > 0 && direct) { Res(r, "skipped", 0, note + "已有部位(加碼設定:每個商品最多一張)"); return; } MqlTick tk; if(!SymbolInfoTick(sym, tk) || tk.ask <= 0 || tk.bid <= 0) { Res(r, "failed", 0, "沒有報價(市場休市?)"); return; } double entry = isBuy ? tk.ask : tk.bid; double sl = 0, tp = 0, lots = 0; string err = ""; if(!CalcStops(s, sym, isBuy, entry, isBuy ? tk.bid : tk.ask, sl, tp, err) || !CalcVolume(s, sym, isBuy, entry, sl, lots, err)) { Res(r, "failed", 0, note + err); return; } double nl = NormLots(sym, lots); if(nl <= 0) { Res(r, "skipped", 0, note + "算出 " + D2S(lots, 4) + " 手,小於最小下單量 " + D2S(SymbolInfoDouble(sym, SYMBOL_VOLUME_MIN))); return; } if(!CapCheck(sym, nl, entry, r, note)) return; bool capped = InpMaxLots > 0 && lots > InpMaxLots + 1e-9; if(capped) note += "算出 " + D2S(lots, 2) + " 手,超過 EA 的單筆上限 " + D2S(InpMaxLots) + " 手,只下上限;"; SendMarket(sym, isBuy, nl, sl, tp, PS(s, "comment"), magic, s, r); if(note != "") r.msg = note + r.msg; if(capped && r.status == "done") r.status = "partial"; } // 逾時後找剛掛上的單:同商品、magic、類型、價格、手數,掛單時間在 sinceMsc 之後(最多等 6 秒) ulong FindRecentOrder(const string sym, const long magic, const ENUM_ORDER_TYPE type, const double price, const double vol, const long sinceMsc) { double ts = SymbolInfoDouble(sym, SYMBOL_TRADE_TICK_SIZE); if(ts <= 0) ts = SymbolInfoDouble(sym, SYMBOL_POINT); for(int w = 0; w < 12; w++) { Sleep(500); for(int i = OrdersTotal() - 1; i >= 0; i--) { ulong t = OrderGetTicket(i); if(t == 0 || Known(g_knownOrders, t) || OrderGetString(ORDER_SYMBOL) != sym || OrderGetInteger(ORDER_MAGIC) != magic) continue; if(OrderGetInteger(ORDER_TYPE) != type || OrderGetInteger(ORDER_TIME_SETUP_MSC) < sinceMsc) continue; if(MathAbs(OrderGetDouble(ORDER_PRICE_OPEN) - price) <= ts * 0.5 + 1e-12 && MathAbs(OrderGetDouble(ORDER_VOLUME_INITIAL) - vol) < 1e-9) return t; } } return 0; } void OpenPending(SSig &s, const string sym, const string cmd, const long magic, SRes &r) { if(!EntryChecks(s, r)) return; bool isBuy = StringFind(cmd, "buy") == 0; bool isLimit = StringFind(cmd, "limit") > 0; MqlTick tk; if(!SymbolInfoTick(sym, tk) || tk.ask <= 0 || tk.bid <= 0) { Res(r, "failed", 0, "沒有報價(市場休市?)"); return; } double price = 0; if(Has(s, "price")) price = PD(s, "price"); else { double d = PD(s, "pending_pips") * Pip(sym); double ref = isBuy ? tk.ask : tk.bid; price = (isBuy == isLimit) ? ref - d : ref + d; // 買限價、賣停損在下;買停損、賣限價在上 } price = NormPrice(sym, price); double ref2 = isBuy ? tk.ask : tk.bid; bool below = price < ref2; if((isBuy && isLimit && !below) || (isBuy && !isLimit && below) || (!isBuy && isLimit && below) || (!isBuy && !isLimit && !below)) { Res(r, "failed", 0, cmd + " 價格 " + D2S(price) + " 在現價 " + D2S(ref2) + " 錯的一邊"); return; } double sl = 0, tp = 0, lots = 0; string err = ""; if(!CalcStops(s, sym, isBuy, price, price, sl, tp, err) || !CalcVolume(s, sym, isBuy, price, sl, lots, err)) { Res(r, "failed", 0, err); return; } double nl = NormLots(sym, lots); if(nl <= 0) { Res(r, "skipped", 0, "算出 " + D2S(lots, 4) + " 手,小於最小下單量"); return; } if(!CapCheck(sym, nl, price, r, "")) return; if(InpMaxLots > 0 && lots > InpMaxLots + 1e-9) g_capNote = "算出 " + D2S(lots, 2) + " 手,超過 EA 的單筆上限 " + D2S(InpMaxLots) + " 手,只掛上限;"; string cm = PS(s, "comment"); PrepTrade(sym, magic); bool ok = false; uint rc = 0; long sinceMsc = (long)TimeTradeServer() * 1000 - 3000; ENUM_ORDER_TYPE want = isBuy ? (isLimit ? ORDER_TYPE_BUY_LIMIT : ORDER_TYPE_BUY_STOP) : (isLimit ? ORDER_TYPE_SELL_LIMIT : ORDER_TYPE_SELL_STOP); for(int a = 0; a <= InpRetries; a++) { if(isBuy && isLimit) ok = g_trade.BuyLimit(nl, price, sym, sl, tp, ORDER_TIME_GTC, 0, cm); else if(isBuy) ok = g_trade.BuyStop(nl, price, sym, sl, tp, ORDER_TIME_GTC, 0, cm); else if(isLimit) ok = g_trade.SellLimit(nl, price, sym, sl, tp, ORDER_TIME_GTC, 0, cm); else ok = g_trade.SellStop(nl, price, sym, sl, tp, ORDER_TIME_GTC, 0, cm); rc = g_trade.ResultRetcode(); if(ok && IsDone(rc)) break; if(Uncertain(rc)) { ulong found = FindRecentOrder(sym, magic, want, price, nl, sinceMsc); if(found > 0) { Remember(g_knownOrders, found); r.ticket = found; r.price = price; r.volume = nl; RegisterTicket(found, cm, s); Res(r, "done", 0, cmd + " " + D2S(nl) + " 手 @ " + D2S(price) + "(逾時後確認已掛上)"); return; } Res(r, "failed", (long)rc, "掛單結果不明(逾時/斷線),為了不重複掛單沒有重送:請到 MT5 確認"); return; } if(!IsRetryable(rc)) break; Sleep(250); } if(!(ok && IsDone(rc))) { Res(r, "failed", (long)rc, "掛單失敗:" + IntegerToString(rc) + " " + g_trade.ResultRetcodeDescription()); return; } r.ticket = g_trade.ResultOrder(); Remember(g_knownOrders, r.ticket); r.price = price; r.volume = nl; RegisterTicket(r.ticket, cm, s); Res(r, "done", (long)rc, cmd + " " + D2S(nl) + " 手 @ " + D2S(price) + (Has(s, "expiry") ? "," + D2S(PD(s, "expiry")) + " 分鐘後失效" : "")); } //──────────────────────────── 其他指令 ──────────────────────────── void DoClose(const string sym, const long magic, const int type, const string cf, SRes &r, const string what) { double v = 0; string e = ""; int n = CloseMatching(sym, magic, type, cf, v, e); r.volume = v; if(e != "") Res(r, n > 0 ? "partial" : "failed", (long)g_closeRc, what + ":平了 " + IntegerToString(n) + " 張," + e); else Res(r, "done", 0, what + ":平了 " + IntegerToString(n) + " 張(" + D2S(v) + " 手)" + (cf != "" ? ",comment=" + cf : "")); } void DoClosePct(SSig &s, const string sym, const long magic, const int type, const string cf, SRes &r) { double pct = PD(s, "pct"); double total = SumVol(sym, magic, type, cf); if(total <= 0) { Res(r, "done", 0, "沒有部位可平"); return; } double cut = RoundLots(sym, total * pct / 100.0); if(cut <= 0) { Res(r, "skipped", 0, "平 " + D2S(pct, 1) + "% 不到最小單位"); return; } string e = ""; bool ok = ReduceSide(sym, magic, type, cf, cut, e); double got = total - SumVol(sym, magic, type, cf); r.volume = got; Res(r, ok ? "done" : (got > 0 ? "partial" : "failed"), ok ? 0 : (long)g_closeRc, "平 " + D2S(pct, 1) + "%:" + D2S(got) + " / " + D2S(total) + " 手" + (e != "" ? "," + e : "")); } void DoModify(SSig &s, const string sym, const long magic, const int type, const string cf, SRes &r) { bool isBuy = (type == POSITION_TYPE_BUY); bool hs = HasSL(s), ht = HasTP(s); MqlTick tk; if(!SymbolInfoTick(sym, tk) || tk.ask <= 0 || tk.bid <= 0) { Res(r, "failed", 0, "沒有報價(市場休市?)"); return; } ulong list[]; for(int i = PositionsTotal() - 1; i >= 0; i--) { ulong t = PositionGetTicket(i); if(t > 0 && MatchPos(sym, magic, type, cf)) { int n = ArraySize(list); ArrayResize(list, n + 1); list[n] = t; } } int ok = 0; string e = ""; for(int i = 0; i < ArraySize(list); i++) { if(!PositionSelectByTicket(list[i])) continue; double open = PositionGetDouble(POSITION_PRICE_OPEN); double sl = 0, tp = 0; string err = ""; if(!CalcStops(s, sym, isBuy, open, isBuy ? tk.bid : tk.ask, sl, tp, err)) { e = err; continue; } double nsl = (hs && sl > 0) ? sl : PositionGetDouble(POSITION_SL); // 帶 0 不會把原本的停損拿掉 double ntp = (ht && tp > 0) ? tp : PositionGetDouble(POSITION_TP); PrepTrade(sym, magic); if(g_trade.PositionModify(list[i], nsl, ntp) && IsDone(g_trade.ResultRetcode())) ok++; else e = "修改失敗 " + IntegerToString(g_trade.ResultRetcode()) + " " + g_trade.ResultRetcodeDescription(); } Res(r, e == "" ? "done" : (ok > 0 ? "partial" : "failed"), 0, "改了 " + IntegerToString(ok) + " 張的停損停利" + (e != "" ? "," + e : "")); } // 部位同步:把(商品, magic)的淨部位調到目標 void DoSync(SSig &s, const string sym, const long magic, SRes &r) { MqlTick tk; if(!SymbolInfoTick(sym, tk) || tk.ask <= 0 || tk.bid <= 0) { Res(r, "failed", 0, "沒有報價(市場休市?)"); return; } double mid = (tk.ask + tk.bid) / 2.0; double target = 0; string capMsg = ""; if(Has(s, "target_lots")) target = PD(s, "target_lots"); else { double npl = NotionalPerLot(sym, mid); if(npl <= 0) { Res(r, "failed", 0, "算不出 1 手的名目"); return; } double pct = PD(s, "target_pct"); if(InpMaxSyncPct > 0 && MathAbs(pct) > InpMaxSyncPct) // 大小不可信:方向照做(平反向),這一邊不加不減 capMsg = "目標名目 " + D2S(pct, 1) + "% 超過 EA 上限 " + D2S(InpMaxSyncPct, 0) + "%(TV 權益數字錯了?),沒有加減碼"; target = pct / 100.0 * Base() / npl; } double tAbs = NormLots(sym, MathAbs(target)); if(InpMaxLots > 0 && MathAbs(target) > InpMaxLots + 1e-9) g_capNote = "目標 " + D2S(MathAbs(target), 2) + " 手超過 EA 的單筆上限 " + D2S(InpMaxLots) + " 手,只做到上限;"; int tSign = (tAbs <= 0) ? 0 : (target > 0 ? 1 : -1); bool tooOld = InpSyncMaxAgeSec > 0 && s.age > (long)InpSyncMaxAgeSec * 1000; bool canAdd = !g_paused && !g_dayBlocked && !tooOld && TerminalInfoInteger(TERMINAL_TRADE_ALLOWED) && MQLInfoInteger(MQL_TRADE_ALLOWED); string cm = PS(s, "comment"); string e = "", note = ""; double v = 0, closed = 0; if(tSign >= 0 && SumVol(sym, magic, POSITION_TYPE_SELL) > 0) { CloseMatching(sym, magic, POSITION_TYPE_SELL, "", v, e); note += "平空 " + D2S(v) + ";"; closed += v; } if(tSign <= 0 && SumVol(sym, magic, POSITION_TYPE_BUY) > 0) { CloseMatching(sym, magic, POSITION_TYPE_BUY, "", v, e); note += "平多 " + D2S(v) + ";"; closed += v; } r.volume = closed; long crc = e != "" ? (long)g_closeRc : 0; // 平倉失敗的原因:休市、斷線時網站會自動重試 if(tSign == 0) { Res(r, e == "" ? "done" : (closed > 0 ? "partial" : "failed"), crc, note + "目標 0 手" + (target != 0 ? "(" + D2S(MathAbs(target), 4) + " 手小於最小單位)" : "") + (e != "" ? "," + e : "")); return; } if(e != "") { Res(r, closed > 0 ? "partial" : "failed", crc, note + "反向部位沒平乾淨,先不開新倉:" + e); return; } if(capMsg != "") { Res(r, closed > 0 ? "partial" : "failed", 0, note + capMsg); return; } int side = tSign > 0 ? POSITION_TYPE_BUY : POSITION_TYPE_SELL; bool isBuy = tSign > 0; double have = SumVol(sym, magic, side); bool hasRatio = Has(s, "ratio"); double ratio = PD(s, "ratio", 1.0); double add = 0, cut = 0; if(have <= 0) { if(hasRatio && ratio < 1.0) // 減碼訊號:手上沒有就不要反過來開新倉 { Res(r, (note != "" || e != "") ? "partial" : "skipped", 0, note + "沒有部位可減(要跟上 TradingView 請到網站按「跟上目前部位」)"); return; } add = tAbs; } else if(hasRatio && ratio < 1.0) cut = RoundLots(sym, have - have * ratio); else if(hasRatio) add = NormLots(sym, tAbs - have); else { double diff = tAbs - have; double tol = MathMax(VolStep(sym) * 0.5, tAbs * InpSyncTolPct / 100.0); if(MathAbs(diff) >= tol) { if(diff > 0) add = NormLots(sym, diff); else cut = RoundLots(sym, -diff); } } if(cut > 0) { string e2 = ""; bool ok = ReduceSide(sym, magic, side, "", cut, e2); double got = MathMax(have - SumVol(sym, magic, side), 0); r.volume = closed + got; Res(r, ok ? "done" : (got > 0 || closed > 0 ? "partial" : "failed"), ok ? 0 : (long)g_closeRc, note + (isBuy ? "多單" : "空單") + "減 " + D2S(got) + " / " + D2S(cut) + " 手(" + D2S(have) + " → " + D2S(have - got) + ")" + (e2 != "" ? "," + e2 : "")); return; } if(add > 0) { if(!canAdd) { Res(r, note != "" ? "partial" : "skipped", 0, note + "目標 " + D2S(tAbs) + " 手,但現在不開新倉:" + (tooOld ? "訊號已經過 " + IntegerToString(s.age / 1000) + " 秒(只減碼不加碼;要跟上請到網站按「跟上目前部位」)" : (g_paused ? "網站暫停中" : (g_dayBlocked ? "每日虧損上限已觸發" : "MT5 沒開演算法交易")))); return; } double sl = 0, tp = 0; string err = ""; if(!CalcStops(s, sym, isBuy, isBuy ? tk.ask : tk.bid, isBuy ? tk.bid : tk.ask, sl, tp, err)) { Res(r, "failed", 0, note + err); return; } if(!CapCheck(sym, add, isBuy ? tk.ask : tk.bid, r, note)) return; SendMarket(sym, isBuy, add, sl, tp, cm, magic, s, r); r.msg = note + "目標 " + D2S(tAbs) + " 手(原有 " + D2S(have) + "):" + r.msg; return; } Res(r, e == "" ? "done" : "partial", 0, note + "已經是目標部位(" + D2S(have) + " 手,目標 " + D2S(tAbs) + ")"); } void DoFlatten(SSig &s, SRes &r) { long ms[]; ArrayResize(ms, 0); string parts[]; int n = StringSplit(PS(s, "magics"), ';', parts); for(int i = 0; i < n; i++) { string t = Trim(parts[i]); if(t == "") continue; long v = StringToInteger(t); if(v <= 0 || IntegerToString(v) != t) { Res(r, "failed", 0, "magics 裡有讀不懂的值「" + t + "」:為了不動到手動下的單,沒有平倉"); return; } int k = ArraySize(ms); ArrayResize(ms, k + 1); ms[k] = v; } if(ArraySize(ms) == 0 || PD(s, "all") > 0) { int k0 = ArraySize(ms); ArrayResize(ms, k0 + 1 + ArraySize(g_magics)); ms[k0] = InpMagic; for(int i = 0; i < ArraySize(g_magics); i++) ms[k0 + 1 + i] = g_magics[i]; } int pos = 0, ord = 0; double vol = 0; string e = ""; for(int i = 0; i < ArraySize(ms); i++) { bool seen = false; for(int j = 0; j < i; j++) if(ms[j] == ms[i]) seen = true; if(seen) continue; double v = 0; ord += DeleteOrders("", ms[i], true, true, true, true, "", e); // 先刪掛單再平倉 pos += CloseMatching("", ms[i], -1, "", v, e); vol += v; } r.volume = vol; Res(r, e == "" ? "done" : "partial", e == "" ? 0 : (long)g_closeRc, "全部平倉:" + IntegerToString(pos) + " 張部位(" + D2S(vol) + " 手)、" + IntegerToString(ord) + " 張掛單" + (e != "" ? "," + e : "")); } //──────────────────────────── 分派 ──────────────────────────── void Execute(SSig &s, SRes &r) { r.status = "failed"; r.retcode = 0; r.ticket = 0; r.price = 0; r.volume = 0; r.msg = ""; g_closeRc = 0; string cmd = s.cmd; long magic = Has(s, "magic") ? (long)StringToInteger(PS(s, "magic")) : InpMagic; RememberMagic(magic); if(cmd == "flatten") { DoFlatten(s, r); return; } string sym = ResolveSymbol(s.sym); if(sym == "") { Res(r, "failed", 0, "MT5 找不到商品「" + s.sym + "」:請設定前綴/後綴或商品對照"); return; } string cf = PS(s, "comment"); string e = ""; if(cmd == "buy" || cmd == "sell") { OpenMarket(s, sym, cmd == "buy", magic, r); return; } if(cmd == "buylimit" || cmd == "selllimit" || cmd == "buystop" || cmd == "sellstop") { g_capNote = ""; OpenPending(s, sym, cmd, magic, r); if(g_capNote != "") { r.msg = g_capNote + r.msg; if(r.status == "done") r.status = "partial"; } return; } if(cmd == "closelong" || cmd == "closeshort" || cmd == "closelongshort") { int ptype = -1; if(cmd == "closelong") ptype = (int)POSITION_TYPE_BUY; if(cmd == "closeshort") ptype = (int)POSITION_TYPE_SELL; DoClose(sym, magic, ptype, cf, r, cmd == "closelong" ? "平多單" : (cmd == "closeshort" ? "平空單" : "多空都平")); return; } if(cmd == "closeall") { int d = DeleteOrders(sym, magic, true, true, true, true, cf, e); // 先刪掛單:平倉中間掛單成交會多出一張 DoClose(sym, magic, -1, cf, r, "全平"); r.msg += ",刪掛單 " + IntegerToString(d) + " 張" + (e != "" ? "(" + e + ")" : ""); if(e != "" && r.status == "done") r.status = "partial"; return; } if(cmd == "closelongpct" || cmd == "closeshortpct") { DoClosePct(s, sym, magic, cmd == "closelongpct" ? POSITION_TYPE_BUY : POSITION_TYPE_SELL, cf, r); return; } if(cmd == "closelongbuy" || cmd == "closeshortsell" || cmd == "closelongsell" || cmd == "closeshortbuy") { bool closeLong = StringFind(cmd, "closelong") == 0; bool openBuy = StringSubstr(cmd, StringLen(cmd) - 3) == "buy"; SRes rc; DoClose(sym, magic, closeLong ? POSITION_TYPE_BUY : POSITION_TYPE_SELL, cf, rc, closeLong ? "平多單" : "平空單"); if(rc.status != "done") // 平倉沒成功就不進場,免得多空同時在 { Res(r, rc.status, rc.retcode, rc.msg + ";平倉沒成功,沒有進場"); r.volume = rc.volume; return; } OpenMarket(s, sym, openBuy, magic, r); r.msg = rc.msg + ";" + r.msg; if(r.status != "done" && rc.volume > 0) r.status = "partial"; return; } if(cmd == "newsltplong" || cmd == "newsltpshort") { DoModify(s, sym, magic, cmd == "newsltplong" ? POSITION_TYPE_BUY : POSITION_TYPE_SELL, cf, r); return; } if(cmd == "sync") { g_capNote = ""; DoSync(s, sym, magic, r); if(g_capNote != "") { r.msg = g_capNote + r.msg; if(r.status == "done") r.status = "partial"; } return; } int nDel = -1; if(cmd == "cancellong") nDel = DeleteOrders(sym, magic, true, true, false, false, cf, e); else if(cmd == "cancelshort") nDel = DeleteOrders(sym, magic, false, false, true, true, cf, e); else if(cmd == "cancelall") nDel = DeleteOrders(sym, magic, true, true, true, true, cf, e); else if(cmd == "cancellongbuystop") nDel = DeleteOrders(sym, magic, false, true, false, false, cf, e); else if(cmd == "cancellongbuylimit") nDel = DeleteOrders(sym, magic, true, false, false, false, cf, e); else if(cmd == "cancelshortsellstop") nDel = DeleteOrders(sym, magic, false, false, false, true, cf, e); else if(cmd == "cancelshortselllimit") nDel = DeleteOrders(sym, magic, false, false, true, false, cf, e); if(nDel >= 0) { Res(r, e == "" ? "done" : (nDel > 0 ? "partial" : "failed"), 0, "刪掉 " + IntegerToString(nDel) + " 張掛單" + (e != "" ? "," + e : "")); return; } Res(r, "failed", 0, "EA 不認得指令 " + cmd); } string AckLine(SSig &s, SRes &r) { return "A," + s.id + "," + r.status + "," + IntegerToString(r.retcode) + "," + IntegerToString((long)r.ticket) + "," + D2S(r.price) + "," + D2S(r.volume) + "," + Clean(r.msg); } void QueueAck(const string ack) { int n = ArraySize(g_acks); ArrayResize(g_acks, n + 1); g_acks[n] = ack; } // ───── 預約下單(at=):Pine 提早送、EA 準時做,TradingView 的延遲就不算數了 ───── long SrvNow() { if(g_srvAt == 0) return (long)TimeGMT() * 1000; // 還沒量過網站的時鐘:先用電腦的(只到秒) return (long)GetTickCount64() + g_srvOffset; } void SrvClockSample(const long srvMs, const ulong rtt) { ulong now = GetTickCount64(); if(srvMs <= 0) return; if(g_srvAt == 0 || rtt <= g_srvRtt || now - g_srvAt > 1800000) // 來回越短量得越準;半小時重量一次 { g_srvOffset = srvMs + (long)(rtt / 2) - (long)now; g_srvRtt = rtt; g_srvAt = now; } } int SchedIndex(const string key) { for(int i = 0; i < ArraySize(g_schKey); i++) if(g_schKey[i] == key) return i; return -1; } void SaveSched() { string fin = FilePath("sched"), tmp = fin + ".tmp"; int h = FileOpen(tmp, FILE_WRITE | FILE_TXT | FILE_ANSI, '\t', CP_UTF8); if(h == INVALID_HANDLE) return; for(int i = 0; i < ArraySize(g_schKey); i++) FileWriteString(h, IntegerToString(g_schAt[i]) + "\t" + g_schKey[i] + "\t" + g_schLine[i] + "\r\n"); FileClose(h); if(!FileMove(tmp, 0, fin, FILE_REWRITE)) Print("[Bridge] 預約清單存檔失敗(錯誤 ", GetLastError(), ")"); } void LoadSched() { ArrayResize(g_schLine, 0); ArrayResize(g_schAt, 0); ArrayResize(g_schKey, 0); int h = FileOpen(FilePath("sched"), FILE_READ | FILE_TXT | FILE_ANSI, '\t', CP_UTF8); if(h == INVALID_HANDLE) return; while(!FileIsEnding(h)) { string ln = FileReadString(h); string f[]; if(StringSplit(ln, '\t', f) < 3) continue; int n = ArraySize(g_schKey); ArrayResize(g_schLine, n + 1); ArrayResize(g_schAt, n + 1); ArrayResize(g_schKey, n + 1); g_schAt[n] = StringToInteger(Trim(f[0])); g_schKey[n] = Trim(f[1]); g_schLine[n] = Trim(f[2]); } FileClose(h); if(ArraySize(g_schKey) > 0) PrintFormat("[Bridge] 讀回 %d 筆預約的訊號", ArraySize(g_schKey)); } void DropSched(const int k) { int n = ArraySize(g_schKey); for(int j = k; j < n - 1; j++) { g_schLine[j] = g_schLine[j + 1]; g_schAt[j] = g_schAt[j + 1]; g_schKey[j] = g_schKey[j + 1]; } ArrayResize(g_schLine, n - 1); ArrayResize(g_schAt, n - 1); ArrayResize(g_schKey, n - 1); } // 下一筆預約還有幾毫秒(沒有預約 = -1) long NextSchedIn() { long best = -1; for(int i = 0; i < ArraySize(g_schAt); i++) if(best < 0 || g_schAt[i] < best) best = g_schAt[i]; if(best < 0) return -1; return MathMax(0, best - SrvNow()); } // 預約的單是不是馬上就到:這段時間不做任何網路呼叫(輪詢、回報、心跳),免得卡在連線裡讓它晚。 // 只有會執行它的 EA(g_owner)才停;時間到了 RunScheduled 會馬上做掉(先從清單拿掉),所以不會一直停下去 bool SchedSoon() { if(!g_owner || !g_polledOk || g_srvAt == 0) return false; // 重開後還沒輪詢成功、還沒量網站的時鐘:先輪詢、送心跳(預約的單要等這兩步) long ns = NextSchedIn(); return ns >= 0 && ns <= g_pollOver + 60; } void HandleSignal(const string line) { string f[]; int n = StringSplit(line, ',', f); if(n < 5) return; SSig s; s.id = Trim(f[1]); s.age = StringToInteger(f[2]); if(!g_runDue && g_pollAt > 0) s.age += (long)(GetTickCount64() - g_pollAt); // 同一批前面的單做很久(逾時、休市重試):這段時間也算進年齡 s.cmd = Lower(Trim(f[3])); s.sym = Trim(f[4]); ArrayResize(s.k, 0); ArrayResize(s.v, 0); for(int i = 5; i < n; i++) { int p = StringFind(f[i], "="); if(p <= 0) continue; int m = ArraySize(s.k); ArrayResize(s.k, m + 1); ArrayResize(s.v, m + 1); s.k[m] = Lower(Trim(StringSubstr(f[i], 0, p))); s.v[m] = Trim(StringSubstr(f[i], p + 1)); } string key = g_instance + ":" + Trim(InpLicense) + ":" + s.id + ":" + PS(s, "nonce"); // 隨機碼:網站從備份還原、編號重來也不會撞 string prev = ""; if(FindDone(key, prev) || (PS(s, "nonce") == "" && FindDone(g_instance + ":" + s.id, prev))) // 伺服器重送:已經做過,只補回報 { QueueAck(prev); return; } long at = Has(s, "at") ? StringToInteger(PS(s, "at")) : 0; if(at > 0) { long nowMs = SrvNow(); if(at - nowMs > 30 && !g_runDue) // 還沒到:存起來(MT5 重開也不會丟),時間到才做 { if(SchedIndex(key) < 0) { int k = ArraySize(g_schKey); ArrayResize(g_schLine, k + 1); ArrayResize(g_schAt, k + 1); ArrayResize(g_schKey, k + 1); g_schLine[k] = line; g_schAt[k] = at; g_schKey[k] = key; SaveSched(); } QueueAck("A," + s.id + ",scheduled,0,,,,預約 " + TimeToString((datetime)(at / 1000), TIME_DATE | TIME_SECONDS) + " UTC 執行(還有 " + IntegerToString((at - nowMs) / 1000) + " 秒)"); return; } s.age = MathMax(0, nowMs - at); // 預約的單:太舊沒有從網站收到算,從預約時間算 } SRes r; ulong t0 = GetTickCount64(); // 先記一筆「執行中」:萬一執行到一半 MT5 被關掉,重送時不會再做一次(回報失敗,請人確認) RememberDone(key, "A," + s.id + ",failed,0,,,,EA 執行到一半中斷(MT5 被關閉?),為了不重複下單沒有重做:請到 MT5 確認"); Execute(s, r); string ack = AckLine(s, r); RememberDone(key, ack); QueueAck(ack); g_processed++; g_lastSignal = TimeToString(TimeLocal(), TIME_SECONDS) + " #" + s.id + " " + s.cmd + " " + s.sym + " → " + r.status; PrintFormat("[Bridge] #%s %s %s → %s %s(%s ms)", s.id, s.cmd, s.sym, r.status, r.msg, IntegerToString((long)(GetTickCount64() - t0))); } //──────────────────────────── HTTP ──────────────────────────── int Http(const string method, const string path, const string body, string &resp, const int timeoutMs) { char data[]; char result[]; string rh; ArrayResize(data, 0); if(body != "") { int n = StringToCharArray(body, data, 0, WHOLE_ARRAY, CP_UTF8); if(n > 0) ArrayResize(data, n - 1); // 去掉結尾的 \0 } // 授權碼、金鑰放在標頭(不放網址,免得出現在伺服器存取紀錄) string headers = "Content-Type: text/plain; charset=utf-8\r\nUser-Agent: BridgeEA/" + EA_VER + "\r\n" + "X-Bridge-License: " + Trim(InpLicense) + "\r\nX-Bridge-Key: " + Trim(InpEAKey) + "\r\n" + "X-Bridge-Login: " + g_login + "\r\nX-Bridge-Session: " + g_session + "\r\n" + "X-Bridge-Server: " + HeaderSafe(AccountInfoString(ACCOUNT_SERVER)) + "\r\n"; string url = g_base + path + (StringFind(path, "?") >= 0 ? "&" : "?") + "v=" + EA_VER; ResetLastError(); ulong t0 = GetTickCount64(); int code = WebRequest(method, url, headers, timeoutMs, data, result, rh); g_lastRtt = GetTickCount64() - t0; if(code == -1) { int err = GetLastError(); if(err == 4014) g_lastErr = "WebRequest 沒被允許:工具 → 選項 → EA 交易 → 勾「允許 WebRequest」並加入 " + g_base; else if(err == 5200) g_lastErr = "網站網址格式不對(錯誤 5200)"; else if(err == 5201) g_lastErr = "連不上網站(錯誤 5201:網站沒開、網域沒指到主機、或防火牆沒開 443)"; else if(err == 5202) g_lastErr = "網站沒回應(錯誤 5202:逾時)"; else if(err == 5203) g_lastErr = "HTTPS 連線失敗(錯誤 5203:憑證或 TLS 問題,也可能是 MT5 某些版本的已知問題)"; else g_lastErr = "連不到網站(錯誤 " + IntegerToString(err) + ")"; resp = ""; return -1; } resp = CharArrayToString(result, 0, WHOLE_ARRAY, CP_UTF8); if(code != 200) { string first = resp; int p = StringFind(first, "\n"); if(p > 0) first = StringSubstr(first, 0, p); g_lastErr = "網站回 " + IntegerToString(code) + ":" + first; } return code; } string JoinAcks() { string body = ""; for(int i = 0; i < ArraySize(g_acks); i++) body += g_acks[i] + "\n"; return body; } void FlushAcks() { if(ArraySize(g_acks) == 0 || g_backoff > 0 || SchedSoon()) // 網站連不上時等下一次輪詢一起帶;預約的單快到了先不送 return; string resp; if(Http("POST", "/api/ea/ack", JoinAcks(), resp, 5000) == 200) ArrayResize(g_acks, 0); } // 通知:寫進「專家」紀錄、跳出警示視窗、推播到手機 MT5(MT5 選項 → 通知 要填 MetaQuotes ID) void Notify(const string msg) { Print("[Bridge] ", msg); if(!InpPushAlerts) return; Alert("Bridge EA:", msg); string push = "Bridge EA:" + msg; if(StringLen(push) > 255) // 手機推播最多 255 字,太長會整則送不出去 push = StringSubstr(push, 0, 254) + "…"; if(TerminalInfoInteger(TERMINAL_NOTIFICATIONS_ENABLED)) SendNotification(push); } // 連線一直失敗才通知(短暫斷線不吵);恢復時也通知一次 void ConnFailed(const int code) { ulong now = GetTickCount64(); if(g_failSince == 0) g_failSince = now; ulong limit = (ulong)MathMax(10, InpAlertAfterSec) * 1000; if((code == 401 || code == 409) && limit > 30000) limit = 30000; // 金鑰錯、被另一個 EA 佔用:30 秒內就通知 if(!g_failNotified && now - g_failSince >= limit) { g_failNotified = true; Notify("帳號 " + g_login + " 連不上網站已經 " + IntegerToString((long)((now - g_failSince) / 1000)) + " 秒:" + g_lastErr + "。訊號會在網站排隊,恢復後平倉照做、太舊的進場不做。"); } } void ConnOk() { if(g_failNotified) Notify("帳號 " + g_login + " 恢復連線(斷了 " + IntegerToString((long)((GetTickCount64() - g_failSince) / 1000)) + " 秒)"); g_failSince = 0; g_failNotified = false; } // 預約時間到了的訊號:最後幾十毫秒用 Sleep 等到準時再做 void RunScheduled() { for(int guard = 0; guard < 50; guard++) { int k = -1; for(int i = 0; i < ArraySize(g_schAt); i++) if(k < 0 || g_schAt[i] < g_schAt[k]) k = i; if(k < 0) return; long dt = g_schAt[k] - SrvNow(); if(dt > 60) return; if(dt < -120000 && g_srvAt > 0) // 過了預約時間 2 分鐘(用網站的時鐘算):網站已經當失敗處理,這裡不要再做 { Print("[Bridge] 預約的訊號已經過了 ", IntegerToString(-dt / 1000), " 秒,不執行(網站會處理):", g_schLine[k]); DropSched(k); SaveSched(); continue; } if(dt > 0) Sleep((int)dt); string line = g_schLine[k]; DropSched(k); // 先拿掉再做:做到一半當掉,去重紀錄會擋下重做 SaveSched(); g_runDue = true; HandleSignal(line); g_runDue = false; } } void DoPoll() { string resp; int sent = ArraySize(g_acks); int waitMs = (int)MathMax(0, MathMin(25, InpPollWait)) * 1000; if(SchedSoon()) return; // 預約的單馬上就到:這一輪不輪詢(連線來回會讓它晚),先準時下單 long ns = NextSchedIn(); long margin = g_pollOver + 60; if(ns >= 0 && ns - margin < waitMs) waitMs = (int)MathMax(0, ns - margin); // 預約的單快到了:長輪詢提早回來(扣掉連線來回的時間) ulong t0 = GetTickCount64(); int code = Http("POST", "/api/ea/poll?wait=" + DoubleToString(waitMs / 1000.0, 3), JoinAcks(), resp, waitMs + 5000); long over = (long)(GetTickCount64() - t0) - waitMs; if(code == 200 && over >= 0 && StringFind(resp, "S,") != 0 && StringFind(resp, "\nS,") < 0) // 網站等滿才回(沒有訊號):多出來的就是連線來回;變慢馬上跟上,變快慢慢降 g_pollOver = (long)MathMin(2000.0, MathMax((double)over, 0.7 * g_pollOver + 0.3 * over)); if(code == 409 && StringFind(resp, "Another EA") >= 0) g_owner = false; else if(code == 200) { if(!g_owner) // 剛拿回這個帳戶:同一台 MT5 的另一個 EA 可能做過一些單,重讀去重紀錄和預約清單 { LoadDone(); LoadSched(); } g_owner = true; } if(code != 200) { g_status = "連線有問題"; g_backoff = (int)MathMin(10000, MathMax(1000, g_backoff * 2)); ConnFailed(code); return; } ConnOk(); g_polledOk = true; g_pollAt = GetTickCount64(); g_backoff = 0; g_status = "連線正常"; g_lastErr = ""; if(sent > 0) // 這次已經把回報帶上去了 { int left = ArraySize(g_acks) - sent; for(int i = 0; i < left; i++) g_acks[i] = g_acks[i + sent]; ArrayResize(g_acks, MathMax(0, left)); } string lines[]; int n = StringSplit(resp, '\n', lines); for(int i = 0; i < n; i++) { string line = Trim(lines[i]); if(line == "") continue; if(StringFind(line, "OK,") == 0) { string of[]; if(StringSplit(line, ',', of) >= 4) g_instance = Trim(of[3]); continue; } if(StringFind(line, "CFG,") == 0) { g_paused = StringFind(line, "paused=1") >= 0; int dp = StringFind(line, "dayoff="); if(dp >= 0) // 網站的「一天」的時區偏移(秒):每日風控跟網站的每日紀錄同一天換日 { string dv = StringSubstr(line, dp + 7); int dc = StringFind(dv, ","); if(dc >= 0) dv = StringSubstr(dv, 0, dc); dv = Trim(dv); long off = StringToInteger(dv); if(off >= -50400 && off <= 50400 && IntegerToString(off) == dv) { g_dayOff = (int)off; g_dayOffOk = true; } } int sp = StringFind(line, "daystart="); if(sp >= 0) // 網站的「今天」從什麼時候開始(UTC 秒) { string sv = StringSubstr(line, sp + 9); int sc = StringFind(sv, ","); if(sc >= 0) sv = StringSubstr(sv, 0, sc); sv = Trim(sv); long st = StringToInteger(sv); if(st > 1000000000 && IntegerToString(st) == sv) { MqlDateTime sd; // 這個起點是哪一天:起點過 3 小時的當地日期(夏令時間那天也在同一天裡) TimeToStruct((datetime)(st + DayOffset() + 10800), sd); g_dayStartUtc = st; g_dayStartKey = sd.year * 10000 + sd.mon * 100 + sd.day; } } int mp = StringFind(line, "magics="); if(mp >= 0) // 這個帳戶訂閱的策略:每日風控全平、刪掛單要涵蓋(VPS 上剛啟動時本機紀錄是空的) { string ml = StringSubstr(line, mp + 7); int cut = StringFind(ml, ","); if(cut >= 0) ml = StringSubstr(ml, 0, cut); string mm[]; int k = StringSplit(ml, ';', mm); string mlist = ";"; for(int j = 0; j < k; j++) { long mg = StringToInteger(Trim(mm[j])); if(mg <= 0) continue; // 壞掉的值不要變成 magic 0(會動到手動單) RememberMagic(mg); mlist += IntegerToString(mg) + ";"; } g_cfgMagics = mlist; } continue; } if(StringFind(line, "S,") == 0) { if(!TerminalInfoInteger(TERMINAL_CONNECTED)) break; // 跟券商斷線了:剩下的不要做(也不回報),網站之後會照順序重送 HandleSignal(line); } } } // 券商商品檢查:網站要的每個商品在這家券商的規格(找不到、交易模式、1 手價格動 1 的價值、手數限制、隔夜費、點差) string SymLines() { string out = ""; string names[]; int n = StringSplit(g_syms, ';', names); for(int i = 0; i < n && i < 30; i++) { string raw = Trim(names[i]); if(raw == "") continue; string sym = ResolveSymbol(raw); if(sym == "") { out += "Y," + Clean(raw) + ",0,0,0,0,0,0,0,0,0,0,0,0,0,\n"; continue; } double bid = SymbolInfoDouble(sym, SYMBOL_BID), ask = SymbolInfoDouble(sym, SYMBOL_ASK); double px = (bid > 0 && ask > 0) ? (bid + ask) / 2.0 : MathMax(bid, ask); double pv = px > 0 ? NotionalPerLot(sym, px) / px : 0; int dg = (int)SymbolInfoInteger(sym, SYMBOL_DIGITS); out += "Y," + Clean(raw) + ",1," + IntegerToString(SymbolInfoInteger(sym, SYMBOL_TRADE_MODE)) + "," + D2S(pv, 6) + "," + D2S(SymbolInfoDouble(sym, SYMBOL_VOLUME_MIN), 4) + "," + D2S(SymbolInfoDouble(sym, SYMBOL_VOLUME_STEP), 4) + "," + D2S(SymbolInfoDouble(sym, SYMBOL_VOLUME_MAX), 2) + "," + IntegerToString(SymbolInfoInteger(sym, SYMBOL_SWAP_MODE)) + "," + D2S(SymbolInfoDouble(sym, SYMBOL_SWAP_LONG), 4) + "," + D2S(SymbolInfoDouble(sym, SYMBOL_SWAP_SHORT), 4) + "," + D2S(SymbolInfoDouble(sym, SYMBOL_POINT), 10) + "," + IntegerToString(SymbolInfoInteger(sym, SYMBOL_SPREAD)) + "," + D2S(px, dg) + "," + IntegerToString(dg) + "," + Clean(sym) + "\n"; } return out; } void SendHeartbeat() { string b = "H,login=" + g_login + ",server=" + Clean(AccountInfoString(ACCOUNT_SERVER)) + ",company=" + Clean(AccountInfoString(ACCOUNT_COMPANY)) + ",currency=" + AccountInfoString(ACCOUNT_CURRENCY) + ",balance=" + D2S(AccountInfoDouble(ACCOUNT_BALANCE), 2) + ",equity=" + D2S(AccountInfoDouble(ACCOUNT_EQUITY), 2) + ",margin=" + D2S(AccountInfoDouble(ACCOUNT_MARGIN), 2) + ",free=" + D2S(AccountInfoDouble(ACCOUNT_MARGIN_FREE), 2) + ",leverage=" + IntegerToString(AccountInfoInteger(ACCOUNT_LEVERAGE)) + ",hedging=" + (IsHedging() ? "1" : "0") + ",connected=" + (TerminalInfoInteger(TERMINAL_CONNECTED) ? "1" : "0") + ",trade_allowed=" + ((TerminalInfoInteger(TERMINAL_TRADE_ALLOWED) && MQLInfoInteger(MQL_TRADE_ALLOWED)) ? "1" : "0") + ",ea=" + EA_VER + ",magic=" + IntegerToString(InpMagic) + ",base=" + BaseName() + ",base_value=" + D2S(Base(), 2) + ",day_start=" + D2S(g_dayStart, 2) + ",day_blocked=" + (g_dayBlocked ? "1" : "0") + ",daily_limit=" + D2S(InpDailyLossPct, 2) + ",build=" + IntegerToString(TerminalInfoInteger(TERMINAL_BUILD)) + ",vps=" + (TerminalInfoInteger(TERMINAL_VPS) ? "1" : "0") + ",rtt_ms=" + IntegerToString((long)g_lastRtt) + ",processed=" + IntegerToString(g_processed) + "\n"; int cnt = 0; for(int i = PositionsTotal() - 1; i >= 0 && cnt < 200; i--) { ulong t = PositionGetTicket(i); if(t == 0) continue; cnt++; string sym = PositionGetString(POSITION_SYMBOL); int dg = (int)SymbolInfoInteger(sym, SYMBOL_DIGITS); b += "P," + IntegerToString((long)t) + "," + sym + "," + (PositionGetInteger(POSITION_TYPE) == POSITION_TYPE_BUY ? "buy" : "sell") + "," + D2S(PositionGetDouble(POSITION_VOLUME)) + "," + D2S(PositionGetDouble(POSITION_PRICE_OPEN), dg) + "," + D2S(PositionGetDouble(POSITION_SL), dg) + "," + D2S(PositionGetDouble(POSITION_TP), dg) + "," + D2S(PositionGetDouble(POSITION_PROFIT) + PositionGetDouble(POSITION_SWAP), 2) + "," + IntegerToString(PositionGetInteger(POSITION_MAGIC)) + "," + Clean(TagOf(t, PositionGetString(POSITION_COMMENT))) + "\n"; } cnt = 0; for(int i = OrdersTotal() - 1; i >= 0 && cnt < 100; i--) { ulong t = OrderGetTicket(i); if(t == 0) continue; cnt++; string sym = OrderGetString(ORDER_SYMBOL); int dg = (int)SymbolInfoInteger(sym, SYMBOL_DIGITS); long ty = OrderGetInteger(ORDER_TYPE); string tn = ty == ORDER_TYPE_BUY_LIMIT ? "buy_limit" : ty == ORDER_TYPE_SELL_LIMIT ? "sell_limit" : ty == ORDER_TYPE_BUY_STOP ? "buy_stop" : ty == ORDER_TYPE_SELL_STOP ? "sell_stop" : "other"; b += "O," + IntegerToString((long)t) + "," + sym + "," + tn + "," + D2S(OrderGetDouble(ORDER_VOLUME_CURRENT)) + "," + D2S(OrderGetDouble(ORDER_PRICE_OPEN), dg) + "," + D2S(OrderGetDouble(ORDER_SL), dg) + "," + D2S(OrderGetDouble(ORDER_TP), dg) + "," + IntegerToString(OrderGetInteger(ORDER_MAGIC)) + "," + Clean(TagOf(t, OrderGetString(ORDER_COMMENT))) + "\n"; } if(g_syms != "" && (g_symDirty || GetTickCount64() - g_lastSymRep >= 600000)) { b += SymLines(); // 清單變了、或每 10 分鐘回報一次 g_symDirty = false; g_lastSymRep = GetTickCount64(); } string resp; if(Http("POST", "/api/ea/hb", b, resp, 5000) == 200) { string lines[]; int n = StringSplit(resp, '\n', lines); for(int i = 0; i < n; i++) { string line = Trim(lines[i]); if(StringFind(line, "TIME,") == 0) { SrvClockSample(StringToInteger(StringSubstr(line, 5)), g_lastRtt); continue; } if(StringFind(line, "SYM,") != 0) continue; string list = StringSubstr(line, 4); if(list != g_syms) { g_syms = list; g_symDirty = true; } } } } //──────────────────────────── 保本、追蹤停損、掛單到期 ──────────────────────────── // MT5 已就緒、跟券商連線、連上超過 3 秒(部位清單同步完) bool Settled() { return g_ready && g_connSince > 0 && TerminalInfoInteger(TERMINAL_CONNECTED) && GetTickCount64() - g_connSince >= 3000; } // 把進場時沒掛上的停損停利補上(推離現價、停損已經被穿過就直接平倉) bool FixWanted(const int i, const ulong t, const string sym, const bool isBuy, const double sl, const double tp) { MqlTick tk; if(!SymbolInfoTick(sym, tk)) return false; double ref = isBuy ? tk.bid : tk.ask; double pt = SymbolInfoDouble(sym, SYMBOL_POINT); double minDist = (double)SymbolInfoInteger(sym, SYMBOL_TRADE_STOPS_LEVEL) * pt + pt; double wsl = g_man[i].wantSL, wtp = g_man[i].wantTP; if(wsl > 0 && sl <= 0 && ((isBuy && ref <= wsl) || (!isBuy && ref >= wsl))) { string ce = ""; if(CloseTicket(t, ce)) { Print("[Bridge] #", t, " 停損一直沒掛上、價格已經越過停損價,已平倉"); return true; } if(g_man[i].lastTry == 0) Print("[Bridge] #", t, " 價格已經越過停損價,但平倉失敗(", ce, "),每 5 秒再試"); return false; } double nsl = sl, ntp = tp; if(wsl > 0 && sl <= 0) nsl = isBuy ? MathMin(wsl, NormPriceDir(sym, ref - minDist, false)) : MathMax(wsl, NormPriceDir(sym, ref + minDist, true)); if(wtp > 0 && tp <= 0) ntp = isBuy ? MathMax(wtp, NormPriceDir(sym, ref + minDist, true)) : MathMin(wtp, NormPriceDir(sym, ref - minDist, false)); if(nsl == sl && ntp == tp) return true; PrepTrade(sym, PositionGetInteger(POSITION_MAGIC)); bool ok = g_trade.PositionModify(t, nsl, ntp) && IsDone(g_trade.ResultRetcode()); if(ok) Print("[Bridge] #", t, " 補上停損停利:SL ", D2S(nsl), " TP ", D2S(ntp)); return ok; } void Manage() { if(!Settled()) return; // 斷線或剛連上時部位清單可能不完整,什麼都不要動 bool changed = false; ulong nowMs = GetTickCount64(); for(int i = ArraySize(g_man) - 1; i >= 0; i--) { ulong t = g_man[i].ticket; if(PositionSelectByTicket(t)) { string sym = PositionGetString(POSITION_SYMBOL); bool isBuy = PositionGetInteger(POSITION_TYPE) == POSITION_TYPE_BUY; double open = PositionGetDouble(POSITION_PRICE_OPEN); double sl = PositionGetDouble(POSITION_SL), tp = PositionGetDouble(POSITION_TP); long pmagic = PositionGetInteger(POSITION_MAGIC); MqlTick tk; if(!SymbolInfoTick(sym, tk)) continue; if((g_man[i].wantSL > 0 && sl > 0) || (g_man[i].wantTP > 0 && tp > 0)) { if(sl > 0) g_man[i].wantSL = 0; // 已經有了(補上了或手動設了)→ 不再補,之後手動拿掉也不會被加回去 if(tp > 0) g_man[i].wantTP = 0; changed = true; } if((g_man[i].wantSL > 0 && sl <= 0) || (g_man[i].wantTP > 0 && tp <= 0)) { bool passed = g_man[i].wantSL > 0 && sl <= 0 && StopPassed(sym, isBuy, g_man[i].wantSL); if(g_man[i].lastTry == 0 || nowMs - g_man[i].lastTry >= (passed ? (ulong)5000 : Backoff(g_man[i].fails))) { if(FixWanted(i, t, sym, isBuy, sl, tp)) { g_man[i].wantSL = 0; g_man[i].wantTP = 0; g_man[i].lastTry = 0; g_man[i].fails = 0; changed = true; } else { g_man[i].lastTry = nowMs; g_man[i].fails++; } } continue; } double pip = Pip(sym); double px = isBuy ? tk.bid : tk.ask; double gain = isBuy ? (px - open) / pip : (open - px) / pip; double nsl = sl; bool beNow = false; if(g_man[i].beTrig > 0 && !g_man[i].beDone && gain >= g_man[i].beTrig) { double be = NormPrice(sym, isBuy ? open + g_man[i].beOff * pip : open - g_man[i].beOff * pip); if(sl != 0 && ((isBuy && sl >= be) || (!isBuy && sl <= be))) { g_man[i].beDone = true; // 停損已經在保本價之外,不用動 changed = true; } else { nsl = be; beNow = true; } } if(g_man[i].trTrig > 0 && g_man[i].trDist > 0 && gain >= g_man[i].trTrig) { double cand = NormPrice(sym, isBuy ? px - g_man[i].trDist * pip : px + g_man[i].trDist * pip); // 至少動「步距、距離的 10%、1 pip」裡最大的那個,而且隔 5 秒以上才改(每個跳動都改會被券商當成洗單) double step = MathMax(MathMax(g_man[i].trStep, g_man[i].trDist * 0.1), 1.0) * pip; if(nowMs - g_man[i].lastMod >= 5000 && ((isBuy && (nsl == 0 || cand >= nsl + step) && cand < px) || (!isBuy && (nsl == 0 || cand <= nsl - step) && cand > px))) nsl = cand; } if(nsl != sl && (g_man[i].lastTry == 0 || nowMs - g_man[i].lastTry >= Backoff(g_man[i].fails))) // 改失敗就退避再試 { PrepTrade(sym, pmagic); if(g_trade.PositionModify(t, nsl, tp) && IsDone(g_trade.ResultRetcode())) { g_man[i].lastTry = 0; g_man[i].fails = 0; g_man[i].lastMod = nowMs; if(beNow) { g_man[i].beDone = true; changed = true; } } else { g_man[i].lastTry = nowMs; g_man[i].fails++; } } continue; } if(OrderSelect(t)) { if(g_man[i].expire > 0 && TimeCurrent() >= g_man[i].expire && (g_man[i].lastTry == 0 || nowMs - g_man[i].lastTry >= Backoff(g_man[i].fails))) { if(g_trade.OrderDelete(t)) Print("[Bridge] 掛單 #", t, " 到期,已刪除"); else { g_man[i].lastTry = nowMs; g_man[i].fails++; } } continue; } if(g_man[i].born > 0 && nowMs - g_man[i].born < 60000) continue; // 剛成交:部位清單可能還沒更新,1 分鐘內先留著 // 已經不在了(平倉或刪單)→ 移除 for(int j = i; j < ArraySize(g_man) - 1; j++) g_man[j] = g_man[j + 1]; ArrayResize(g_man, ArraySize(g_man) - 1); changed = true; } if(changed) SaveManage(); } // 移除已經不存在的單子註解 void CleanTags() { if(!Settled()) return; int w = 0; for(int i = 0; i < ArraySize(g_tagT); i++) { if(PositionSelectByTicket(g_tagT[i]) || OrderSelect(g_tagT[i])) { g_tagT[w] = g_tagT[i]; g_tagC[w] = g_tagC[i]; w++; } } if(w != ArraySize(g_tagT)) { ArrayResize(g_tagT, w); ArrayResize(g_tagC, w); SaveTags(); } } //──────────────────────────── 每日虧損保護 ──────────────────────────── void DailyGuard() { if(!g_ready || TimeCurrent() <= 0) return; double bal = AccountInfoDouble(ACCOUNT_BALANCE), eq = AccountInfoDouble(ACCOUNT_EQUITY); if(bal <= 0) return; // 帳戶資料還沒載入,不要把起始值記成 0 int k = DayKey(); string gk = "BridgeEA_" + g_login + "_daykey", gs = "BridgeEA_" + g_login + "_daystart"; string gb = "BridgeEA_" + g_login + "_dayblock", gl = "BridgeEA_" + g_login + "_daylimit"; if(k != g_dayKey || g_dayStart <= 0) { g_dayKey = k; g_dayBlocked = false; g_dayFlattened = false; g_dayOrdersClean = true; if(GlobalVariableCheck(gk) && (int)GlobalVariableGet(gk) == k && GlobalVariableGet(gs) > 0) g_dayStart = GlobalVariableGet(gs); // 今天已經記過(EA 重開、改設定):沿用當時的起始 else { g_dayStart = MathMax(bal, eq); double atStart = bal - ClosedToday(); // 換日時的餘額:EA 沒在跑(重開、斷線)時已經平倉的虧損也算回去 if(atStart > g_dayStart) g_dayStart = atStart; GlobalVariableSet(gk, k); GlobalVariableSet(gs, g_dayStart); GlobalVariablesFlush(); } if(InpDailyLossPct > 0 && GlobalVariableCheck(gb) && (int)GlobalVariableGet(gb) == k && GlobalVariableCheck(gl) && InpDailyLossPct <= GlobalVariableGet(gl) + 1e-9) { g_dayBlocked = true; // 今天重開之前已經碰過上限:照樣不開新倉(上限關掉或調高了就不沿用) g_dayOrdersClean = false; g_lastOrdTry = 0; } } if(InpDailyLossPct <= 0) return; double loss = (g_dayStart - eq) / g_dayStart * 100.0; if(loss >= InpDailyLossPct && !g_dayBlocked) { g_dayBlocked = true; GlobalVariableSet(gb, k); // EA 重開(改設定、MT5 重開)也記得今天已經擋了 GlobalVariableSet(gl, InpDailyLossPct); GlobalVariablesFlush(); g_dayOrdersClean = false; g_lastOrdTry = 0; PrintFormat("[Bridge] 今天虧損 %.2f%% 達上限 %.2f%%,停止開新倉", loss, InpDailyLossPct); } if(g_dayBlocked && !g_dayOrdersClean && (g_lastOrdTry == 0 || GetTickCount64() - g_lastOrdTry >= 30000)) { bool first = (g_lastOrdTry == 0); g_lastOrdTry = GetTickCount64(); string e = ""; int nd = DeleteOrders("", InpMagic, true, true, true, true, "", e); for(int i = 0; i < ArraySize(g_magics); i++) if(g_magics[i] != InpMagic) nd += DeleteOrders("", g_magics[i], true, true, true, true, "", e); g_dayOrdersClean = (e == ""); // 刪不掉的(休市、斷線)30 秒後再試 if(nd > 0) Print("[Bridge] 每日風控:刪掉 ", nd, " 張掛單(免得之後成交)"); if(e != "" && first) Print("[Bridge] 每日風控:有掛單刪不掉(", e, "),每 30 秒重試"); } if(g_dayBlocked && InpDailyFlatten && !g_dayFlattened && GetTickCount64() - g_lastFlatTry >= 30000) { g_lastFlatTry = GetTickCount64(); SSig s; SRes r; s.id = "daily"; s.age = 0; s.cmd = "flatten"; s.sym = "*"; ArrayResize(s.k, 0); ArrayResize(s.v, 0); DoFlatten(s, r); g_dayFlattened = (r.status == "done"); // 沒平乾淨 30 秒後再試 Print("[Bridge] 每日虧損保護:", r.msg); } } // 設成「只在 MQL5 VPS 執行」而且這份在自己的電腦上:完全不動(不連網站、不顧停損、不管每日虧損), // 不然本機這份會跟 VPS 上那份搶同一個授權碼 bool Standby() { return InpRunWhere == BR_WHERE_VPS && !TerminalInfoInteger(TERMINAL_VPS); } void UpdateComment() { string s = "Bridge EA " + EA_VER + "\n" + "網站:" + g_base + " " + g_status + (g_lastErr != "" ? "\n⚠ " + g_lastErr : "") + "\n" + "授權碼:" + InpLicense + " MT5:" + g_login + (IsHedging() ? "(對沖)" : "(淨額)") + "\n" + "已處理訊號:" + IntegerToString(g_processed) + " 連線延遲:" + IntegerToString((long)g_lastRtt) + " ms\n" + (g_lastSignal != "" ? "最後一筆:" + g_lastSignal + "\n" : "") + (ArraySize(g_schKey) > 0 ? "⏰ 預約中 " + IntegerToString(ArraySize(g_schKey)) + " 筆\n" : "") + (g_paused ? "⏸ 網站暫停中(只平倉、不開新倉)\n" : "") + (g_dayBlocked ? "⛔ 今日虧損達上限,停止開新倉\n" : ""); Comment(s); } //──────────────────────────── 事件 ──────────────────────────── // MT5 連上券商、登入、部位同步完(連上後等 3 秒)才處理訊號;第一次就緒時讀存檔 bool CheckReady() { bool conn = TerminalInfoInteger(TERMINAL_CONNECTED) && AccountInfoInteger(ACCOUNT_LOGIN) != 0 && AccountInfoDouble(ACCOUNT_BALANCE) > 0; if(!conn) { g_connSince = 0; return false; } if(g_connSince == 0) g_connSince = GetTickCount64(); if(GetTickCount64() - g_connSince < 3000) return false; if(!g_ready) { g_login = IntegerToString(AccountInfoInteger(ACCOUNT_LOGIN)); LoadDone(); LoadSched(); LoadTags(); LoadManage(); LoadMagics(); g_ready = true; g_trade.SetMarginMode(); // OnInit 時帳戶資訊可能還沒載入:不重設的話對沖帳戶的部分平倉會送不出去 RememberMagic(InpMagic); // 今天的起始權益、是否已經擋單:第一次 DailyGuard 換日時從存檔讀(跟「今天是哪一天」一起決定) if(!IsHedging()) Print("[Bridge] 注意:這是淨額(Netting)帳戶,同一商品多支策略會合在一起;建議用對沖(Hedging)帳戶"); PrintFormat("[Bridge] 就緒:%s,授權碼 %s,MT5 %s", g_base, InpLicense, g_login); } return true; } int OnInit() { g_base = Trim(InpServerURL); while(StringLen(g_base) > 0 && StringSubstr(g_base, StringLen(g_base) - 1) == "/") g_base = StringSubstr(g_base, 0, StringLen(g_base) - 1); if(g_base == "" || Trim(InpLicense) == "" || Trim(InpEAKey) == "") { Alert("Bridge EA:請填網站網址、授權碼、EA 金鑰(網站「帳戶」頁)"); return INIT_PARAMETERS_INCORRECT; } if(StringFind(g_base, "https://") != 0 && StringFind(g_base, "http://") != 0) { Alert("Bridge EA:網站網址要以 https:// 開頭"); return INIT_PARAMETERS_INCORRECT; } g_ready = false; // 存檔等 MT5 連上券商、知道帳號之後才讀(CheckReady) g_connSince = 0; g_instance = ""; g_login = "0"; ArrayResize(g_acks, 0); ArrayResize(g_magics, 0); ArrayResize(g_doneId, 0); ArrayResize(g_doneAck, 0); ArrayResize(g_tagT, 0); ArrayResize(g_tagC, 0); ArrayResize(g_man, 0); g_dayKey = 0; g_dayStart = 0; g_dayBlocked = false; g_dayFlattened = false; g_dayOffOk = false; g_polledOk = false; g_pollAt = 0; g_backoff = 0; g_failSince = 0; g_failNotified = false; MathSrand((uint)(GetTickCount64() ^ (ulong)TimeLocal() ^ (ulong)ChartID())); g_session = ""; for(int i = 0; i < 16; i++) g_session += StringSubstr("0123456789abcdef", MathRand() % 16, 1); FolderCreate(DIR_NAME); g_trade.SetMarginMode(); g_trade.LogLevel(LOG_LEVEL_ERRORS); EventSetMillisecondTimer((int)MathMax(50, InpPollMs)); g_lastHb = 0; g_lastPoll = 0; g_lastClean = GetTickCount64(); g_status = Standby() ? "本機待命:設定為「只在 MQL5 VPS 執行」,這份不連網站、不下單" : "等 MT5 連上券商…"; UpdateComment(); PrintFormat("[Bridge] 啟動:%s,授權碼 %s%s", g_base, InpLicense, Standby() ? "(本機待命,只在 MQL5 VPS 執行)" : ""); return INIT_SUCCEEDED; } void OnDeinit(const int reason) { EventKillTimer(); if(g_ready && g_owner) // 還沒就緒時帳號未知、或被擋下的第二個 EA:不要覆蓋存檔 { SaveDone(); SaveTags(); SaveManage(); SaveMagics(); } Comment(""); } void OnTimer() { if(Standby()) return; if(!CheckReady()) { g_status = g_ready ? "MT5 跟券商斷線中,暫停處理訊號" : "等 MT5 連上券商…"; if(g_ready && GetTickCount64() - g_lastHb >= (ulong)MathMax(2, InpHeartbeatSec) * 1000) { SendHeartbeat(); // 讓網站知道 MT5 斷線了 g_lastHb = GetTickCount64(); } UpdateComment(); return; } if(g_owner) { if(g_dayKey == 0) DailyGuard(); // 重開後第一次:先算每日風控(今天是不是已經擋了),預約的單才不會搶在前面 if(g_polledOk && g_srvAt > 0) RunScheduled(); // 預約的單最優先:準時(重開後要先輪詢成功、量過網站的時鐘) DailyGuard(); if(!SchedSoon()) Manage(); // 先顧停損、保本、追蹤(網路呼叫可能卡幾秒) } if(GetTickCount64() - g_lastPoll >= (ulong)(MathMax(50, InpPollMs) + g_backoff)) { DoPoll(); g_lastPoll = GetTickCount64(); if(g_owner && g_polledOk && g_srvAt > 0) RunScheduled(); // 輪詢為了預約提早回來:馬上做 } FlushAcks(); if(g_backoff == 0 && !SchedSoon() && GetTickCount64() - g_lastHb >= (ulong)MathMax(2, InpHeartbeatSec) * 1000) { SendHeartbeat(); g_lastHb = GetTickCount64(); } if(g_owner && !SchedSoon()) Manage(); if(g_owner && GetTickCount64() - g_lastClean >= 600000) { CleanTags(); g_lastClean = GetTickCount64(); } UpdateComment(); } void OnTick() { if(!Standby() && g_owner && Settled() && !SchedSoon()) Manage(); } //+------------------------------------------------------------------+