//+------------------------------------------------------------------+ //| Jkinstrading_Bridge.mq5 | //| Universal bridge between Jkinstrading and any MetaTrader 5 | //| broker account (Exness, Deriv, XM, IC Markets, FBS, Pepperstone | //| and every other MT5 server). | //| | //| The robot brain runs in the Jkinstrading app. This EA streams | //| prices to it, receives commands, executes them and manages the | //| money based stops, targets, partial closes and trailing locally. | //| Works on hedging and netting accounts. | //+------------------------------------------------------------------+ #property copyright "Jkinstrading" #property version "1.10" #property description "Jkinstrading bridge: streams prices to the app, executes its commands, manages money stops locally." #include input group "=== Jkinstrading connection ===" input string InpServerUrl = "https://your-app-url"; // App URL, no trailing slash input string InpApiKey = "jkt_xxxxxxxxxxxxxxxx"; // Connection key from the Platforms page input int InpSyncSeconds = 5; // Seconds between syncs input int InpBarsToSend = 200; // Closes sent per sync input string InpTradeSymbol = ""; // Symbol ("" = chart symbol) input group "=== Execution ===" input long InpMagic = 505050; // Magic number input int InpSlippage = 30; // Deviation in points input string InpComment = "Jkinstrading"; // Order comment input bool InpAllowTrade = true; // Master switch on this terminal input group "=== Local fallbacks (used until the first sync answers) ===" input double InpFbLots = 0.10; // Lot size input double InpFbSL = 20.0; // Stop loss in money input double InpFbTP1 = 10.0; // Target 1 in money input double InpFbTP2 = 20.0; // Target 2 in money input double InpFbTP3 = 40.0; // Target 3 in money //--- state received from the app CTrade trade; string g_symbol = ""; string g_url = ""; bool g_running = false; bool g_synced = false; double g_lots = 0.10; double g_sl = 20.0; double g_tp1 = 10.0; double g_tp2 = 20.0; double g_tp3 = 40.0; bool g_usePartial = true; double g_partial1 = 50.0; double g_partial2 = 25.0; double g_lockAfterTP1 = 2.0; bool g_useBE = true; double g_beTrigger = 8.0; double g_beLock = 2.0; bool g_useTrail = true; double g_trailStart = 15.0; double g_trailDist = 8.0; double g_trailStep = 2.0; //--- symbol cache int g_digits = 0; double g_point = 0.0; double g_volStep = 0.0; double g_volMin = 0.0; double g_volMax = 0.0; int g_volDigits = 2; //--- command acknowledgements waiting to be reported string g_done = ""; //+------------------------------------------------------------------+ //| Init | //+------------------------------------------------------------------+ int OnInit() { g_symbol = (StringLen(InpTradeSymbol)>0 ? InpTradeSymbol : _Symbol); if(!SymbolSelect(g_symbol,true)) { Print("Init error: symbol ",g_symbol," is not available on this account."); return(INIT_PARAMETERS_INCORRECT); } g_url = InpServerUrl; while(StringLen(g_url)>0 && StringSubstr(g_url,StringLen(g_url)-1,1)=="/") g_url = StringSubstr(g_url,0,StringLen(g_url)-1); if(StringLen(g_url)<8 || StringFind(g_url,"http")!=0) { Print("Init error: set InpServerUrl to the Jkinstrading app address."); return(INIT_PARAMETERS_INCORRECT); } if(StringLen(InpApiKey)<8) { Print("Init error: paste the connection key from the Platforms page."); return(INIT_PARAMETERS_INCORRECT); } if(InpSyncSeconds<1) { Print("Init error: sync interval must be 1 second or more."); return(INIT_PARAMETERS_INCORRECT); } g_digits = (int)SymbolInfoInteger(g_symbol,SYMBOL_DIGITS); g_point = SymbolInfoDouble(g_symbol,SYMBOL_POINT); g_volStep = SymbolInfoDouble(g_symbol,SYMBOL_VOLUME_STEP); g_volMin = SymbolInfoDouble(g_symbol,SYMBOL_VOLUME_MIN); g_volMax = SymbolInfoDouble(g_symbol,SYMBOL_VOLUME_MAX); if(g_point<=0.0) g_point = 1.0/MathPow(10.0,(double)g_digits); if(g_volStep<=0.0) g_volStep = 0.01; if(g_volMin<=0.0) g_volMin = g_volStep; if(g_volMax<=0.0) g_volMax = 100.0; g_volDigits = 0; double step = g_volStep; while(step<1.0 && g_volDigits<8) { step *= 10.0; g_volDigits++; } g_lots = InpFbLots; g_sl = InpFbSL; g_tp1 = InpFbTP1; g_tp2 = InpFbTP2; g_tp3 = InpFbTP3; trade.SetExpertMagicNumber((ulong)InpMagic); trade.SetDeviationInPoints((ulong)MathMax(0,InpSlippage)); trade.SetTypeFillingBySymbol(g_symbol); trade.SetMarginMode(); trade.LogLevel(LOG_LEVEL_ERRORS); EventSetTimer(InpSyncSeconds); Print("Jkinstrading bridge online. Symbol ",g_symbol," url ",g_url); Sync(); return(INIT_SUCCEEDED); } void OnDeinit(const int reason) { EventKillTimer(); Print("Jkinstrading bridge stopped. Reason code ",(string)reason); } //+------------------------------------------------------------------+ //| Helpers | //+------------------------------------------------------------------+ string TimeframeName() { string name = EnumToString((ENUM_TIMEFRAMES)_Period); int cut = StringFind(name,"_"); if(cut>=0) name = StringSubstr(name,cut+1); return(name); } string UrlEncode(const string text) { string out = ""; int len = StringLen(text); for(int i=0; i=48 && code<=57) || (code>=65 && code<=90) || (code>=97 && code<=122) || ch=="-" || ch=="_" || ch=="." || ch=="~"); if(safe) out += ch; else if(ch==" ") out += "+"; else out += "%"+StringFormat("%02X",(int)code); } return(out); } double MoneyToPrice(const double money,const double volume) { if(money<=0.0 || volume<=0.0) return(0.0); double tickValue = SymbolInfoDouble(g_symbol,SYMBOL_TRADE_TICK_VALUE); double tickSize = SymbolInfoDouble(g_symbol,SYMBOL_TRADE_TICK_SIZE); if(tickValue<=0.0 || tickSize<=0.0) return(0.0); double perPrice = (tickValue/tickSize)*volume; if(perPrice<=0.0) return(0.0); return(money/perPrice); } double NormalizeLots(const double volume) { if(g_volStep<=0.0) return(0.0); double v = MathFloor(volume/g_volStep+0.5)*g_volStep; v = NormalizeDouble(v,g_volDigits); if(vg_volMax) v = g_volMax; return(NormalizeDouble(v,g_volDigits)); } double FloorLots(const double volume) { if(g_volStep<=0.0 || volume<=0.0) return(0.0); double v = MathFloor(volume/g_volStep+0.0000001)*g_volStep; return(NormalizeDouble(v,g_volDigits)); } double StopsDistance() { long level = (long)SymbolInfoInteger(g_symbol,SYMBOL_TRADE_STOPS_LEVEL); if(level<0) level = 0; return((double)level*g_point); } bool FreezeBlocks(const bool isBuy,const double currentSL,const double currentTP) { long level = (long)SymbolInfoInteger(g_symbol,SYMBOL_TRADE_FREEZE_LEVEL); if(level<=0) return(false); double freeze = (double)level*g_point; double bid = SymbolInfoDouble(g_symbol,SYMBOL_BID); double ask = SymbolInfoDouble(g_symbol,SYMBOL_ASK); if(isBuy) { if(currentSL>0.0 && (bid-currentSL)0.0 && (currentTP-bid)0.0 && (currentSL-ask)0.0 && (ask-currentTP)0.0 && sl>(bid-minDist)) sl = bid-minDist; if(tp>0.0 && tp<(ask+minDist)) tp = ask+minDist; } else { if(sl>0.0 && sl<(ask+minDist)) sl = ask+minDist; if(tp>0.0 && tp>(bid-minDist)) tp = bid-minDist; } if(sl<0.0) sl = 0.0; if(tp<0.0) tp = 0.0; if(sl>0.0) sl = NormalizeDouble(sl,g_digits); if(tp>0.0) tp = NormalizeDouble(tp,g_digits); } string GVName(const ulong ticket,const string suffix) { return("JKT_"+IntegerToString(InpMagic)+"_"+IntegerToString((long)ticket)+"_"+suffix); } int PositionStage(const ulong ticket) { string name = GVName(ticket,"stage"); if(!GlobalVariableCheck(name)) return(0); return((int)GlobalVariableGet(name)); } void SetPositionStage(const ulong ticket,const int stage) { GlobalVariableSet(GVName(ticket,"stage"),(double)stage); } double OriginalVolume(const ulong ticket,const double currentVolume) { string name = GVName(ticket,"vol"); if(!GlobalVariableCheck(name)) { GlobalVariableSet(name,currentVolume); return(currentVolume); } double stored = GlobalVariableGet(name); if(stored<=0.0) { GlobalVariableSet(name,currentVolume); return(currentVolume); } return(stored); } void CleanupGlobals() { string prefix = "JKT_"+IntegerToString(InpMagic)+"_"; for(int i=GlobalVariablesTotal()-1; i>=0; i--) { string name = GlobalVariableName(i); if(StringFind(name,prefix)!=0) continue; string rest = StringSubstr(name,StringLen(prefix)); int sep = StringFind(rest,"_"); if(sep<=0) continue; ulong ticket = (ulong)StringToInteger(StringSubstr(rest,0,sep)); if(ticket==0 || !PositionSelectByTicket(ticket)) GlobalVariableDel(name); } } //+------------------------------------------------------------------+ //| Position management (money stops, partials, trailing) | //+------------------------------------------------------------------+ bool MoveStopLoss(const ulong ticket,const bool isBuy,double newSL,double ¤tSL,const double currentTP) { if(newSL<=0.0) return(false); newSL = NormalizeDouble(newSL,g_digits); double tolerance = g_point*0.5; if(isBuy && currentSL>0.0 && newSL<=(currentSL+tolerance)) return(false); if(!isBuy && currentSL>0.0 && newSL>=(currentSL-tolerance)) return(false); double minDist = StopsDistance(); double bid = SymbolInfoDouble(g_symbol,SYMBOL_BID); double ask = SymbolInfoDouble(g_symbol,SYMBOL_ASK); if(isBuy && newSL>(bid-minDist)) return(false); if(!isBuy && newSL<(ask+minDist)) return(false); if(FreezeBlocks(isBuy,currentSL,currentTP)) return(false); double tp = (currentTP>0.0 ? NormalizeDouble(currentTP,g_digits) : 0.0); if(!trade.PositionModify(ticket,newSL,tp)) { Print("Modify SL failed, ticket ",(string)ticket," retcode=",(string)trade.ResultRetcode()," ", trade.ResultRetcodeDescription()); return(false); } currentSL = newSL; return(true); } void ClosePartial(const ulong ticket,const double originalVolume,const double currentVolume,const double percent) { if(percent<=0.0 || currentVolume<=0.0) return; double want = FloorLots(originalVolume*percent/100.0); if(want<=0.0) return; if(want>(currentVolume-g_volStep*0.5)) want = FloorLots(currentVolume-g_volStep); if(want=target); return(marketPrice<=target); } void ManagePositions() { for(int i=PositionsTotal()-1; i>=0; i--) { ulong ticket = PositionGetTicket(i); if(ticket==0) continue; if(!PositionSelectByTicket(ticket)) continue; if(PositionGetString(POSITION_SYMBOL)!=g_symbol) continue; if(PositionGetInteger(POSITION_MAGIC)!=InpMagic) continue; bool isBuy = (PositionGetInteger(POSITION_TYPE)==(long)POSITION_TYPE_BUY); double curVol = PositionGetDouble(POSITION_VOLUME); double entry = PositionGetDouble(POSITION_PRICE_OPEN); double curSL = PositionGetDouble(POSITION_SL); double curTP = PositionGetDouble(POSITION_TP); double profit = PositionGetDouble(POSITION_PROFIT); double bid = SymbolInfoDouble(g_symbol,SYMBOL_BID); double ask = SymbolInfoDouble(g_symbol,SYMBOL_ASK); double market = (isBuy ? bid : ask); if(curVol<=0.0 || entry<=0.0 || market<=0.0) continue; double origVol = OriginalVolume(ticket,curVol); int stage = PositionStage(ticket); double tp1Price = TargetPrice(entry,isBuy,g_tp1,origVol); double tp2Price = TargetPrice(entry,isBuy,g_tp2,origVol); if(stage<1 && TargetReached(isBuy,market,tp1Price)) { if(g_usePartial) ClosePartial(ticket,origVol,curVol,g_partial1); SetPositionStage(ticket,1); double lockDist = MoneyToPrice(g_lockAfterTP1,origVol); if(lockDist>0.0) MoveStopLoss(ticket,isBuy,(isBuy ? entry+lockDist : entry-lockDist),curSL,curTP); continue; } if(stage==1 && TargetReached(isBuy,market,tp2Price)) { if(g_usePartial) ClosePartial(ticket,origVol,curVol,g_partial2); SetPositionStage(ticket,2); MoveStopLoss(ticket,isBuy,(tp1Price>0.0 ? tp1Price : entry),curSL,curTP); continue; } if(g_useBE && g_beTrigger>0.0 && profit>=g_beTrigger) { double lockDist = MoneyToPrice(g_beLock,curVol); double target = (g_beLock<=0.0 ? entry : (isBuy ? entry+lockDist : entry-lockDist)); MoveStopLoss(ticket,isBuy,target,curSL,curTP); } if(g_useTrail && g_trailDist>0.0 && profit>=g_trailStart) { double trailDist = MoneyToPrice(g_trailDist,curVol); double stepDist = MoneyToPrice(g_trailStep,curVol); if(trailDist>0.0) { double candidate = (isBuy ? market-trailDist : market+trailDist); bool improves = true; if(curSL>0.0 && stepDist>0.0) improves = (isBuy ? (candidate-curSL)>=stepDist : (curSL-candidate)>=stepDist); if(improves) MoveStopLoss(ticket,isBuy,candidate,curSL,curTP); } } } } //+------------------------------------------------------------------+ //| Counting and closing | //+------------------------------------------------------------------+ int CountPositions(const int direction) { int count = 0; for(int i=PositionsTotal()-1; i>=0; i--) { ulong ticket = PositionGetTicket(i); if(ticket==0 || !PositionSelectByTicket(ticket)) continue; if(PositionGetString(POSITION_SYMBOL)!=g_symbol) continue; if(PositionGetInteger(POSITION_MAGIC)!=InpMagic) continue; long type = PositionGetInteger(POSITION_TYPE); if(direction>0 && type!=(long)POSITION_TYPE_BUY) continue; if(direction<0 && type!=(long)POSITION_TYPE_SELL) continue; count++; } return(count); } double FloatingProfit() { double sum = 0.0; for(int i=PositionsTotal()-1; i>=0; i--) { ulong ticket = PositionGetTicket(i); if(ticket==0 || !PositionSelectByTicket(ticket)) continue; if(PositionGetString(POSITION_SYMBOL)!=g_symbol) continue; if(PositionGetInteger(POSITION_MAGIC)!=InpMagic) continue; sum += PositionGetDouble(POSITION_PROFIT); } return(sum); } int ClosePositions(const int direction) { int closed = 0; for(int i=PositionsTotal()-1; i>=0; i--) { ulong ticket = PositionGetTicket(i); if(ticket==0 || !PositionSelectByTicket(ticket)) continue; if(PositionGetString(POSITION_SYMBOL)!=g_symbol) continue; if(PositionGetInteger(POSITION_MAGIC)!=InpMagic) continue; bool isBuy = (PositionGetInteger(POSITION_TYPE)==(long)POSITION_TYPE_BUY); if(direction>0 && !isBuy) continue; if(direction<0 && isBuy) continue; if(FreezeBlocks(isBuy,PositionGetDouble(POSITION_SL),PositionGetDouble(POSITION_TP))) continue; if(trade.PositionClose(ticket)) { GlobalVariableDel(GVName(ticket,"stage")); GlobalVariableDel(GVName(ticket,"vol")); closed++; } else Print("Close failed, ticket ",(string)ticket," retcode=",(string)trade.ResultRetcode()," ", trade.ResultRetcodeDescription()); } return(closed); } bool OpenTrade(const bool isBuy,const double requestedLots) { double lots = NormalizeLots(requestedLots>0.0 ? requestedLots : g_lots); if(lots<=0.0) return(false); double price = (isBuy ? SymbolInfoDouble(g_symbol,SYMBOL_ASK) : SymbolInfoDouble(g_symbol,SYMBOL_BID)); if(price<=0.0) return(false); double slDist = MoneyToPrice(g_sl,lots); double tpDist = MoneyToPrice(g_tp3,lots); double sl = 0.0; double tp = 0.0; if(slDist>0.0) sl = (isBuy ? price-slDist : price+slDist); if(tpDist>0.0) tp = (isBuy ? price+tpDist : price-tpDist); AdjustStops(isBuy,sl,tp); bool ok = (isBuy ? trade.Buy(lots,g_symbol,0.0,sl,tp,InpComment) : trade.Sell(lots,g_symbol,0.0,sl,tp,InpComment)); if(!ok) { Print("Open ",(isBuy ? "BUY" : "SELL")," failed, retcode=",(string)trade.ResultRetcode()," ", trade.ResultRetcodeDescription()); return(false); } Print("Opened ",(isBuy ? "BUY" : "SELL")," ",DoubleToString(lots,g_volDigits)," ",g_symbol, " at ",DoubleToString(trade.ResultPrice(),g_digits)); return(true); } //+------------------------------------------------------------------+ //| Protocol | //+------------------------------------------------------------------+ void Acknowledge(const string id,const string result) { if(StringLen(g_done)>0) g_done += ","; g_done += id+":"+result; } void ApplyStatus(string &parts[]) { int n = ArraySize(parts); if(n<18) return; g_running = (StringToInteger(parts[1])==1); g_lots = StringToDouble(parts[2]); g_sl = StringToDouble(parts[3]); g_tp1 = StringToDouble(parts[4]); g_tp2 = StringToDouble(parts[5]); g_tp3 = StringToDouble(parts[6]); g_usePartial = (StringToInteger(parts[7])==1); g_partial1 = StringToDouble(parts[8]); g_partial2 = StringToDouble(parts[9]); g_lockAfterTP1 = StringToDouble(parts[10]); g_useBE = (StringToInteger(parts[11])==1); g_beTrigger = StringToDouble(parts[12]); g_beLock = StringToDouble(parts[13]); g_useTrail = (StringToInteger(parts[14])==1); g_trailStart = StringToDouble(parts[15]); g_trailDist = StringToDouble(parts[16]); g_trailStep = StringToDouble(parts[17]); if(g_lots<=0.0) g_lots = InpFbLots; g_synced = true; } void ExecuteCommand(string &parts[]) { int n = ArraySize(parts); if(n<4) return; string id = parts[1]; string kind = parts[2]; string arg = parts[3]; double lots = (n>4 ? StringToDouble(parts[4]) : 0.0); if(!InpAllowTrade) { Acknowledge(id,"blocked-terminal"); return; } if(kind=="OPEN") { bool isBuy = (arg=="BUY"); bool ok = OpenTrade(isBuy,lots); Acknowledge(id,(ok ? "opened "+arg : "error "+(string)trade.ResultRetcode())); return; } if(kind=="CLOSE") { int dir = 0; if(arg=="BUY") dir = 1; if(arg=="SELL") dir = -1; int closed = ClosePositions(dir); Acknowledge(id,"closed "+(string)closed); return; } Acknowledge(id,"unknown-command"); } void HandleResponse(string response) { StringReplace(response,"\r",""); string lines[]; int count = StringSplit(response,(ushort)10,lines); for(int i=0; i0) series += ","; series += DoubleToString(closes[i],g_digits); } datetime bar = (datetime)SeriesInfoInteger(g_symbol,_Period,SERIES_LASTBAR_DATE); string body = "key="+UrlEncode(InpApiKey)+ "&platform="+UrlEncode("MetaTrader 5")+ "&symbol="+UrlEncode(g_symbol)+ "&tf="+UrlEncode(TimeframeName())+ "&bar="+IntegerToString((long)bar)+ "&bid="+DoubleToString(SymbolInfoDouble(g_symbol,SYMBOL_BID),g_digits)+ "&ask="+DoubleToString(SymbolInfoDouble(g_symbol,SYMBOL_ASK),g_digits)+ "&spread="+IntegerToString((long)SymbolInfoInteger(g_symbol,SYMBOL_SPREAD))+ "&balance="+DoubleToString(AccountInfoDouble(ACCOUNT_BALANCE),2)+ "&equity="+DoubleToString(AccountInfoDouble(ACCOUNT_EQUITY),2)+ "¤cy="+UrlEncode(AccountInfoString(ACCOUNT_CURRENCY))+ "&buys="+IntegerToString(CountPositions(1))+ "&sells="+IntegerToString(CountPositions(-1))+ "&floating="+DoubleToString(FloatingProfit(),2)+ "&done="+UrlEncode(g_done)+ "&closes="+series; int len = StringLen(body); char post[]; char result[]; string resultHeaders; ArrayResize(post,len); StringToCharArray(body,post,0,len,CP_UTF8); ResetLastError(); int code = WebRequest("POST",g_url+"/api/sync", "Content-Type: application/x-www-form-urlencoded\r\n", 5000,post,result,resultHeaders); if(code==-1) { int err = GetLastError(); Print("WebRequest failed, error ",(string)err, ". Allow ",g_url," in Tools > Options > Expert Advisors > Allow WebRequest for listed URL."); return; } if(code!=200) { Print("Jkinstrading answered HTTP ",(string)code); return; } g_done = ""; HandleResponse(CharArrayToString(result,0,ArraySize(result),CP_UTF8)); } //+------------------------------------------------------------------+ //| Events | //+------------------------------------------------------------------+ void OnTimer() { Sync(); CleanupGlobals(); } void OnTick() { ManagePositions(); Comment("Jkinstrading bridge | ",g_symbol, " | robot: ",(g_running ? "RUNNING" : "PAUSED"), " | synced: ",(g_synced ? "yes" : "no"), " | lots: ",DoubleToString(g_lots,g_volDigits)); } //+------------------------------------------------------------------+