//+------------------------------------------------------------------+ //| localHedgingClientCopierMt5.mq5 | //| Copyright 2025, MetaQuotes Ltd. | //| https://www.mqldevelopment.com/ | //+------------------------------------------------------------------+ #property copyright "Copyright 2025, MetaQuotes Ltd." #property link "https://www.mqldevelopment.com/" #property version "1.00" #define orderCount 2000 #define count1 50 #define testCounter 50 #define MaxOrders 20000 #define daysOfTradesToAdd 20 #include CTrade trade; //+------------------------------------------------------------------+ //| Expert initialization function | //+------------------------------------------------------------------+ struct historyTradesClientSide { ulong ticket; ulong magic; historyTradesClientSide() { ticket = -1; magic = 0; } }; historyTradesClientSide historyTradeStore[MaxOrders]; struct order { ulong ticket; double price; datetime opentime; string symbol; int ordertype; double lots; double stoploss; double takeprofit; double accountBalance; int contractSize; string comments; int magicNo; double closedPercentageOfTrade; order() { ticket =-1; closedPercentageOfTrade = 0; } }; struct clientOrder { ulong ticket; double price; datetime opentime; string symbol; int ordertype; double lots; double stoploss; double takeprofit; ulong magic; string comments; double masterLot; clientOrder() { ticket=-1; price=-1; symbol=Symbol(); ordertype=-1; lots=0; masterLot=0; stoploss=0; takeprofit=0; magic=0; comments=""; } }; clientOrder cod[orderCount]; struct masterOrder { datetime opentime; string symbol; ulong ordertype; double price; double lots; double stoploss; double takeprofit; ulong ticket; int magic; double accountBalance; int contractSize; string comment; masterOrder() { ticket=-1; price=-1; symbol=Symbol(); ordertype=-1; lots=0; stoploss=0; takeprofit=0; } }; masterOrder mod1[orderCount]; enum lot_option { fix, //Fixed Lot mul, //Multiplied Lot Balance, // Balance Base Multiplier slaveLotCal, }; enum tradeCopy_type { buy,//Buy Only sell,//Sell Only buySell,//Buy and Sell }; enum operation_code { Master, //Master Client, //Client }; sinput string string_0 = "<><><><><><> General SETTINGS <><><><><><>"; //__ input int slip = 5; // Master Order Variation in Pips input int sec = 10; // Master Order Expired After Seconds input tradeCopy_type tradeType = buySell; // Trades To Copy input lot_option lotoption = fix; // Lot Option input double mult = 1.0; // Multiplier (for Client) input double fixed = 0.1; // Fixed Lot (for Client) input double Bmult = 1; // Balance Multiplier (for Client) input double recoveryAmount = 3000; // Recovery Amount (for Client Lot) input double maxDd = 8000; // Max DrawDown (for Client Lot) input string suffix = ""; // Suffix input string symbolExclude = ""; // Symbol to Exclude input string prefix = ""; // Prefix // Heart Beat sinput string string_1 = "<><><><><><> HeartBeat Setting <><><><><><>"; //__ input string clientServer = ""; // Master Server input string mappingSymbol = "GOLD,XAUUSD;bitcoin,BTCUSD"; // Mapping Pairs Inp,Out;Inp,Out input string localApiKey = "U2FsdGVkX18vBY4H1uzQiZwuh8B++8VBtCGJ3yGr2XPII0qCodmfuhjssKu5oug1J4e97bkwPtDQLi4py1OODQ=="; // Local API Key input string localHB_req_link = "http://localhost/api/slastConnected"; // Request Link For LastConnected //+------------------------------------------------------------------+ //| | //+------------------------------------------------------------------+ //Global Variable int gmtDifference = 0; int filehandle; // Heart Beat long lastFileSize=0; datetime lastModified=0; bool contractChk = true;//Contract Checking bool doReversal = true; // Reverse Trades bool fileLastEmpty=false; long accountNumber=AccountInfoInteger(ACCOUNT_LOGIN); int counter=0,testCounterVar=0; order order_array[]; datetime lastModified1=0; long lastFileSize1=0; bool fileHandlerIssue=false; operation_code mode1=Client; //Working code int OnInit() { //--- accountNumber=AccountInfoInteger(ACCOUNT_LOGIN); EventSetMillisecondTimer(20); if(!ObjectFind(0,"mode") || ObjectGetString(0,"mode",OBJPROP_TEXT,0)!=EnumToString(mode1)+" Account") { ObjectDelete(0,"mode"); ObjectCreate(0,"mode",OBJ_LABEL,0,0,0); ObjectSetInteger(0,"mode",OBJPROP_XDISTANCE,10); ObjectSetInteger(0,"mode",OBJPROP_YDISTANCE,25); ObjectSetInteger(0,"mode",OBJPROP_CORNER,CORNER_RIGHT_UPPER); ObjectSetInteger(0,"mode",OBJPROP_ANCHOR,ANCHOR_RIGHT_UPPER); ObjectSetInteger(0,"mode",OBJPROP_COLOR,clrLightBlue); ObjectSetString(0,"mode",OBJPROP_TEXT,EnumToString(mode1)+" Account"); ObjectSetInteger(0,"mode",OBJPROP_FONTSIZE,14); } gmtDifference = (int)TimeCurrent() - (int)TimeGMT(); Print("GMT Difference(sec): ",gmtDifference); mapHistory(); //--- return(INIT_SUCCEEDED); } //+------------------------------------------------------------------+ //| Expert deinitialization function | //+------------------------------------------------------------------+ void OnDeinit(const int reason) { //--- EventKillTimer(); ObjectsDeleteAll(0,0,-1); } //+------------------------------------------------------------------+ //| Expert tick function | //+------------------------------------------------------------------+ void OnTick() { //--- } //+------------------------------------------------------------------+ void OnTimer() { gmtDifference = (int)TimeCurrent() - (int)TimeGMT(); read_history_file(); readData(); writeDataClientCof(); } //+------------------------------------------------------------------+ //| | //+------------------------------------------------------------------+ void writeDataClientCof() { int fileHandleClientCof; if(PositionsTotal()==0 && OrdersTotal()==0 && !fileLastEmpty && TerminalInfoInteger(TERMINAL_CONNECTED)) { fileHandleClientCof = FileOpen("COF_client.csv", FILE_WRITE|FILE_CSV|FILE_COMMON); if(fileHandleClientCof != INVALID_HANDLE) { Print("Writing file to empty"); FileWrite(fileHandleClientCof, ""); FileClose(fileHandleClientCof); fileLastEmpty = true; emptyStruct(); } else { Print(" Client Cof File handler issue:", GetLastError()); } } else { bool updationReq = checkOrderUpdate(); if(updationReq || fileHandlerIssue) { Print(" ------------------------------- Client Cof Start ------------------------------------------ "); fileHandleClientCof = FileOpen("COF_client.csv", FILE_WRITE|FILE_CSV|FILE_COMMON); if(fileHandleClientCof != INVALID_HANDLE) { fileHandlerIssue = false; for(int i = PositionsTotal()-1; i >= 0; i--) { ulong ticket = PositionGetTicket(i); if(PositionSelectByTicket(ticket)) { string time = TimeToString(PositionGetInteger(POSITION_TIME)-gmtDifference,TIME_DATE|TIME_SECONDS); string symbol = PositionGetString(POSITION_SYMBOL); double digits=getDoubleSymbolInfo(symbol,"digits"); int symbolContractSize=(int)getDoubleSymbolInfo(symbol,"contract"); ulong tempTicket = PositionGetInteger(POSITION_TICKET); if(suffix != "") symbol = StringSubstr(symbol, 0, StringFind(symbol, suffix, 0)); if(prefix != "") StringReplace(symbol, prefix, ""); long orderType = PositionGetInteger(POSITION_TYPE); double takeProfit = PositionGetDouble(POSITION_TP), stopLoss = PositionGetDouble(POSITION_SL); if(doReversal) { if(orderType == POSITION_TYPE_BUY) orderType = POSITION_TYPE_SELL; else if(orderType == POSITION_TYPE_SELL) orderType = POSITION_TYPE_BUY; takeProfit = PositionGetDouble(POSITION_SL); stopLoss = PositionGetDouble(POSITION_TP); } double sumOfClosed = dealOutLotsCheck(0, PositionGetInteger(POSITION_TICKET)); double currentLot = PositionGetDouble(POSITION_VOLUME); double totalLot = sumOfClosed + currentLot; double closedPercentage = 0.0; if(totalLot > 0.0) closedPercentage = (sumOfClosed / totalLot) * 100.0; Print(" Client Closed % = ", closedPercentage); string OrderToWrite = time+","+symbol+","+IntegerToString(orderType)+","+DoubleToString(PositionGetDouble(POSITION_PRICE_OPEN), (int)digits)+","+DoubleToString(PositionGetDouble(POSITION_VOLUME),2)+","+DoubleToString(stopLoss,(int) digits)+","+DoubleToString(takeProfit, (int) digits)+","+IntegerToString(PositionGetInteger(POSITION_TICKET))+","+IntegerToString(PositionGetInteger(POSITION_MAGIC))+","+(string)AccountInfoDouble(ACCOUNT_BALANCE)+","+DoubleToString(closedPercentage, 1)+","+(string)SymbolInfoDouble(PositionGetString(POSITION_SYMBOL),SYMBOL_TRADE_CONTRACT_SIZE)+PositionGetString(POSITION_COMMENT)+"\r\n"; FileWrite(filehandle,OrderToWrite); } } for(int i = OrdersTotal()-1; i >= 0; i--) { ulong ticket = OrderGetTicket(i); if(OrderSelect(ticket)) { string time = TimeToString(OrderGetInteger(ORDER_TIME_SETUP)-gmtDifference, TIME_DATE|TIME_SECONDS); string symbol = OrderGetString(ORDER_SYMBOL); double digits = getDoubleSymbolInfo(symbol,"digits"); if(suffix != "") symbol = StringSubstr(symbol, 0, StringFind(symbol, suffix, 0)); if(prefix != "") StringReplace(symbol, prefix, ""); long orderType = OrderGetInteger(ORDER_TYPE); double takeProfit = OrderGetDouble(ORDER_TP); double stopLoss = OrderGetDouble(ORDER_SL); if(doReversal) { if(orderType == ORDER_TYPE_BUY_STOP) orderType = ORDER_TYPE_SELL_LIMIT; else if(orderType == ORDER_TYPE_SELL_STOP) orderType = ORDER_TYPE_BUY_LIMIT; else if(orderType == ORDER_TYPE_BUY_LIMIT) orderType = ORDER_TYPE_SELL_STOP; else if(orderType == ORDER_TYPE_SELL_LIMIT) orderType = ORDER_TYPE_BUY_STOP; takeProfit = OrderGetDouble(ORDER_SL); stopLoss = OrderGetDouble(ORDER_TP); } double closedPercentage = 0; string OrderToWrite = time + "," + symbol + "," + IntegerToString(orderType) + "," + DoubleToString(OrderGetDouble(ORDER_PRICE_OPEN),(int)digits) + "," + DoubleToString(OrderGetDouble(ORDER_VOLUME_CURRENT),2) + "," + DoubleToString(stopLoss,(int)digits) + "," + DoubleToString(takeProfit,(int)digits) + "," + IntegerToString(OrderGetInteger(ORDER_TICKET)) + "," + IntegerToString(OrderGetInteger(ORDER_MAGIC)) + "," + (string)AccountInfoDouble(ACCOUNT_BALANCE) + "," + DoubleToString(closedPercentage) +","+ (string)SymbolInfoDouble(OrderGetString(ORDER_SYMBOL), SYMBOL_TRADE_CONTRACT_SIZE) + OrderGetString(ORDER_COMMENT) + "\r\n"; Print("Client Cof Writing Pending Order Block."); FileWrite(fileHandleClientCof, OrderToWrite); } } FileClose(fileHandleClientCof); fileLastEmpty = false; Print("Client Cof File Updated:", TimeCurrent()); } else { Print("Client Cof File Handle Issue:", GetLastError()); } Print(" ------------------------------- Client Cof End ------------------------------------------ "); } } } //+------------------------------------------------------------------+ //| | //+------------------------------------------------------------------+ bool checkOrderUpdate() { bool updationRequired=false,currCheck=false; for(int i = PositionsTotal()-1 ; i >= 0 ; i--) { ulong ticket = PositionGetTicket(i); if(PositionSelectByTicket(ticket)) { int orderIndex=-1; bool alreadyAdded=isOrderThere(ticket, orderIndex); if(!alreadyAdded) { currCheck=false; currCheck=addOrderMaster(ticket, "Market"); if(!updationRequired) updationRequired=currCheck; } else { if(orderIndex!=-1) { currCheck=false; currCheck=IsOrderChanged(PositionGetInteger(POSITION_TICKET),orderIndex, "Market"); if(!updationRequired) { updationRequired=currCheck; } } } } } for(int i = OrdersTotal()-1 ; i >= 0 ; i--) { ulong ticket = OrderGetTicket(i); if(OrderSelect(ticket)) { if(OrderGetInteger(ORDER_TYPE) != ORDER_TYPE_BUY && OrderGetInteger(ORDER_TYPE) != ORDER_TYPE_SELL && OrderGetInteger(ORDER_TYPE) != ORDER_TYPE_CLOSE_BY) { int orderIndex=-1; bool alreadyAdded=isOrderThere(ticket, orderIndex); if(!alreadyAdded) { Print("Inside pending Adding to master order: ",ticket," type: ",OrderGetInteger(ORDER_TYPE)," ",OrdersTotal()," ",ORDER_TYPE_CLOSE_BY); currCheck=false; currCheck=addOrderMaster(ticket, "Pending"); if(!updationRequired) updationRequired=currCheck; } else { if(orderIndex!=-1) { currCheck=false; currCheck=IsOrderChanged(OrderGetInteger(ORDER_TICKET), orderIndex, "Pending"); if(!updationRequired) { updationRequired=currCheck; } } } } } } for(int i=0; i=0; j--) { ulong ticket = PositionGetTicket(j); if(PositionSelectByTicket(ticket)) { if(ticket==mod1[i].ticket) { isPresent=true; break; } } } // Pending Order for(int j = OrdersTotal()-1; j>=0; j--) { ulong ticket = OrderGetTicket(j); if(OrderSelect(ticket)) { if(ticket==mod1[i].ticket) { isPresent=true; break; } } } if(!isPresent) { Print("Ticket is closed so removed from struct: ",mod1[i].ticket); mod1[i].ticket=-1; mod1[i].price=-1; mod1[i].symbol=""; mod1[i].ordertype=-1; mod1[i].lots=0; mod1[i].stoploss=0; mod1[i].takeprofit=0; currCheck=true; //currCheck=clearStructIndex(mod1[i].ticket); if(!updationRequired) updationRequired=currCheck; } } } return updationRequired; } //+------------------------------------------------------------------+ //| | //+------------------------------------------------------------------+ bool IsOrderChanged(ulong orderTicket, int index, string calledBy) { if(mod1[index].ticket!=-1) { if(calledBy == "Market") { if(PositionSelectByTicket(orderTicket)) { //Digits double digits=getDoubleSymbolInfo(PositionGetString(POSITION_SYMBOL),"digits"); double tp=NormalizeDouble(PositionGetDouble(POSITION_TP), (int)digits), sl=NormalizeDouble(PositionGetDouble(POSITION_SL),(int)digits), lot=NormalizeDouble(PositionGetDouble(POSITION_VOLUME),2); if(mod1[index].takeprofit!=tp || mod1[index].stoploss != sl || mod1[index].lots!=lot || mod1[index].ordertype!=PositionGetInteger(POSITION_TYPE) || mod1[index].price != PositionGetDouble(POSITION_PRICE_OPEN)) { Print(" Inside IsOrderChanged() ",mod1[index].lots," lot: ",lot," calledBy: ",calledBy," mod1 ticket ",mod1[index].ticket," orderTicket: ",orderTicket); // Time datetime time = (datetime)(PositionGetInteger(POSITION_TIME) - gmtDifference); mod1[index].opentime=time; mod1[index].lots=lot; mod1[index].stoploss=sl; mod1[index].takeprofit=tp; mod1[index].comment=PositionGetString(POSITION_COMMENT); mod1[index].ordertype=PositionGetInteger(POSITION_TYPE); mod1[index].price=PositionGetDouble(POSITION_PRICE_OPEN); return true; } } } if(calledBy == "Pending") { if(OrderSelect(orderTicket)) { double digits=getDoubleSymbolInfo(OrderGetString(ORDER_SYMBOL),"digits"); double tp=NormalizeDouble(OrderGetDouble(ORDER_TP), (int)digits), sl=NormalizeDouble(OrderGetDouble(ORDER_SL),(int)digits), lot=NormalizeDouble(OrderGetDouble(ORDER_VOLUME_CURRENT),2); if(mod1[index].takeprofit!=tp || mod1[index].stoploss != sl || mod1[index].lots!=lot || mod1[index].ordertype!=OrderGetInteger(ORDER_TYPE) || mod1[index].price != OrderGetDouble(ORDER_PRICE_OPEN)) { //time datetime time = (datetime)(OrderGetDouble(ORDER_PRICE_OPEN) - gmtDifference); mod1[index].opentime=time; mod1[index].lots=lot; mod1[index].stoploss=sl; mod1[index].takeprofit=tp; mod1[index].comment=OrderGetString(ORDER_COMMENT); mod1[index].ordertype=OrderGetInteger(ORDER_TYPE); mod1[index].price=OrderGetDouble(ORDER_PRICE_OPEN); return true; } } } } return false; } //+------------------------------------------------------------------+ //| | //+------------------------------------------------------------------+ bool addOrderMaster(ulong ticket, string calledBy) { for(int i=0; i=count1 && TerminalInfoInteger(TERMINAL_CONNECTED)) { if(testCounterVar==testCounter) { testCounterVar=0; } adminHeartBeat(); counter=0; } counter++; testCounterVar++; } else { clearOrderArray(); while(!FileIsEnding(filehandle)) { string OrderToRead = FileReadString(filehandle); string Order_specs []; StringSplit(OrderToRead,StringGetCharacter(",",0),Order_specs); Print("Array Size: ", ArraySize(Order_specs)); if(ArraySize(Order_specs) == 12 || ArraySize(Order_specs) == 13) { string symbol = getSymbol(Order_specs[1]);//prefix+Order_specs[1]+suffix; int orderType=StringToInteger(Order_specs[2]); if(StringFind(symbol,symbolExclude,0) < 0 && (((orderType==POSITION_TYPE_BUY||orderType==ORDER_TYPE_BUY_STOP ||orderType==ORDER_TYPE_SELL_STOP)&& (tradeType==0||tradeType==2)) || ((orderType==POSITION_TYPE_SELL||orderType==ORDER_TYPE_BUY_LIMIT ||orderType==ORDER_TYPE_SELL_LIMIT)&& (tradeType==1||tradeType==2))) ) { order_array[ArraySize(order_array)-1].symbol = symbol; order_array[ArraySize(order_array)-1].opentime = StringToTime(Order_specs[0]); order_array[ArraySize(order_array)-1].price = StringToDouble(Order_specs[3]); order_array[ArraySize(order_array)-1].ordertype = StringToInteger(Order_specs[2]); order_array[ArraySize(order_array)-1].lots = StringToDouble(Order_specs[4]); order_array[ArraySize(order_array)-1].stoploss = StringToDouble(Order_specs[5]); order_array[ArraySize(order_array)-1].takeprofit = StringToDouble(Order_specs[6]); order_array[ArraySize(order_array)-1].ticket = StringToInteger(Order_specs[7]); //Saving master order ticket to order magic number order_array[ArraySize(order_array)-1].magicNo = StringToInteger(Order_specs[7]); order_array[ArraySize(order_array)-1].accountBalance=StringToDouble(Order_specs[9]); order_array[ArraySize(order_array)-1].closedPercentageOfTrade = StringToDouble(Order_specs[10]); order_array[ArraySize(order_array)-1].contractSize=StringToInteger(Order_specs[11]); if(ArraySize(Order_specs) == 13) order_array[ArraySize(order_array)-1].comments=Order_specs[12]; else order_array[ArraySize(order_array)-1].comments=""; if(ArraySize(Order_specs) == 13) { StringReplace(Order_specs[12],"from #",""); StringReplace(Order_specs[12]," ",""); Print(" Order_specs[12] ",Order_specs[12]," order_array[ArraySize(order_array)-1].ticket ",order_array[ArraySize(order_array)-1].ticket); for(int l=0; l 0) { for(int i=PositionsTotal()-1; i>=0; i--) { ulong ticket = PositionGetTicket(i); if(PositionSelectByTicket(ticket)) { if(history_ticket_present(PositionGetInteger(POSITION_MAGIC))) if(!trade.PositionClose(ticket)) { Print(" Order Close Error on No Master Trade: "+IntegerToString(GetLastError())); } else Print(" ------------- Order Close by empty array ------------------ "); } } } if(OrdersTotal() > 0) { for(int i=OrdersTotal()-1; i>=0; i--) { ulong ticket = OrderGetTicket(i); if(OrderSelect(ticket)) { if(history_ticket_present(OrderGetInteger(ORDER_MAGIC))) if(!trade.OrderDelete(ticket)) { Print(" Error in Deleting Pending Order (Empty Array) : "+IntegerToString(GetLastError())); } else Print("Order Close by empty array (Empty Array)"); } } } deleteAllArray(); } else { for(int i=0; i 0.0) closedPercentage = NormalizeDouble((sumOfClosed / totalLot) * 100.0, 1); } //Print(" Magic: ", cod[j].magic, " Ticket: ", order_array[i].ticket, " Master Lot: ", cod[j].masterLot, " Client Lot: ", order_array[i].lots); if(cod[j].magic==order_array[i].ticket) { if(closedPercentage < order_array[i].closedPercentageOfTrade) { percentageToClose = MathAbs(order_array[i].closedPercentageOfTrade - closedPercentage); trade_taken=1; partialCloseOrderPosition=j; } } } } if(order_array[i].ticket != -1) { if(trade_taken==1) { //current order need to close partially if(partialCloseOrderPosition!=-1) { bool isOrderClose=false; int roundDigit=0; double step=SymbolInfoDouble(cod[partialCloseOrderPosition].symbol,SYMBOL_VOLUME_STEP); while(step<1) { roundDigit++; step=step*10; } double lotClosePer = NormalizeDouble((totalLot * percentageToClose) / 100, roundDigit); if(percentageToClose > 0 && lotClosePer > SymbolInfoDouble(cod[partialCloseOrderPosition].symbol,SYMBOL_VOLUME_MIN)) { if(!trade.PositionClosePartial(cod[partialCloseOrderPosition].ticket, lotClosePer)) { Print("Partial order did not close:",cod[partialCloseOrderPosition].ticket, " Lot To Close is: ", lotClosePer); } else { isOrderClose=true; Print("Order Partial Close. currentLot Was =", currentLot, " Percentage to close = ", percentageToClose, " Lot I am Going To close = ", lotClosePer); } } } } else if(trade_taken == 2) { int diff1=((int)TimeCurrent()-(int)order_array[i].opentime)-gmtDifference;// ,diff2=TimeSeconds(TimeCurrent()-order_array[i].opentime); if(diff1 <= sec) { Print("Symbol: ",order_array[i].opentime," ",diff1," <= ",sec); trade.SetExpertMagicNumber(IntegerToString(order_array[i].ticket)); trade.SetDeviationInPoints(10); trade.SetTypeFilling(ORDER_FILLING_IOC); trade.LogLevel(LOG_LEVEL_ALL); trade.SetAsyncMode(false); if(order_array[i].ordertype == ORDER_TYPE_BUY) { double tempSlip=MathAbs(order_array[i].price- SymbolInfoDouble(order_array[i].symbol,SYMBOL_ASK))/SymbolInfoDouble(order_array[i].symbol,SYMBOL_POINT); if((MathAbs(order_array[i].price-SymbolInfoDouble(order_array[i].symbol,SYMBOL_ASK))/SymbolInfoDouble(order_array[i].symbol,SYMBOL_POINT)) <= slip*10) { double lotsize = getLotSize(order_array[i].symbol, order_array[i].accountBalance, order_array[i].lots, order_array[i].contractSize); double Stoploss=0.0; double ask=NormalizeDouble(SymbolInfoDouble(order_array[i].symbol,SYMBOL_ASK),(int)SymbolInfoInteger(order_array[i].symbol,SYMBOL_DIGITS)); if(trade.PositionOpen(order_array[i].symbol,ORDER_TYPE_BUY,lotsize,ask,order_array[i].stoploss,order_array[i].takeprofit,"")) { if(addOrderMaster(trade.ResultOrder(),order_array[i].ticket,order_array[i].lots, "Market")) { Print(" Buy Order Ticket:",trade.ResultOrder()," Stored!!!"); } else { //Print("Order Ticket is not stotred: ",trade.ResultOrder()," Error is: ", GetLastError()); } } else { Print("Copy Buy Order Send Error: "+IntegerToString(GetLastError())); } } } if(order_array[i].ordertype == ORDER_TYPE_SELL) { if((MathAbs(order_array[i].price-SymbolInfoDouble(order_array[i].symbol,SYMBOL_BID))/SymbolInfoDouble(order_array[i].symbol,SYMBOL_POINT)) <= slip*10) { double lotsize = getLotSize(order_array[i].symbol, order_array[i].accountBalance, order_array[i].lots, order_array[i].contractSize); double Stoploss=0.0; double bid=NormalizeDouble(SymbolInfoDouble(order_array[i].symbol,SYMBOL_BID),(int)SymbolInfoInteger(order_array[i].symbol,SYMBOL_DIGITS)); if(trade.PositionOpen(order_array[i].symbol,ORDER_TYPE_SELL,lotsize,bid,order_array[i].stoploss,order_array[i].takeprofit,"")) { if(addOrderMaster(trade.ResultOrder(),order_array[i].ticket,order_array[i].lots, "Market")) { Print(" Sell Order Ticket:",trade.ResultOrder()," Stored!!!"); } } else { Print("Copy Buy Order Send Error: "+IntegerToString(GetLastError())); } } } if(order_array[i].ordertype == ORDER_TYPE_BUY_STOP) { // Not Checking Slippage double lotsize = getLotSize(order_array[i].symbol, order_array[i].accountBalance, order_array[i].lots, order_array[i].contractSize); if(trade.BuyStop(lotsize, order_array[i].price, order_array[i].symbol, order_array[i].stoploss, order_array[i].takeprofit, 0, 0, "")) { if(addOrderMaster(trade.ResultOrder(),order_array[i].ticket,order_array[i].lots, "Pending")) { Print("Order Ticket Buy Stop:",trade.ResultOrder()," Stored!!!"); } } else { Print("Error in Order Buy Stop Order: "+Symbol()+" ",GetLastError()); } } if(order_array[i].ordertype == ORDER_TYPE_SELL_STOP) { double lotsize = getLotSize(order_array[i].symbol, order_array[i].accountBalance, order_array[i].lots, order_array[i].contractSize); if(trade.SellStop(lotsize, order_array[i].price, order_array[i].symbol, order_array[i].stoploss, order_array[i].takeprofit, 0, 0, "")) { if(addOrderMaster(trade.ResultOrder(),order_array[i].ticket,order_array[i].lots, "Pending")) { Print("Order Ticket Sell Stop:",trade.ResultOrder()," Stored!!!"); } } else { Print("Error in Order Sell Stop Order: "+Symbol()+" ",GetLastError()); } } if(order_array[i].ordertype == ORDER_TYPE_BUY_LIMIT) { double lotsize = getLotSize(order_array[i].symbol, order_array[i].accountBalance, order_array[i].lots, order_array[i].contractSize); if(trade.BuyLimit(lotsize, order_array[i].price, order_array[i].symbol, order_array[i].stoploss, order_array[i].takeprofit, 0, 0, "")) { if(addOrderMaster(trade.ResultOrder(),order_array[i].ticket,order_array[i].lots, "Pending")) { Print("Order Ticket Buy Limit:",trade.ResultOrder()," Stored!!!"); } } else { Print("Error in Order Buy Limit: "+Symbol()+" ",GetLastError()); } } if(order_array[i].ordertype == ORDER_TYPE_SELL_LIMIT) { double lotsize = getLotSize(order_array[i].symbol, order_array[i].accountBalance, order_array[i].lots, order_array[i].contractSize); if(trade.SellLimit(lotsize, order_array[i].price, order_array[i].symbol, order_array[i].stoploss, order_array[i].takeprofit, 0, 0, "")) { if(addOrderMaster(trade.ResultOrder(),order_array[i].ticket,order_array[i].lots, "Pending")) { Print("Order Ticket Sell Limit: ",trade.ResultOrder()," Stored!!! ", " Tp: ", order_array[i].takeprofit, " Sl: ", order_array[i].stoploss); } } else { Print("Error in Order Sell Limit: "+Symbol()+" ",GetLastError()); } } } } } } for(int i=0; i Symbol:",symbol," master Account balance:",masterAccountBalance," master lot:",masterLot," master Contract:",masterContractSize); if(lotoption == mul) { lotsize = NormalizeDouble(masterLot*mult,2); } else if(lotoption == Balance) { lotsize=((AccountInfoDouble(ACCOUNT_BALANCE)/masterAccountBalance)*masterLot)*Bmult; } else if(lotoption == slaveLotCal) { lotsize = masterLot * (maxDd / recoveryAmount); } Print("Before Lot Size: ",lotsize); if(contractChk) { int clientContractSize=getDoubleSymbolInfo(symbol,"contract"); Print("Client Contract size:",clientContractSize); if(masterContractSize!=0 && clientContractSize!=0) { lotsize=((masterContractSize*1.0)/clientContractSize)*lotsize; } } int roundDigit=0; double step=getDoubleSymbolInfo(symbol, "lotStep"); while(step<1) { roundDigit++; step=step*10; } Print("Round Digits:",roundDigit); lotsize = NormalizeDouble(lotsize,roundDigit); if(lotsizegetDoubleSymbolInfo(symbol,"maxLot")) lotsize=getDoubleSymbolInfo(symbol,"maxLot"); Print("Lot Size: ",lotsize); return lotsize; } //+------------------------------------------------------------------+ //| | //+------------------------------------------------------------------+ void adminHeartBeat() { string headers = "apikey:"+localApiKey+"\r\naccept: */* \r\nContent-Type: application/json\r\nUser-Agent: MetaTraderApi"; string url =localHB_req_link;// Request_link+(string)accountNumber; bool isPost; int timeout = 100000; string lastConnected=TimeToString(TimeCurrent()); StringReplace(lastConnected,".","-"); StringReplace(lastConnected," ","T"); string gmtTime=TimeToString(TimeGMT()); string jsonData="{\"sLogin\":\""+(string)accountNumber+"\",\"sServer\":\""+clientServer+"\",\"sVersion\":\"5\" ,\"sLastConnected\":\""+gmtTime+"\"}";//\",\"url\":"+"\""+url+"\""+headers+"}"; uchar data[]; StringToCharArray(jsonData, data, 0, StringLen(jsonData)); // Print("Making the heart beat request to the local host"); POST_function(url,headers,timeout,data,isPost); } //+------------------------------------------------------------------+ //| | //+------------------------------------------------------------------+ bool POST_function(string url, string headers, int timeout, uchar &data[], bool &IsPost) { ResetLastError(); // clear previous error static int lastErrorPrinted = 0; uchar result[]; // use uchar for WebRequest result string resultHeaders; int res = WebRequest("POST", url, headers, timeout, data, result, resultHeaders); if(res == 200 || res == 201) { Print("***Request success. HTTP response code POST: ", res); string result_string = CharArrayToString(result); Print("content POST: ", result_string); lastErrorPrinted = 0; // reset remembered error on success IsPost = true; return true; } else { int err = GetLastError(); // read the error once // only print when there's a real error and it's different from last time if(err != 0 && err != lastErrorPrinted) { Print("Get last error: ", err); Print("***Request failed. HTTP response code: ", res); string result_string = CharArrayToString(result); Print("content: ", result_string); lastErrorPrinted = err; // remember this error so we don't spam it } IsPost = false; return false; } } //+------------------------------------------------------------------+ //| | //+------------------------------------------------------------------+ void clearOrderArray() { //Resize to one ArrayResize(order_array,1); //Clear all data order_array[0].symbol = ""; order_array[0].opentime = 0; order_array[0].price = 0; order_array[0].ordertype = 0; order_array[0].lots = 0; order_array[0].stoploss = 0; order_array[0].takeprofit = 0; order_array[0].ticket = -1; order_array[0].magicNo = 0; order_array[0].accountBalance=0; order_array[0].contractSize=0; order_array[0].comments=""; order_array[0].closedPercentageOfTrade = 0; } //+------------------------------------------------------------------+ //| | //+------------------------------------------------------------------+ void mapHistory() { for(int i=0; i 999) { addOrderMaster(PositionGetInteger(POSITION_TICKET), PositionGetInteger(POSITION_MAGIC), PositionGetDouble(POSITION_VOLUME), "Market"); } } } for(int i=0; i 999) { addOrderMaster(OrderGetInteger(ORDER_TICKET), OrderGetInteger(ORDER_MAGIC), OrderGetDouble(ORDER_VOLUME_CURRENT), "Pending"); } } } } //+------------------------------------------------------------------+ //| | //+------------------------------------------------------------------+ bool addToMarketWatch(string symbol) { Print("Symbol:",symbol); bool result=SymbolSelect(symbol,true); if(result) { Print("Successfully added the symbol or already there:", symbol); return true; } else { Print("Error in adding symbol:",symbol); } return false; } //+------------------------------------------------------------------+ //| | //+------------------------------------------------------------------+ void read_history_file() { string file_name = "history_trades.csv"; if(!FileIsExist(file_name, FILE_COMMON)) { Print("File not found: ", file_name); return; } int h = FileOpen(file_name, FILE_SHARE_READ|FILE_CSV|FILE_COMMON|FILE_READ|FILE_ANSI|FILE_TXT|FILE_COMMON); if(h == INVALID_HANDLE) { Print("Error opening file: ", file_name, " Err:", GetLastError()); return; } datetime lastFileModified=(datetime)FileGetInteger(h,FILE_MODIFY_DATE); long fileSize=FileGetInteger(h,FILE_SIZE); if(lastModified1==lastFileModified && fileSize==lastFileSize1) { FileClose(h); return; } else { ulong fileTickets[]; ArrayResize(fileTickets, 0); while(!FileIsEnding(h)) { string line = FileReadString(h); // split by comma string parts[]; int count = StringSplit(line,',', parts); if(count >= 2) { // convert to integers ulong ticket = StringToInteger(parts[0]); ulong magic = StringToInteger(parts[1]); int newSize = ArraySize(fileTickets) + 1; ArrayResize(fileTickets, newSize); fileTickets[newSize - 1] = ticket; if(!history_ticket_present(ticket)) add_history_ticket(ticket, magic); } else { // Print("Skipped malformed line while reading ", file_name, " : ", line); } } FileClose(h); lastModified1=lastFileModified; lastFileSize1=fileSize; for(int i = 0; i < MaxOrders; i++) { ulong tk = historyTradeStore[i].ticket; if(tk == -1) continue; bool found = false; for(int j = 0; j < ArraySize(fileTickets); j++) { if(fileTickets[j] == tk) { found = true; break; } } if(!found) { Print("Removing ticket not found in file: ", tk, " index=", i); historyTradeStore[i].ticket = -1; historyTradeStore[i].magic = 0; } } } } //+------------------------------------------------------------------+ //| | //+------------------------------------------------------------------+ void add_history_ticket(ulong ticket, ulong magicIs) { for(int i = 0; i < MaxOrders; i++) { if(historyTradeStore[i].ticket == -1) { historyTradeStore[i].ticket = ticket; historyTradeStore[i].magic = magicIs; Print(" -------- add_history_ticket() Added ticket: ", ticket, " Magic: ", magicIs, " ---------------------------- "); return; } } Print("historyTradeStore full, cannot add ticket: ", ticket); } //+------------------------------------------------------------------+ //| | //+------------------------------------------------------------------+ bool history_ticket_present(ulong ticket) { for(int i = 0 ; i < MaxOrders ; i++) { if(historyTradeStore[i].ticket == ticket) return true; } return false; } //+------------------------------------------------------------------+ //+------------------------------------------------------------------+ //| | //+------------------------------------------------------------------+