#property strict #property version "1.10" #property description "SignalBridge MT5 connector: market orders, exact broker symbols, no order replay." input string BridgeUrl="https://signalbridgeadzean.duckdns.org/mt5/YOUR_USER_ID"; input string BridgeToken=""; input long ExpectedLogin=0; input string ExpectedServer=""; input bool AllowLive=false; input double MaxLots=0.10; input int MaxSpreadPoints=100; input int DeviationPoints=20; input ulong MagicNumber=320032; int journal=INVALID_HANDLE; string pending="",stopPrefix="",stopLabel=""; string Quote(string s){StringReplace(s,"\\","\\\\");StringReplace(s,"\"","\\\"");StringReplace(s,"\r","\\r");StringReplace(s,"\n","\\n");StringReplace(s,"\t","\\t");return "\""+s+"\"";} string Mode(){return AccountInfoInteger(ACCOUNT_TRADE_MODE)==ACCOUNT_TRADE_MODE_REAL?"live":"demo";} string Identity(){return "\"login\":"+Quote((string)AccountInfoInteger(ACCOUNT_LOGIN))+",\"server\":"+Quote(AccountInfoString(ACCOUNT_SERVER))+",\"account_mode\":"+Quote(Mode());} bool Matches(){return AccountInfoInteger(ACCOUNT_LOGIN)==ExpectedLogin && AccountInfoString(ACCOUNT_SERVER)==ExpectedServer && (Mode()!="live"||AllowLive) && AccountInfoInteger(ACCOUNT_TRADE_MODE)!=ACCOUNT_TRADE_MODE_CONTEST;} int Send(string action,string body,string &response){char data[],result[];string headers;int size=StringToCharArray(body,data,0,WHOLE_ARRAY,CP_UTF8);ArrayResize(data,size-1);ResetLastError();int code=WebRequest("POST",BridgeUrl+"/"+action,"Content-Type: application/json\r\nAuthorization: Bearer "+BridgeToken+"\r\n",5000,data,result,headers);response=CharArrayToString(result,0,WHOLE_ARRAY,CP_UTF8);return code;} bool Save(string value){if(!FileSeek(journal,0,SEEK_SET))return false;if(FileWriteString(journal,value+"\n")==0)return false;FileFlush(journal);pending=value;return true;} string Ack(long id,string status,string message,uint ret=0,ulong order=0,ulong deal=0,double volume=0){return "{"+Identity()+",\"id\":"+(string)id+",\"status\":"+Quote(status)+",\"message\":"+Quote(message)+",\"retcode\":"+(string)ret+",\"order\":"+Quote((string)order)+",\"deal\":"+Quote((string)deal)+",\"filled_lots\":"+DoubleToString(volume,8)+"}";} void Reject(long id,string reason){Save(Ack(id,"REJECTED",reason));} int OnInit(){ if(StringFind(BridgeUrl,"https://")!=0 || StringFind(BridgeUrl,"/mt5/")<0 || StringLen(BridgeToken)<32 || ExpectedLogin<=0 || ExpectedServer=="" || MaxLots<=0 || MaxSpreadPoints<=0 || DeviationPoints<0 || !Matches()){Print("SignalBridge: check URL, pairing fields, account and AllowLive.");return INIT_PARAMETERS_INCORRECT;} uint hash=2166136261;for(int i=0;iMaxLots || !SymbolSelect(symbol,true)){Reject(id,"Account mode, symbol or local lot limit rejected.");return;} if(n==11 && (start<0||distance<0||trigger<0||offset<0||(start>0&&(distance<=0||distance>start))||(trigger>0&&offset>=trigger)||sl<=0)){Reject(id,"Invalid dynamic protection.");return;} double min=SymbolInfoDouble(symbol,SYMBOL_VOLUME_MIN),max=SymbolInfoDouble(symbol,SYMBOL_VOLUME_MAX),step=SymbolInfoDouble(symbol,SYMBOL_VOLUME_STEP); if(step<=0 || lotsmax || MathAbs(lots/step-MathRound(lots/step))>0.000001){Reject(id,"Invalid broker lot size/step. No rounding performed.");return;} MqlTick tick;if(!SymbolInfoTick(symbol,tick)||tick.bid<=0||tick.ask<=0||TimeTradeServer()-tick.time>30){Reject(id,"Missing or stale broker quote.");return;} double point=SymbolInfoDouble(symbol,SYMBOL_POINT);if(point<=0 || (tick.ask-tick.bid)/point>MaxSpreadPoints){Reject(id,"Spread exceeds local limit.");return;} long tradeMode=SymbolInfoInteger(symbol,SYMBOL_TRADE_MODE); if(tradeMode==SYMBOL_TRADE_MODE_DISABLED||tradeMode==SYMBOL_TRADE_MODE_CLOSEONLY||(tradeMode==SYMBOL_TRADE_MODE_LONGONLY&&side=="SELL")||(tradeMode==SYMBOL_TRADE_MODE_SHORTONLY&&side=="BUY")){Reject(id,"Symbol trading mode blocks requested side.");return;} // Refuse mixing positions: same-symbol manual/other-EA exposure or opposite directions. for(int i=PositionsTotal()-1;i>=0;i--){if(PositionGetTicket(i)>0 && PositionGetString(POSITION_SYMBOL)==symbol){Reject(id,"Existing symbol position. Manage/close it in MT5 first.");return;}} for(int i=OrdersTotal()-1;i>=0;i--){if(OrderGetTicket(i)>0&&OrderGetString(ORDER_SYMBOL)==symbol){Reject(id,"Existing pending order on symbol; review MT5 first.");return;}} int digits=(int)SymbolInfoInteger(symbol,SYMBOL_DIGITS); if((sl>0 && MathAbs(sl-NormalizeDouble(sl,digits))>point/100)||(tp>0 && MathAbs(tp-NormalizeDouble(tp,digits))>point/100)){Reject(id,"SL/TP precision does not match broker symbol.");return;} double gap=SymbolInfoInteger(symbol,SYMBOL_TRADE_STOPS_LEVEL)*point; if(side=="BUY" && ((sl>0 && sl>=tick.bid-gap)||(tp>0 && tp<=tick.bid+gap)) || side=="SELL" && ((sl>0 && sl<=tick.ask+gap)||(tp>0 && tp>=tick.ask-gap))){Reject(id,"SL/TP direction or broker stop distance invalid.");return;} MqlTradeRequest request={};MqlTradeResult result={};MqlTradeCheckResult check={}; request.action=TRADE_ACTION_DEAL;request.symbol=symbol;request.volume=lots;request.type=side=="BUY"?ORDER_TYPE_BUY:ORDER_TYPE_SELL;request.price=side=="BUY"?tick.ask:tick.bid;request.sl=sl;request.tp=tp;request.deviation=DeviationPoints;request.magic=MagicNumber;request.comment=(n==11?stopLabel:"SB-")+(string)id; if(StringLen(request.comment)>31){Reject(id,"Position label exceeds broker limit. No order sent.");return;} long filling=SymbolInfoInteger(symbol,SYMBOL_FILLING_MODE); if((filling&SYMBOL_FILLING_FOK)!=0)request.type_filling=ORDER_FILLING_FOK; else if((filling&SYMBOL_FILLING_IOC)!=0)request.type_filling=ORDER_FILLING_IOC; else if(SymbolInfoInteger(symbol,SYMBOL_TRADE_EXEMODE)!=SYMBOL_TRADE_EXECUTION_MARKET)request.type_filling=ORDER_FILLING_RETURN; else{Reject(id,"Broker filling policy unsupported.");return;} if(!OrderCheck(request,check)){Reject(id,"Broker preflight rejected: "+(string)check.retcode);return;} if(n==11){string k=stopPrefix+(string)id+"-";bool saved=GlobalVariableSet(k+"start",start)!=0 && GlobalVariableSet(k+"distance",distance)!=0 && GlobalVariableSet(k+"trigger",trigger)!=0 && GlobalVariableSet(k+"offset",offset)!=0 && GlobalVariableSet(k+"lots",lots)!=0 && GlobalVariableSet(k+"peak",0)!=0;GlobalVariablesFlush();if(!saved){Reject(id,"Cannot persist dynamic settings. No order sent.");return;}} bool sent=OrderSend(request,result);string status="UNKNOWN"; if(result.retcode==TRADE_RETCODE_DONE)status="FILLED"; else if(result.retcode==TRADE_RETCODE_DONE_PARTIAL)status="PARTIAL"; else if(result.retcode==TRADE_RETCODE_PLACED)status="PLACED"; else if(result.retcode!=0 && result.retcode!=TRADE_RETCODE_TIMEOUT && result.retcode!=TRADE_RETCODE_CONNECTION && result.retcode!=TRADE_RETCODE_ERROR)status="REJECTED"; if(!sent&&result.retcode==0)status="UNKNOWN"; if(!Save(Ack(id,status,"Broker return code "+(string)result.retcode,result.retcode,result.order,result.deal,result.volume))){Comment("Journal failure after OrderSend. Verify MT5 manually. No replay.");EventKillTimer();} } void ManageStops(){ if(!Matches()||!TerminalInfoInteger(TERMINAL_CONNECTED)||!MQLInfoInteger(MQL_TRADE_ALLOWED)||!TerminalInfoInteger(TERMINAL_TRADE_ALLOWED))return; for(int i=PositionsTotal()-1;i>=0;i--){ ulong ticket=PositionGetTicket(i);if(ticket==0||PositionGetInteger(POSITION_MAGIC)!=(long)MagicNumber)continue; string comment=PositionGetString(POSITION_COMMENT);if(StringFind(comment,stopLabel)!=0)continue; string k=stopPrefix+StringSubstr(comment,StringLen(stopLabel))+"-"; if(!GlobalVariableCheck(k+"lots")||MathAbs(PositionGetDouble(POSITION_VOLUME)-GlobalVariableGet(k+"lots"))>0.00000001)continue; string symbol=PositionGetString(POSITION_SYMBOL);MqlTick tick;if(!SymbolInfoTick(symbol,tick)||TimeTradeServer()-tick.time>30)continue; bool buy=PositionGetInteger(POSITION_TYPE)==POSITION_TYPE_BUY;double quote=buy?tick.bid:tick.ask,point=SymbolInfoDouble(symbol,SYMBOL_POINT),unit=SymbolInfoDouble(symbol,SYMBOL_TRADE_TICK_SIZE); if(quote<=0||point<=0||unit<=0)continue; double entry=PositionGetDouble(POSITION_PRICE_OPEN),old=PositionGetDouble(POSITION_SL),tp=PositionGetDouble(POSITION_TP),peak=GlobalVariableGet(k+"peak"),start=GlobalVariableGet(k+"start"),distance=GlobalVariableGet(k+"distance"),trigger=GlobalVariableGet(k+"trigger"),offset=GlobalVariableGet(k+"offset"); peak=peak==0?quote:buy?MathMax(peak,quote):MathMin(peak,quote);double sign=buy?1:-1,gain=sign*(peak-entry)/point,target=old; if(trigger>0&&gain>=trigger){double v=entry+sign*offset*point;target=target==0?v:buy?MathMax(target,v):MathMin(target,v);} if(start>0&&gain>=start){double v=peak-sign*distance*point;target=target==0?v:buy?MathMax(target,v):MathMin(target,v);} if(GlobalVariableSet(k+"peak",peak)==0){Print("Cannot persist dynamic watermark; existing SL retained.");continue;}GlobalVariablesFlush(); target=NormalizeDouble((buy?MathFloor(target/unit):MathCeil(target/unit))*unit,(int)SymbolInfoInteger(symbol,SYMBOL_DIGITS)); double gap=MathMax(SymbolInfoInteger(symbol,SYMBOL_TRADE_STOPS_LEVEL),SymbolInfoInteger(symbol,SYMBOL_TRADE_FREEZE_LEVEL))*point; if(target<=0||(buy?target>=quote-gap:target<=quote+gap)||(old>0&&(buy?target<=old:target>=old)))continue; MqlTradeRequest req={};MqlTradeResult res={};req.action=TRADE_ACTION_SLTP;req.position=ticket;req.symbol=symbol;req.sl=target;req.tp=tp;req.magic=MagicNumber; if(!OrderSend(req,res)||res.retcode!=TRADE_RETCODE_DONE)Print("Dynamic SL update not confirmed on ",ticket,": ",res.retcode,". Existing SL retained; verify terminal."); } }