Нет описания

localHedgingClientCopierMt5.mq5 66KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661
  1. //+------------------------------------------------------------------+
  2. //| localHedgingClientCopierMt5.mq5 |
  3. //| Copyright 2025, MetaQuotes Ltd. |
  4. //| https://www.mqldevelopment.com/ |
  5. //+------------------------------------------------------------------+
  6. #property copyright "Copyright 2025, MetaQuotes Ltd."
  7. #property link "https://www.mqldevelopment.com/"
  8. #property version "1.00"
  9. #define orderCount 2000
  10. #define count1 50
  11. #define testCounter 50
  12. #define MaxOrders 20000
  13. #define daysOfTradesToAdd 20
  14. #include <Trade\Trade.mqh>
  15. CTrade trade;
  16. //+------------------------------------------------------------------+
  17. //| Expert initialization function |
  18. //+------------------------------------------------------------------+
  19. struct historyTradesClientSide
  20. {
  21. ulong ticket;
  22. ulong magic;
  23. historyTradesClientSide()
  24. {
  25. ticket = -1;
  26. magic = 0;
  27. }
  28. };
  29. historyTradesClientSide historyTradeStore[MaxOrders];
  30. struct order
  31. {
  32. ulong ticket;
  33. double price;
  34. datetime opentime;
  35. string symbol;
  36. int ordertype;
  37. double lots;
  38. double stoploss;
  39. double takeprofit;
  40. double accountBalance;
  41. int contractSize;
  42. string comments;
  43. int magicNo;
  44. order()
  45. {
  46. ticket =-1;
  47. }
  48. };
  49. struct clientOrder
  50. {
  51. ulong ticket;
  52. double price;
  53. datetime opentime;
  54. string symbol;
  55. int ordertype;
  56. double lots;
  57. double stoploss;
  58. double takeprofit;
  59. ulong magic;
  60. string comments;
  61. double masterLot;
  62. clientOrder()
  63. {
  64. ticket=-1;
  65. price=-1;
  66. symbol=Symbol();
  67. ordertype=-1;
  68. lots=0;
  69. masterLot=0;
  70. stoploss=0;
  71. takeprofit=0;
  72. magic=0;
  73. comments="";
  74. }
  75. };
  76. clientOrder cod[orderCount];
  77. struct masterOrder
  78. {
  79. datetime opentime;
  80. string symbol;
  81. ulong ordertype;
  82. double price;
  83. double lots;
  84. double stoploss;
  85. double takeprofit;
  86. ulong ticket;
  87. int magic;
  88. double accountBalance;
  89. int contractSize;
  90. string comment;
  91. masterOrder()
  92. {
  93. ticket=-1;
  94. price=-1;
  95. symbol=Symbol();
  96. ordertype=-1;
  97. lots=0;
  98. stoploss=0;
  99. takeprofit=0;
  100. }
  101. };
  102. masterOrder mod1[orderCount];
  103. enum lot_option
  104. {
  105. fix, //Fixed Lot
  106. mul, //Multiplied Lot
  107. Balance, // Balance Base Multiplier
  108. slaveLotCal,
  109. };
  110. enum tradeCopy_type
  111. {
  112. buy,//Buy Only
  113. sell,//Sell Only
  114. buySell,//Buy and Sell
  115. };
  116. enum operation_code
  117. {
  118. Master, //Master
  119. Client, //Client
  120. };
  121. sinput string string_0 = "<><><><><><> General SETTINGS <><><><><><>"; //__
  122. input int slip = 5; // Master Order Variation in Pips
  123. input int sec = 10; // Master Order Expired After Seconds
  124. input tradeCopy_type tradeType = buySell; // Trades To Copy
  125. input lot_option lotoption = fix; // Lot Option
  126. input double mult = 1.0; // Multiplier (for Client)
  127. input double fixed = 0.1; // Fixed Lot (for Client)
  128. input double Bmult = 1; // Balance Multiplier (for Client)
  129. input double recoveryAmount = 3000; // Recovery Amount (for Client Lot)
  130. input double maxDd = 8000; // Max DrawDown (for Client Lot)
  131. input string suffix = ""; // Suffix
  132. input string symbolExclude = ""; // Symbol to Exclude
  133. input string prefix = ""; // Prefix
  134. // Heart Beat
  135. sinput string string_1 = "<><><><><><> HeartBeat Setting <><><><><><>"; //__
  136. input string clientServer = ""; // Master Server
  137. input string mappingSymbol = "GOLD,XAUUSD;bitcoin,BTCUSD"; // Mapping Pairs Inp,Out;Inp,Out
  138. input string localApiKey = "U2FsdGVkX18vBY4H1uzQiZwuh8B++8VBtCGJ3yGr2XPII0qCodmfuhjssKu5oug1J4e97bkwPtDQLi4py1OODQ=="; // Local API Key
  139. input string localHB_req_link = "http://localhost/api/slastConnected"; // Request Link For LastConnected
  140. //+------------------------------------------------------------------+
  141. //| |
  142. //+------------------------------------------------------------------+
  143. //Global Variable
  144. int gmtDifference = 0;
  145. int filehandle;
  146. // Heart Beat
  147. long lastFileSize=0;
  148. datetime lastModified=0;
  149. bool contractChk = true;//Contract Checking
  150. bool doReversal = true; // Reverse Trades
  151. bool fileLastEmpty=false;
  152. long accountNumber=AccountInfoInteger(ACCOUNT_LOGIN);
  153. int counter=0,testCounterVar=0;
  154. order order_array[];
  155. datetime lastModified1=0;
  156. long lastFileSize1=0;
  157. bool fileHandlerIssue=false;
  158. operation_code mode1=Client; //Working code
  159. int OnInit()
  160. {
  161. //---
  162. accountNumber=AccountInfoInteger(ACCOUNT_LOGIN);
  163. EventSetMillisecondTimer(20);
  164. if(!ObjectFind(0,"mode") || ObjectGetString(0,"mode",OBJPROP_TEXT,0)!=EnumToString(mode1)+" Account")
  165. {
  166. ObjectDelete(0,"mode");
  167. ObjectCreate(0,"mode",OBJ_LABEL,0,0,0);
  168. ObjectSetInteger(0,"mode",OBJPROP_XDISTANCE,10);
  169. ObjectSetInteger(0,"mode",OBJPROP_YDISTANCE,25);
  170. ObjectSetInteger(0,"mode",OBJPROP_CORNER,CORNER_RIGHT_UPPER);
  171. ObjectSetInteger(0,"mode",OBJPROP_ANCHOR,ANCHOR_RIGHT_UPPER);
  172. ObjectSetInteger(0,"mode",OBJPROP_COLOR,clrLightBlue);
  173. ObjectSetString(0,"mode",OBJPROP_TEXT,EnumToString(mode1)+" Account");
  174. ObjectSetInteger(0,"mode",OBJPROP_FONTSIZE,14);
  175. }
  176. gmtDifference = (int)TimeCurrent() - (int)TimeGMT();
  177. Print("GMT Difference(sec): ",gmtDifference);
  178. mapHistory();
  179. //---
  180. return(INIT_SUCCEEDED);
  181. }
  182. //+------------------------------------------------------------------+
  183. //| Expert deinitialization function |
  184. //+------------------------------------------------------------------+
  185. void OnDeinit(const int reason)
  186. {
  187. //---
  188. EventKillTimer();
  189. ObjectsDeleteAll(0,0,-1);
  190. }
  191. //+------------------------------------------------------------------+
  192. //| Expert tick function |
  193. //+------------------------------------------------------------------+
  194. void OnTick()
  195. {
  196. //---
  197. }
  198. //+------------------------------------------------------------------+
  199. void OnTimer()
  200. {
  201. gmtDifference = (int)TimeCurrent() - (int)TimeGMT();
  202. read_history_file();
  203. readData();
  204. writeDataClientCof();
  205. }
  206. //+------------------------------------------------------------------+
  207. //| |
  208. //+------------------------------------------------------------------+
  209. void writeDataClientCof()
  210. {
  211. int fileHandleClientCof;
  212. if(PositionsTotal()==0 && OrdersTotal()==0 && !fileLastEmpty && TerminalInfoInteger(TERMINAL_CONNECTED))
  213. {
  214. fileHandleClientCof = FileOpen("COF_client.csv", FILE_WRITE|FILE_CSV|FILE_COMMON);
  215. if(fileHandleClientCof != INVALID_HANDLE)
  216. {
  217. Print("Writing file to empty");
  218. FileWrite(fileHandleClientCof, "");
  219. FileClose(fileHandleClientCof);
  220. fileLastEmpty = true;
  221. emptyStruct();
  222. }
  223. else
  224. {
  225. Print(" Client Cof File handler issue:", GetLastError());
  226. }
  227. }
  228. else
  229. {
  230. bool updationReq = checkOrderUpdate();
  231. if(updationReq || fileHandlerIssue)
  232. {
  233. Print(" ------------------------------- Client Cof Start ------------------------------------------ ");
  234. fileHandleClientCof = FileOpen("COF_client.csv", FILE_WRITE|FILE_CSV|FILE_COMMON);
  235. if(fileHandleClientCof != INVALID_HANDLE)
  236. {
  237. fileHandlerIssue = false;
  238. for(int i = PositionsTotal()-1; i >= 0; i--)
  239. {
  240. ulong ticket = PositionGetTicket(i);
  241. if(PositionSelectByTicket(ticket))
  242. {
  243. //if(((useMinimumLot && (PositionGetDouble(POSITION_VOLUME) > minimumLot)) || !useMinimumLot) &&
  244. // ((useMaximumLot && (PositionGetDouble(POSITION_VOLUME) < maximumLot)) || !useMaximumLot))
  245. {
  246. string time = TimeToString(PositionGetInteger(POSITION_TIME)-gmtDifference, TIME_DATE|TIME_SECONDS);
  247. string symbol = PositionGetString(POSITION_SYMBOL);
  248. double digits = getDoubleSymbolInfo(symbol,"digits");
  249. if(suffix != "")
  250. symbol = StringSubstr(symbol, 0, StringFind(symbol, suffix, 0));
  251. if(prefix != "")
  252. StringReplace(symbol, prefix, "");
  253. long orderType = PositionGetInteger(POSITION_TYPE);
  254. double takeProfit = PositionGetDouble(POSITION_TP);
  255. double stopLoss = PositionGetDouble(POSITION_SL);
  256. if(doReversal)
  257. {
  258. if(orderType == POSITION_TYPE_BUY)
  259. orderType = POSITION_TYPE_SELL;
  260. else
  261. if(orderType == POSITION_TYPE_SELL)
  262. orderType = POSITION_TYPE_BUY;
  263. takeProfit = PositionGetDouble(POSITION_SL);
  264. stopLoss = PositionGetDouble(POSITION_TP);
  265. }
  266. string OrderToWrite =
  267. time + "," +
  268. symbol + "," +
  269. IntegerToString(orderType) + "," +
  270. DoubleToString(PositionGetDouble(POSITION_PRICE_OPEN),(int)digits) + "," +
  271. DoubleToString(PositionGetDouble(POSITION_VOLUME),2) + "," +
  272. DoubleToString(stopLoss,(int)digits) + "," +
  273. DoubleToString(takeProfit,(int)digits) + "," +
  274. IntegerToString(PositionGetInteger(POSITION_TICKET)) + "," +
  275. IntegerToString(PositionGetInteger(POSITION_MAGIC)) + "," +
  276. (string)AccountInfoDouble(ACCOUNT_BALANCE) + "," +
  277. (string)SymbolInfoDouble(PositionGetString(POSITION_SYMBOL), SYMBOL_TRADE_CONTRACT_SIZE) +
  278. PositionGetString(POSITION_COMMENT) + "\r\n";
  279. FileWrite(fileHandleClientCof, OrderToWrite);
  280. }
  281. }
  282. }
  283. for(int i = OrdersTotal()-1; i >= 0; i--)
  284. {
  285. ulong ticket = OrderGetTicket(i);
  286. if(OrderSelect(ticket))
  287. {
  288. //if(((useMinimumLot && (OrderGetDouble(ORDER_VOLUME_CURRENT) > minimumLot)) || !useMinimumLot) &&
  289. // ((useMaximumLot && (OrderGetDouble(ORDER_VOLUME_CURRENT) < maximumLot)) || !useMaximumLot))
  290. {
  291. string time = TimeToString(OrderGetInteger(ORDER_TIME_SETUP)-gmtDifference, TIME_DATE|TIME_SECONDS);
  292. string symbol = OrderGetString(ORDER_SYMBOL);
  293. double digits = getDoubleSymbolInfo(symbol,"digits");
  294. if(suffix != "")
  295. symbol = StringSubstr(symbol, 0, StringFind(symbol, suffix, 0));
  296. if(prefix != "")
  297. StringReplace(symbol, prefix, "");
  298. long orderType = OrderGetInteger(ORDER_TYPE);
  299. double takeProfit = OrderGetDouble(ORDER_TP);
  300. double stopLoss = OrderGetDouble(ORDER_SL);
  301. if(doReversal)
  302. {
  303. if(orderType == ORDER_TYPE_BUY_STOP)
  304. orderType = ORDER_TYPE_SELL_LIMIT;
  305. else
  306. if(orderType == ORDER_TYPE_SELL_STOP)
  307. orderType = ORDER_TYPE_BUY_LIMIT;
  308. else
  309. if(orderType == ORDER_TYPE_BUY_LIMIT)
  310. orderType = ORDER_TYPE_SELL_STOP;
  311. else
  312. if(orderType == ORDER_TYPE_SELL_LIMIT)
  313. orderType = ORDER_TYPE_BUY_STOP;
  314. takeProfit = OrderGetDouble(ORDER_SL);
  315. stopLoss = OrderGetDouble(ORDER_TP);
  316. }
  317. string OrderToWrite =
  318. time + "," +
  319. symbol + "," +
  320. IntegerToString(orderType) + "," +
  321. DoubleToString(OrderGetDouble(ORDER_PRICE_OPEN),(int)digits) + "," +
  322. DoubleToString(OrderGetDouble(ORDER_VOLUME_CURRENT),2) + "," +
  323. DoubleToString(stopLoss,(int)digits) + "," +
  324. DoubleToString(takeProfit,(int)digits) + "," +
  325. IntegerToString(OrderGetInteger(ORDER_TICKET)) + "," +
  326. IntegerToString(OrderGetInteger(ORDER_MAGIC)) + "," +
  327. (string)AccountInfoDouble(ACCOUNT_BALANCE) + "," +
  328. (string)SymbolInfoDouble(OrderGetString(ORDER_SYMBOL), SYMBOL_TRADE_CONTRACT_SIZE) +
  329. OrderGetString(ORDER_COMMENT) + "\r\n";
  330. Print("Client Cof Writing Pending Order Block.");
  331. FileWrite(fileHandleClientCof, OrderToWrite);
  332. }
  333. }
  334. }
  335. FileClose(fileHandleClientCof);
  336. fileLastEmpty = false;
  337. Print("Client Cof File Updated:", TimeCurrent());
  338. }
  339. else
  340. {
  341. Print("Client Cof File Handle Issue:", GetLastError());
  342. }
  343. Print(" ------------------------------- Client Cof End ------------------------------------------ ");
  344. }
  345. }
  346. }
  347. //+------------------------------------------------------------------+
  348. //| |
  349. //+------------------------------------------------------------------+
  350. bool checkOrderUpdate()
  351. {
  352. bool updationRequired=false,currCheck=false;
  353. for(int i = PositionsTotal()-1 ; i >= 0 ; i--)
  354. {
  355. ulong ticket = PositionGetTicket(i);
  356. if(PositionSelectByTicket(ticket))
  357. {
  358. int orderIndex=-1;
  359. bool alreadyAdded=isOrderThere(ticket, orderIndex);
  360. if(!alreadyAdded)
  361. {
  362. currCheck=false;
  363. currCheck=addOrderMaster(ticket, "Market");
  364. if(!updationRequired)
  365. updationRequired=currCheck;
  366. }
  367. else
  368. {
  369. if(orderIndex!=-1)
  370. {
  371. currCheck=false;
  372. currCheck=IsOrderChanged(PositionGetInteger(POSITION_TICKET),orderIndex, "Market");
  373. if(!updationRequired)
  374. {
  375. updationRequired=currCheck;
  376. }
  377. }
  378. }
  379. }
  380. }
  381. for(int i = OrdersTotal()-1 ; i >= 0 ; i--)
  382. {
  383. ulong ticket = OrderGetTicket(i);
  384. if(OrderSelect(ticket))
  385. {
  386. if(OrderGetInteger(ORDER_TYPE) != ORDER_TYPE_BUY && OrderGetInteger(ORDER_TYPE) != ORDER_TYPE_SELL && OrderGetInteger(ORDER_TYPE) != ORDER_TYPE_CLOSE_BY)
  387. {
  388. int orderIndex=-1;
  389. bool alreadyAdded=isOrderThere(ticket, orderIndex);
  390. if(!alreadyAdded)
  391. {
  392. Print("Inside pending Adding to master order: ",ticket," type: ",OrderGetInteger(ORDER_TYPE)," ",OrdersTotal()," ",ORDER_TYPE_CLOSE_BY);
  393. currCheck=false;
  394. currCheck=addOrderMaster(ticket, "Pending");
  395. if(!updationRequired)
  396. updationRequired=currCheck;
  397. }
  398. else
  399. {
  400. if(orderIndex!=-1)
  401. {
  402. currCheck=false;
  403. currCheck=IsOrderChanged(OrderGetInteger(ORDER_TICKET), orderIndex, "Pending");
  404. if(!updationRequired)
  405. {
  406. updationRequired=currCheck;
  407. }
  408. }
  409. }
  410. }
  411. }
  412. }
  413. for(int i=0; i<ArraySize(mod1); i++)
  414. {
  415. bool isPresent=false;
  416. if(mod1[i].ticket !=-1)
  417. {
  418. for(int j = PositionsTotal()-1; j>=0; j--)
  419. {
  420. ulong ticket = PositionGetTicket(j);
  421. if(PositionSelectByTicket(ticket))
  422. {
  423. if(ticket==mod1[i].ticket)
  424. {
  425. isPresent=true;
  426. break;
  427. }
  428. }
  429. }
  430. // Pending Order
  431. for(int j = OrdersTotal()-1; j>=0; j--)
  432. {
  433. ulong ticket = OrderGetTicket(j);
  434. if(OrderSelect(ticket))
  435. {
  436. if(ticket==mod1[i].ticket)
  437. {
  438. isPresent=true;
  439. break;
  440. }
  441. }
  442. }
  443. if(!isPresent)
  444. {
  445. Print("Ticket is closed so removed from struct: ",mod1[i].ticket);
  446. mod1[i].ticket=-1;
  447. mod1[i].price=-1;
  448. mod1[i].symbol="";
  449. mod1[i].ordertype=-1;
  450. mod1[i].lots=0;
  451. mod1[i].stoploss=0;
  452. mod1[i].takeprofit=0;
  453. currCheck=true;
  454. //currCheck=clearStructIndex(mod1[i].ticket);
  455. if(!updationRequired)
  456. updationRequired=currCheck;
  457. }
  458. }
  459. }
  460. return updationRequired;
  461. }
  462. //+------------------------------------------------------------------+
  463. //| |
  464. //+------------------------------------------------------------------+
  465. bool IsOrderChanged(ulong orderTicket, int index, string calledBy)
  466. {
  467. if(mod1[index].ticket!=-1)
  468. {
  469. if(calledBy == "Market")
  470. {
  471. if(PositionSelectByTicket(orderTicket))
  472. {
  473. //Digits
  474. double digits=getDoubleSymbolInfo(PositionGetString(POSITION_SYMBOL),"digits");
  475. double tp=NormalizeDouble(PositionGetDouble(POSITION_TP), (int)digits),
  476. sl=NormalizeDouble(PositionGetDouble(POSITION_SL),(int)digits),
  477. lot=NormalizeDouble(PositionGetDouble(POSITION_VOLUME),2);
  478. 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))
  479. {
  480. Print(" Inside IsOrderChanged() ",mod1[index].lots," lot: ",lot," calledBy: ",calledBy," mod1 ticket ",mod1[index].ticket," orderTicket: ",orderTicket);
  481. // Time
  482. datetime time = (datetime)(PositionGetInteger(POSITION_TIME) - gmtDifference);
  483. mod1[index].opentime=time;
  484. mod1[index].lots=lot;
  485. mod1[index].stoploss=sl;
  486. mod1[index].takeprofit=tp;
  487. mod1[index].comment=PositionGetString(POSITION_COMMENT);
  488. mod1[index].ordertype=PositionGetInteger(POSITION_TYPE);
  489. mod1[index].price=PositionGetDouble(POSITION_PRICE_OPEN);
  490. return true;
  491. }
  492. }
  493. }
  494. if(calledBy == "Pending")
  495. {
  496. if(OrderSelect(orderTicket))
  497. {
  498. double digits=getDoubleSymbolInfo(OrderGetString(ORDER_SYMBOL),"digits");
  499. double tp=NormalizeDouble(OrderGetDouble(ORDER_TP), (int)digits),
  500. sl=NormalizeDouble(OrderGetDouble(ORDER_SL),(int)digits),
  501. lot=NormalizeDouble(OrderGetDouble(ORDER_VOLUME_CURRENT),2);
  502. 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))
  503. {
  504. //time
  505. datetime time = (datetime)(OrderGetDouble(ORDER_PRICE_OPEN) - gmtDifference);
  506. mod1[index].opentime=time;
  507. mod1[index].lots=lot;
  508. mod1[index].stoploss=sl;
  509. mod1[index].takeprofit=tp;
  510. mod1[index].comment=OrderGetString(ORDER_COMMENT);
  511. mod1[index].ordertype=OrderGetInteger(ORDER_TYPE);
  512. mod1[index].price=OrderGetDouble(ORDER_PRICE_OPEN);
  513. return true;
  514. }
  515. }
  516. }
  517. }
  518. return false;
  519. }
  520. //+------------------------------------------------------------------+
  521. //| |
  522. //+------------------------------------------------------------------+
  523. bool addOrderMaster(ulong ticket, string calledBy)
  524. {
  525. for(int i=0; i<ArraySize(mod1); i++)
  526. {
  527. if(mod1[i].ticket==-1)
  528. {
  529. if(calledBy == "Market")
  530. {
  531. //ulong ticket = PositionGetTicket(orderTicket);
  532. if(PositionSelectByTicket(ticket))
  533. {
  534. //Symbol Updation
  535. string symbol=PositionGetString(POSITION_SYMBOL);
  536. if(suffix!="")
  537. symbol = StringSubstr(symbol,0,StringFind(PositionGetString(POSITION_SYMBOL),suffix,0));
  538. if(prefix!="")
  539. StringReplace(symbol,prefix,"");
  540. //Digits
  541. double digits=getDoubleSymbolInfo(PositionGetString(POSITION_SYMBOL),"digits");
  542. //time
  543. datetime time = (datetime)(PositionGetInteger(POSITION_TIME)-gmtDifference);
  544. mod1[i].opentime=time;
  545. mod1[i].symbol=symbol;
  546. mod1[i].ordertype=PositionGetInteger(POSITION_TYPE);
  547. mod1[i].price=NormalizeDouble(PositionGetDouble(POSITION_PRICE_OPEN),(int)digits);
  548. mod1[i].lots=NormalizeDouble(PositionGetDouble(POSITION_VOLUME),2);
  549. mod1[i].stoploss=NormalizeDouble(PositionGetDouble(POSITION_SL),(int)digits);
  550. mod1[i].takeprofit=NormalizeDouble(PositionGetDouble(POSITION_TP),(int)digits);
  551. mod1[i].ticket=PositionGetInteger(POSITION_TICKET);
  552. mod1[i].magic=(int)PositionGetInteger(POSITION_MAGIC);
  553. mod1[i].comment=PositionGetString(POSITION_COMMENT);
  554. Print("Ticket:",PositionGetInteger(POSITION_TICKET)," stored in index:",i);
  555. return true;
  556. }
  557. }
  558. if(calledBy == "Pending")
  559. {
  560. if(OrderSelect(ticket))
  561. {
  562. string symbol = OrderGetString(ORDER_SYMBOL);
  563. if(suffix!="")
  564. symbol = StringSubstr(symbol,0,StringFind(OrderGetString(ORDER_SYMBOL),suffix,0));
  565. if(prefix!="")
  566. StringReplace(symbol,prefix,"");
  567. //Digits
  568. double digits=getDoubleSymbolInfo(OrderGetString(ORDER_SYMBOL),"digits");
  569. //time
  570. datetime time = (datetime)(OrderGetInteger(ORDER_TIME_SETUP) - gmtDifference);
  571. mod1[i].opentime=time;
  572. mod1[i].symbol=symbol;
  573. mod1[i].ordertype=OrderGetInteger(ORDER_TYPE);
  574. mod1[i].price=NormalizeDouble(OrderGetDouble(ORDER_PRICE_OPEN),(int)digits);
  575. mod1[i].lots=NormalizeDouble(OrderGetDouble(ORDER_VOLUME_CURRENT),2);
  576. mod1[i].stoploss=NormalizeDouble(OrderGetDouble(ORDER_SL),(int)digits);
  577. mod1[i].takeprofit=NormalizeDouble(OrderGetDouble(ORDER_TP),(int)digits);
  578. mod1[i].ticket=OrderGetInteger(ORDER_TICKET);
  579. mod1[i].magic=(int)OrderGetInteger(ORDER_MAGIC);
  580. mod1[i].comment=OrderGetString(ORDER_COMMENT);
  581. Print("Ticket: ",OrderGetInteger(ORDER_TICKET)," stored in index by pending order:",i);
  582. return true;
  583. }
  584. }
  585. }
  586. }
  587. return false;
  588. }
  589. //+------------------------------------------------------------------+
  590. //| |
  591. //+------------------------------------------------------------------+
  592. void readData()
  593. {
  594. if(EnumToString(mode1)=="Client")
  595. {
  596. filehandle=FileOpen("COF.csv",FILE_SHARE_READ|FILE_CSV|FILE_COMMON|FILE_READ|FILE_ANSI|FILE_TXT|FILE_COMMON);
  597. if(filehandle!=INVALID_HANDLE)
  598. {
  599. datetime lastFileModified=(datetime)FileGetInteger(filehandle,FILE_MODIFY_DATE);
  600. long fileSize=FileGetInteger(filehandle,FILE_SIZE);
  601. int a= 0;
  602. if(lastModified==lastFileModified && fileSize==lastFileSize) // lastModified==lastFileModified && fileSize==lastFileSize
  603. {
  604. FileClose(filehandle);
  605. if(counter>=count1 && TerminalInfoInteger(TERMINAL_CONNECTED))
  606. {
  607. if(testCounterVar==testCounter)
  608. {
  609. testCounterVar=0;
  610. }
  611. adminHeartBeat();
  612. counter=0;
  613. }
  614. counter++;
  615. testCounterVar++;
  616. }
  617. else
  618. {
  619. clearOrderArray();
  620. while(!FileIsEnding(filehandle))
  621. {
  622. string OrderToRead = FileReadString(filehandle);
  623. string Order_specs [];
  624. StringSplit(OrderToRead,StringGetCharacter(",",0),Order_specs);
  625. Print("Array Size: ", ArraySize(Order_specs));
  626. if(ArraySize(Order_specs) == 11 || ArraySize(Order_specs) == 12)
  627. {
  628. string symbol = getSymbol(Order_specs[1]);//prefix+Order_specs[1]+suffix;
  629. int orderType=StringToInteger(Order_specs[2]);
  630. if(StringFind(symbol,symbolExclude,0) < 0 &&
  631. (((orderType==POSITION_TYPE_BUY||orderType==ORDER_TYPE_BUY_STOP ||orderType==ORDER_TYPE_SELL_STOP)&& (tradeType==0||tradeType==2)) ||
  632. ((orderType==POSITION_TYPE_SELL||orderType==ORDER_TYPE_BUY_LIMIT ||orderType==ORDER_TYPE_SELL_LIMIT)&& (tradeType==1||tradeType==2)))
  633. )
  634. {
  635. order_array[ArraySize(order_array)-1].symbol = symbol;
  636. order_array[ArraySize(order_array)-1].opentime = StringToTime(Order_specs[0]);
  637. order_array[ArraySize(order_array)-1].price = StringToDouble(Order_specs[3]);
  638. order_array[ArraySize(order_array)-1].ordertype = StringToInteger(Order_specs[2]);
  639. order_array[ArraySize(order_array)-1].lots = StringToDouble(Order_specs[4]);
  640. order_array[ArraySize(order_array)-1].stoploss = StringToDouble(Order_specs[5]);
  641. order_array[ArraySize(order_array)-1].takeprofit = StringToDouble(Order_specs[6]);
  642. order_array[ArraySize(order_array)-1].ticket = StringToInteger(Order_specs[7]);
  643. //Saving master order ticket to order magic number
  644. order_array[ArraySize(order_array)-1].magicNo = StringToInteger(Order_specs[7]);
  645. order_array[ArraySize(order_array)-1].accountBalance=StringToDouble(Order_specs[9]);
  646. order_array[ArraySize(order_array)-1].contractSize=StringToInteger(Order_specs[10]);
  647. if(ArraySize(Order_specs) == 12)
  648. order_array[ArraySize(order_array)-1].comments=Order_specs[11];
  649. else
  650. order_array[ArraySize(order_array)-1].comments="";
  651. if(ArraySize(Order_specs) == 12)
  652. {
  653. StringReplace(Order_specs[11],"from #","");
  654. StringReplace(Order_specs[11]," ","");
  655. Print(" Order_specs[11] ",Order_specs[11]," order_array[ArraySize(order_array)-1].ticket ",order_array[ArraySize(order_array)-1].ticket);
  656. for(int l=0; l<orderCount; l++)
  657. {
  658. if(cod[l].magic == int(Order_specs[11]))
  659. {
  660. cod[l].magic = order_array[ArraySize(order_array)-1].ticket;
  661. }
  662. }
  663. }
  664. Print(" Symbol: ",order_array[ArraySize(order_array)-1].symbol,"Open Price: ",order_array[ArraySize(order_array)-1].price," Lot: ", order_array[ArraySize(order_array)-1].lots,"OPen time: ",order_array[ArraySize(order_array)-1].opentime);
  665. ArrayResize(order_array,ArraySize(order_array)+1);
  666. addToMarketWatch(symbol);
  667. }
  668. }
  669. }
  670. lastModified=lastFileModified;
  671. lastFileSize=fileSize;
  672. FileClose(filehandle);
  673. }
  674. int arraySize=ArraySize(order_array);
  675. if(ArraySize(order_array) == 1) //
  676. {
  677. if(PositionsTotal() > 0)
  678. {
  679. for(int i=PositionsTotal()-1; i>=0; i--)
  680. {
  681. ulong ticket = PositionGetTicket(i);
  682. if(PositionSelectByTicket(ticket))
  683. {
  684. if(history_ticket_present(PositionGetInteger(POSITION_MAGIC)))
  685. if(!trade.PositionClose(ticket))
  686. {
  687. Print(" Order Close Error on No Master Trade: "+IntegerToString(GetLastError()));
  688. }
  689. else
  690. Print(" ------------- Order Close by empty array ------------------ ");
  691. }
  692. }
  693. }
  694. if(OrdersTotal() > 0)
  695. {
  696. for(int i=OrdersTotal()-1; i>=0; i--)
  697. {
  698. ulong ticket = OrderGetTicket(i);
  699. if(OrderSelect(ticket))
  700. {
  701. if(history_ticket_present(OrderGetInteger(ORDER_MAGIC)))
  702. if(!trade.OrderDelete(ticket))
  703. {
  704. Print(" Error in Deleting Pending Order (Empty Array) : "+IntegerToString(GetLastError()));
  705. }
  706. else
  707. Print("Order Close by empty array (Empty Array)");
  708. }
  709. }
  710. }
  711. deleteAllArray();
  712. }
  713. else
  714. {
  715. for(int i=0; i<ArraySize(order_array); i++)
  716. {
  717. int trade_taken = 2;
  718. int partialCloseOrderPosition=-1;
  719. for(int j=0; j<orderCount; j++)
  720. {
  721. //if(OrderSelect(cod[j].ticket,SELECT_BY_POS))
  722. if(cod[j].ticket!=-1)
  723. {
  724. if(cod[j].magic==order_array[i].ticket)
  725. {
  726. trade_taken = 0;
  727. }
  728. if(cod[j].magic==order_array[i].ticket)
  729. {
  730. if(cod[j].masterLot != order_array[i].lots)
  731. {
  732. Print(" Cod Lot Size: ", cod[j].masterLot, " Order Array Lot: ", order_array[i].lots);
  733. Print("Order is partial close:",cod[j].magic);
  734. trade_taken=1;
  735. partialCloseOrderPosition=j;
  736. }
  737. }
  738. }
  739. }
  740. if(order_array[i].ticket != -1)
  741. {
  742. if(trade_taken==1)
  743. {
  744. //current order need to close partially
  745. if(partialCloseOrderPosition!=-1)
  746. {
  747. bool isOrderClose=false;
  748. if(cod[partialCloseOrderPosition].masterLot <= 0)
  749. {
  750. Print("Error: Invalid masterLot for partial close");
  751. continue;
  752. }
  753. //if(OrderSelect(partialCloseOrderPosition,SELECT_BY_TICKET))
  754. {
  755. Print("Master lot: ",order_array[i].lots," last save lot: ",cod[partialCloseOrderPosition].masterLot);
  756. double lotClosePer = NormalizeDouble(100 - (order_array[i].lots/cod[partialCloseOrderPosition].masterLot*100),2);
  757. Print("Order in master is closed in percentage: ",lotClosePer," last client lot: ",cod[partialCloseOrderPosition].lots);
  758. double closeLot=NormalizeDouble(lotClosePer/100 *cod[partialCloseOrderPosition].lots,2);
  759. Print("Close lot in client: ",closeLot);
  760. if(!trade.PositionClosePartial(cod[partialCloseOrderPosition].ticket,closeLot))
  761. {
  762. Print("Partial order did not close:",cod[partialCloseOrderPosition].ticket);
  763. }
  764. else
  765. {
  766. isOrderClose=true;
  767. cod[partialCloseOrderPosition].lots=cod[partialCloseOrderPosition].lots-closeLot; //PositionGetDouble(POSITION_VOLUME);
  768. cod[partialCloseOrderPosition].masterLot = order_array[i].lots;
  769. }
  770. }
  771. }
  772. }
  773. else
  774. if(trade_taken == 2)
  775. {
  776. int diff1=((int)TimeCurrent()-(int)order_array[i].opentime)-gmtDifference;// ,diff2=TimeSeconds(TimeCurrent()-order_array[i].opentime);
  777. if(diff1 <= sec)
  778. {
  779. Print("Symbol: ",order_array[i].opentime," ",diff1," <= ",sec);
  780. trade.SetExpertMagicNumber(IntegerToString(order_array[i].ticket));
  781. trade.SetDeviationInPoints(10);
  782. trade.SetTypeFilling(ORDER_FILLING_IOC);
  783. trade.LogLevel(LOG_LEVEL_ALL);
  784. trade.SetAsyncMode(false);
  785. if(order_array[i].ordertype == ORDER_TYPE_BUY)
  786. {
  787. double tempSlip=MathAbs(order_array[i].price- SymbolInfoDouble(order_array[i].symbol,SYMBOL_ASK))/SymbolInfoDouble(order_array[i].symbol,SYMBOL_POINT);
  788. if((MathAbs(order_array[i].price-SymbolInfoDouble(order_array[i].symbol,SYMBOL_ASK))/SymbolInfoDouble(order_array[i].symbol,SYMBOL_POINT)) <= slip*10)
  789. {
  790. double lotsize = getLotSize(order_array[i].symbol, order_array[i].accountBalance, order_array[i].lots, order_array[i].contractSize);
  791. double Stoploss=0.0;
  792. double ask=NormalizeDouble(SymbolInfoDouble(order_array[i].symbol,SYMBOL_ASK),(int)SymbolInfoInteger(order_array[i].symbol,SYMBOL_DIGITS));
  793. if(trade.PositionOpen(order_array[i].symbol,ORDER_TYPE_BUY,lotsize,ask,order_array[i].stoploss,order_array[i].takeprofit,""))
  794. {
  795. if(addOrderMaster(trade.ResultOrder(),order_array[i].ticket,order_array[i].lots, "Market"))
  796. {
  797. Print("Order Ticket:",trade.ResultOrder()," Stored!!!");
  798. }
  799. else
  800. {
  801. //Print("Order Ticket is not stotred: ",trade.ResultOrder()," Error is: ", GetLastError());
  802. }
  803. }
  804. else
  805. {
  806. Print("Copy Buy Order Send Error: "+IntegerToString(GetLastError()));
  807. }
  808. }
  809. }
  810. if(order_array[i].ordertype == ORDER_TYPE_SELL)
  811. {
  812. if((MathAbs(order_array[i].price-SymbolInfoDouble(order_array[i].symbol,SYMBOL_BID))/SymbolInfoDouble(order_array[i].symbol,SYMBOL_POINT)) <= slip*10)
  813. {
  814. double lotsize = getLotSize(order_array[i].symbol, order_array[i].accountBalance, order_array[i].lots, order_array[i].contractSize);
  815. double Stoploss=0.0;
  816. double bid=NormalizeDouble(SymbolInfoDouble(order_array[i].symbol,SYMBOL_BID),(int)SymbolInfoInteger(order_array[i].symbol,SYMBOL_DIGITS));
  817. if(trade.PositionOpen(order_array[i].symbol,ORDER_TYPE_SELL,lotsize,bid,order_array[i].stoploss,order_array[i].takeprofit,""))
  818. {
  819. if(addOrderMaster(trade.ResultOrder(),order_array[i].ticket,order_array[i].lots, "Market"))
  820. {
  821. Print("Order Ticket:",trade.ResultOrder()," Stored!!!");
  822. }
  823. }
  824. else
  825. {
  826. Print("Copy Buy Order Send Error: "+IntegerToString(GetLastError()));
  827. }
  828. }
  829. }
  830. if(order_array[i].ordertype == ORDER_TYPE_BUY_STOP)
  831. {
  832. // Not Checking Slippage
  833. double lotsize = getLotSize(order_array[i].symbol, order_array[i].accountBalance, order_array[i].lots, order_array[i].contractSize);
  834. if(trade.BuyStop(lotsize, order_array[i].price, order_array[i].symbol, order_array[i].stoploss, order_array[i].takeprofit, 0, 0, ""))
  835. {
  836. if(addOrderMaster(trade.ResultOrder(),order_array[i].ticket,order_array[i].lots, "Pending"))
  837. {
  838. Print("Order Ticket Buy Stop:",trade.ResultOrder()," Stored!!!");
  839. }
  840. }
  841. else
  842. {
  843. Print("Error in Order Buy Stop Order: "+Symbol()+" ",GetLastError());
  844. }
  845. }
  846. if(order_array[i].ordertype == ORDER_TYPE_SELL_STOP)
  847. {
  848. double lotsize = getLotSize(order_array[i].symbol, order_array[i].accountBalance, order_array[i].lots, order_array[i].contractSize);
  849. if(trade.SellStop(lotsize, order_array[i].price, order_array[i].symbol, order_array[i].stoploss, order_array[i].takeprofit, 0, 0, ""))
  850. {
  851. if(addOrderMaster(trade.ResultOrder(),order_array[i].ticket,order_array[i].lots, "Pending"))
  852. {
  853. Print("Order Ticket Sell Stop:",trade.ResultOrder()," Stored!!!");
  854. }
  855. }
  856. else
  857. {
  858. Print("Error in Order Sell Stop Order: "+Symbol()+" ",GetLastError());
  859. }
  860. }
  861. if(order_array[i].ordertype == ORDER_TYPE_BUY_LIMIT)
  862. {
  863. double lotsize = getLotSize(order_array[i].symbol, order_array[i].accountBalance, order_array[i].lots, order_array[i].contractSize);
  864. if(trade.BuyLimit(lotsize, order_array[i].price, order_array[i].symbol, order_array[i].stoploss, order_array[i].takeprofit, 0, 0, ""))
  865. {
  866. if(addOrderMaster(trade.ResultOrder(),order_array[i].ticket,order_array[i].lots, "Pending"))
  867. {
  868. Print("Order Ticket Buy Limit:",trade.ResultOrder()," Stored!!!");
  869. }
  870. }
  871. else
  872. {
  873. Print("Error in Order Buy Limit: "+Symbol()+" ",GetLastError());
  874. }
  875. }
  876. if(order_array[i].ordertype == ORDER_TYPE_SELL_LIMIT)
  877. {
  878. double lotsize = getLotSize(order_array[i].symbol, order_array[i].accountBalance, order_array[i].lots, order_array[i].contractSize);
  879. if(trade.SellLimit(lotsize, order_array[i].price, order_array[i].symbol, order_array[i].stoploss, order_array[i].takeprofit, 0, 0, ""))
  880. {
  881. if(addOrderMaster(trade.ResultOrder(),order_array[i].ticket,order_array[i].lots, "Pending"))
  882. {
  883. Print("Order Ticket Sell Limit: ",trade.ResultOrder()," Stored!!! ", " Tp: ", order_array[i].takeprofit, " Sl: ", order_array[i].stoploss);
  884. }
  885. }
  886. else
  887. {
  888. Print("Error in Order Sell Limit: "+Symbol()+" ",GetLastError());
  889. }
  890. }
  891. }
  892. }
  893. }
  894. }
  895. for(int i=0; i<orderCount; i++)
  896. {
  897. bool trade_close = true;
  898. if(PositionSelectByTicket(cod[i].ticket))
  899. {
  900. for(int j=0; j<ArraySize(order_array); j++)
  901. {
  902. if(cod[i].magic == (order_array[j].ticket))
  903. {
  904. trade_close = false;
  905. if(PositionGetDouble(POSITION_TP)!=order_array[j].takeprofit || PositionGetDouble(POSITION_SL)!=order_array[j].stoploss)
  906. {
  907. if(trade.PositionModify(PositionGetInteger(POSITION_TICKET),order_array[j].stoploss,order_array[j].takeprofit))
  908. {
  909. Print("Order modified ticket:",PositionGetInteger(POSITION_TICKET));
  910. cod[i].takeprofit=order_array[j].takeprofit;
  911. cod[i].stoploss=order_array[j].stoploss;
  912. }
  913. else
  914. {
  915. Print("Order not modified error:",GetLastError());
  916. }
  917. }
  918. }
  919. }
  920. if(trade_close == true)
  921. {
  922. if(PositionGetInteger(POSITION_TYPE)== ORDER_TYPE_BUY)
  923. {
  924. if(!trade.PositionClose(PositionGetInteger(POSITION_TICKET)))
  925. {
  926. Print("Buy Order Close Error on Master Trade Close: "+IntegerToString(GetLastError()));
  927. }
  928. else
  929. {
  930. Print("Order close by no master copy of trade");
  931. cod[i].ticket=-1;
  932. }
  933. }
  934. if(PositionGetInteger(POSITION_TYPE)== ORDER_TYPE_SELL)
  935. {
  936. if(!trade.PositionClose(PositionGetInteger(POSITION_TICKET)))
  937. {
  938. Print("Sell Order Close Error on Master Trade Close: "+IntegerToString(GetLastError()));
  939. }
  940. else
  941. {
  942. Print("Order close by no master copy of trade");
  943. cod[i].ticket=-1;
  944. }
  945. }
  946. }
  947. }
  948. if(OrderSelect(cod[i].ticket))
  949. {
  950. for(int j=0; j<ArraySize(order_array); j++)
  951. {
  952. if(cod[i].magic == (order_array[j].ticket))
  953. {
  954. trade_close = false;
  955. if(OrderGetDouble(ORDER_TP)!=order_array[j].takeprofit || OrderGetDouble(ORDER_SL)!=order_array[j].stoploss || OrderGetDouble(ORDER_PRICE_OPEN)!=order_array[j].price)
  956. {
  957. if(trade.OrderModify(OrderGetInteger(ORDER_TICKET),order_array[j].price,order_array[j].stoploss,order_array[j].takeprofit, 0, 0, 0))
  958. {
  959. Print("Pending Order modified ticket:",PositionGetInteger(POSITION_TICKET));
  960. cod[i].takeprofit=order_array[j].takeprofit;
  961. cod[i].stoploss=order_array[j].stoploss;
  962. cod[i].price = order_array[j].price;
  963. }
  964. else
  965. {
  966. Print("Order not modified error:",GetLastError());
  967. }
  968. }
  969. }
  970. }
  971. if(trade_close == true)
  972. {
  973. if(OrderGetInteger(ORDER_TYPE)== ORDER_TYPE_BUY_STOP || OrderGetInteger(ORDER_TYPE)== ORDER_TYPE_SELL_STOP || OrderGetInteger(ORDER_TYPE)== ORDER_TYPE_BUY_LIMIT || OrderGetInteger(ORDER_TYPE)== ORDER_TYPE_SELL_LIMIT)
  974. {
  975. if(!trade.OrderDelete(OrderGetInteger(ORDER_TICKET)))
  976. {
  977. Print("Error in Deleting Pending Order: "+IntegerToString(GetLastError()));
  978. }
  979. else
  980. {
  981. Print("Pending Order Deleted. Ticket is: ", cod[i].ticket);
  982. cod[i].ticket=-1;
  983. }
  984. }
  985. }
  986. }
  987. }
  988. }
  989. }
  990. }
  991. }
  992. //+------------------------------------------------------------------+
  993. //| |
  994. //+------------------------------------------------------------------+
  995. void print()
  996. {
  997. for(int i=0; i<orderCount; i++)
  998. {
  999. if(cod[i].ticket!=-1)
  1000. {
  1001. Print("Ticket : ",cod[i].ticket," OPen price: ",cod[i].price, " Type: ",cod[i].ordertype);
  1002. }
  1003. }
  1004. }
  1005. //+------------------------------------------------------------------+
  1006. //| |
  1007. //+------------------------------------------------------------------+
  1008. bool isOrderThere(ulong ticket,int &index)
  1009. {
  1010. for(int i=0; i<ArraySize(mod1); i++)
  1011. {
  1012. if(ticket != -1)
  1013. {
  1014. if(mod1[i].ticket==ticket)
  1015. {
  1016. index=i;
  1017. return true;
  1018. }
  1019. }
  1020. }
  1021. return false;
  1022. }
  1023. //+------------------------------------------------------------------+
  1024. //| |
  1025. //+------------------------------------------------------------------+
  1026. void emptyStruct()
  1027. {
  1028. for(int i = 0 ; i < orderCount ; i++)
  1029. {
  1030. if(mod1[i].ticket != -1)
  1031. {
  1032. mod1[i].ticket=-1;
  1033. mod1[i].price=-1;
  1034. mod1[i].symbol="";
  1035. mod1[i].ordertype=-1;
  1036. mod1[i].lots=0;
  1037. mod1[i].stoploss=0;
  1038. mod1[i].takeprofit=0;
  1039. }
  1040. }
  1041. }
  1042. //+------------------------------------------------------------------+
  1043. //| |
  1044. //+------------------------------------------------------------------+
  1045. void deleteAllArray()
  1046. {
  1047. for(int i=0; i<orderCount; i++)
  1048. {
  1049. if(cod[i].ticket!=-1)
  1050. {
  1051. cod[i].ticket=-1;
  1052. }
  1053. }
  1054. }
  1055. //+------------------------------------------------------------------+
  1056. //| |
  1057. //+------------------------------------------------------------------+
  1058. bool addOrderMaster(ulong ticket,ulong magic,double lot, string calledBy)
  1059. {
  1060. Print("in addOrderMaster: ", ticket);
  1061. bool notFoundPosition=false;//Use to look in to the order loop in case order isn't converted
  1062. if(OrderSelect(ticket))
  1063. {
  1064. Print("Inside order selection:");
  1065. Print("Order State:",(ENUM_ORDER_STATE)OrderGetInteger(ORDER_STATE));
  1066. Print("Order Time done:",(datetime)OrderGetInteger(ORDER_TIME_DONE));
  1067. Print("Order Type:",(ENUM_ORDER_TYPE)OrderGetInteger(ORDER_TYPE));
  1068. }
  1069. else
  1070. if(HistoryOrderSelect(ticket))
  1071. {
  1072. Print("Inside history order selection:");
  1073. Print("Order State:",(ENUM_ORDER_STATE)HistoryOrderGetInteger(ticket,ORDER_STATE));
  1074. Print("Order Time done:",(datetime)HistoryOrderGetInteger(ticket,ORDER_TIME_DONE));
  1075. Print("Order Type:",(ENUM_ORDER_TYPE)HistoryOrderGetInteger(ticket,ORDER_TYPE));
  1076. }
  1077. else
  1078. {
  1079. PrintFormat("OrderSelect(%I64u) failed. Error %d", ticket, GetLastError());
  1080. }
  1081. for(int i=0; i<orderCount; i++)
  1082. {
  1083. if(cod[i].ticket==-1)
  1084. {
  1085. if(calledBy == "Market")
  1086. {
  1087. if(PositionSelectByTicket(ticket))
  1088. {
  1089. cod[i].ticket=PositionGetInteger(POSITION_TICKET);
  1090. cod[i].price=PositionGetDouble(POSITION_PRICE_OPEN);
  1091. cod[i].symbol=PositionGetString(POSITION_SYMBOL);
  1092. cod[i].ordertype=PositionGetInteger(POSITION_TYPE);
  1093. cod[i].lots=PositionGetDouble(POSITION_VOLUME);
  1094. cod[i].stoploss=PositionGetDouble(POSITION_SL);
  1095. cod[i].takeprofit=PositionGetDouble(POSITION_TP);
  1096. cod[i].magic=PositionGetInteger(POSITION_MAGIC);
  1097. cod[i].comments=PositionGetString(POSITION_COMMENT);
  1098. cod[i].masterLot = lot;
  1099. Print("Ticket stored in master:",PositionGetInteger(POSITION_TICKET)," stored in index:",i);
  1100. return true;
  1101. }
  1102. else
  1103. {
  1104. Print("Ticket:",ticket," not found in the position list");
  1105. notFoundPosition=true;
  1106. }
  1107. }
  1108. if(calledBy == "Pending" || notFoundPosition)
  1109. {
  1110. if(OrderSelect(ticket))
  1111. {
  1112. cod[i].ticket=OrderGetInteger(ORDER_TICKET);
  1113. cod[i].price=OrderGetDouble(ORDER_PRICE_OPEN);
  1114. cod[i].symbol=OrderGetString(ORDER_SYMBOL);
  1115. cod[i].ordertype=OrderGetInteger(ORDER_TYPE);
  1116. cod[i].lots=OrderGetDouble(ORDER_VOLUME_CURRENT);
  1117. cod[i].stoploss=OrderGetDouble(ORDER_SL);
  1118. cod[i].takeprofit=OrderGetDouble(ORDER_TP);
  1119. cod[i].magic=OrderGetInteger(ORDER_MAGIC);
  1120. cod[i].comments=OrderGetString(ORDER_COMMENT);
  1121. cod[i].masterLot = lot;
  1122. Print("Pending Order Ticket in master:",OrderGetInteger(ORDER_TICKET)," stored in index:",i);
  1123. return true;
  1124. }
  1125. else
  1126. {
  1127. Print("Ticket:",ticket," not found in the order list");
  1128. }
  1129. }
  1130. }
  1131. }
  1132. return false;
  1133. }
  1134. //+------------------------------------------------------------------+
  1135. //+------------------------------------------------------------------+
  1136. //| |
  1137. //+------------------------------------------------------------------+
  1138. double getDoubleSymbolInfo(string symbol,string info)
  1139. {
  1140. long digits=8;
  1141. //Symbol without the suffix and prefix
  1142. string updatedSymbol=symbol;
  1143. if(suffix!="")
  1144. updatedSymbol = StringSubstr(updatedSymbol,0,StringFind(updatedSymbol,suffix,0));
  1145. if(prefix!="")
  1146. StringReplace(updatedSymbol,prefix,"");
  1147. //Digits calculation could be used in other calculations
  1148. digits = SymbolInfoInteger(symbol,SYMBOL_DIGITS);
  1149. if(digits==0)
  1150. {
  1151. digits=SymbolInfoInteger(updatedSymbol,SYMBOL_DIGITS);
  1152. if(digits==0)
  1153. digits=8;
  1154. }
  1155. if(info=="digits")
  1156. {
  1157. return (double)digits;
  1158. }
  1159. else
  1160. if(info=="point" || info=="points")
  1161. {
  1162. double points=SymbolInfoDouble(symbol, SYMBOL_POINT);
  1163. if(points==0)
  1164. {
  1165. points=SymbolInfoDouble(updatedSymbol,SYMBOL_POINT);
  1166. if(points==0)
  1167. points=0.00001;
  1168. }
  1169. return points;
  1170. }
  1171. else
  1172. if(info=="ask")
  1173. {
  1174. double ask = SymbolInfoDouble(symbol, SYMBOL_ASK);
  1175. if(ask==0)
  1176. {
  1177. ask=SymbolInfoDouble(updatedSymbol,SYMBOL_ASK);
  1178. if(ask==0)
  1179. ask=0.00001;
  1180. }
  1181. return NormalizeDouble(ask,(int)digits);
  1182. }
  1183. else
  1184. if(info=="bid")
  1185. {
  1186. double bid=SymbolInfoDouble(symbol, SYMBOL_BID);
  1187. if(bid==0)
  1188. {
  1189. bid=SymbolInfoDouble(updatedSymbol,SYMBOL_BID);
  1190. if(bid==0)
  1191. bid=0.00001;
  1192. }
  1193. return NormalizeDouble(bid,(int)digits);
  1194. }
  1195. else
  1196. if(info=="contract"||info=="contractSize")
  1197. {
  1198. double contract=SymbolInfoDouble(symbol,SYMBOL_TRADE_CONTRACT_SIZE);
  1199. if(contract==0)
  1200. {
  1201. contract=SymbolInfoDouble(updatedSymbol,SYMBOL_TRADE_CONTRACT_SIZE);
  1202. }
  1203. return contract;
  1204. }
  1205. else
  1206. if(info=="lotStep")
  1207. {
  1208. double step=SymbolInfoDouble(symbol, SYMBOL_VOLUME_STEP);
  1209. if(step==0)
  1210. {
  1211. step=SymbolInfoDouble(updatedSymbol,SYMBOL_VOLUME_STEP);
  1212. }
  1213. return step;
  1214. }
  1215. else
  1216. if(info=="minLot")
  1217. {
  1218. double minLot=SymbolInfoDouble(symbol, SYMBOL_VOLUME_MIN);
  1219. if(minLot==0)
  1220. {
  1221. minLot = SymbolInfoDouble(updatedSymbol, SYMBOL_VOLUME_MIN);
  1222. }
  1223. return minLot;
  1224. }
  1225. else
  1226. if(info=="maxLot")
  1227. {
  1228. double maxLot=SymbolInfoDouble(symbol,SYMBOL_VOLUME_MAX);
  1229. if(maxLot==0)
  1230. {
  1231. maxLot=SymbolInfoDouble(updatedSymbol,SYMBOL_VOLUME_MAX);
  1232. }
  1233. return maxLot;
  1234. }
  1235. return 0;
  1236. }
  1237. //+------------------------------------------------------------------+
  1238. //| |
  1239. //+------------------------------------------------------------------+
  1240. string getSymbol(string symbol)
  1241. {
  1242. if(mappingSymbol!="")
  1243. {
  1244. string symbollist[];
  1245. StringSplit(mappingSymbol,';',symbollist);
  1246. for(int i=0; i<ArraySize(symbollist); i++)
  1247. {
  1248. string symbolPairs[];
  1249. StringSplit(symbollist[i],',',symbolPairs);
  1250. if(ArraySize(symbolPairs)==2)
  1251. {
  1252. if(symbol==symbolPairs[0])
  1253. return symbolPairs[1];
  1254. }
  1255. }
  1256. }
  1257. else
  1258. {
  1259. return prefix+symbol+suffix;
  1260. }
  1261. return prefix+symbol+suffix;
  1262. }
  1263. //+------------------------------------------------------------------+
  1264. //| |
  1265. //+------------------------------------------------------------------+
  1266. double getLotSize(string symbol,double masterAccountBalance,double masterLot,int masterContractSize)
  1267. {
  1268. double lotsize = fixed;
  1269. Print("------> Symbol:",symbol," master Account balance:",masterAccountBalance," master lot:",masterLot," master Contract:",masterContractSize);
  1270. if(lotoption == mul)
  1271. {
  1272. lotsize = NormalizeDouble(masterLot*mult,2);
  1273. }
  1274. else
  1275. if(lotoption == Balance)
  1276. {
  1277. lotsize=((AccountInfoDouble(ACCOUNT_BALANCE)/masterAccountBalance)*masterLot)*Bmult;
  1278. }
  1279. else
  1280. if(lotoption == slaveLotCal)
  1281. {
  1282. lotsize = masterLot * (maxDd / recoveryAmount);
  1283. }
  1284. Print("Before Lot Size: ",lotsize);
  1285. if(contractChk)
  1286. {
  1287. int clientContractSize=getDoubleSymbolInfo(symbol,"contract");
  1288. Print("Client Contract size:",clientContractSize);
  1289. if(masterContractSize!=0 && clientContractSize!=0)
  1290. {
  1291. lotsize=((masterContractSize*1.0)/clientContractSize)*lotsize;
  1292. }
  1293. }
  1294. int roundDigit=0;
  1295. double step=getDoubleSymbolInfo(symbol, "lotStep");
  1296. while(step<1)
  1297. {
  1298. roundDigit++;
  1299. step=step*10;
  1300. }
  1301. Print("Round Digits:",roundDigit);
  1302. lotsize = NormalizeDouble(lotsize,roundDigit);
  1303. if(lotsize<getDoubleSymbolInfo(symbol,"minLot"))
  1304. lotsize=getDoubleSymbolInfo(symbol,"minLot");
  1305. else
  1306. if(lotsize>getDoubleSymbolInfo(symbol,"maxLot"))
  1307. lotsize=getDoubleSymbolInfo(symbol,"maxLot");
  1308. Print("Lot Size: ",lotsize);
  1309. return lotsize;
  1310. }
  1311. //+------------------------------------------------------------------+
  1312. //| |
  1313. //+------------------------------------------------------------------+
  1314. void adminHeartBeat()
  1315. {
  1316. string headers = "apikey:"+localApiKey+"\r\naccept: */* \r\nContent-Type: application/json\r\nUser-Agent: MetaTraderApi";
  1317. string url =localHB_req_link;// Request_link+(string)accountNumber;
  1318. bool isPost;
  1319. int timeout = 100000;
  1320. string lastConnected=TimeToString(TimeCurrent());
  1321. StringReplace(lastConnected,".","-");
  1322. StringReplace(lastConnected," ","T");
  1323. string gmtTime=TimeToString(TimeGMT());
  1324. string jsonData="{\"sLogin\":\""+(string)accountNumber+"\",\"sServer\":\""+clientServer+"\",\"sVersion\":\"5\" ,\"sLastConnected\":\""+gmtTime+"\"}";//\",\"url\":"+"\""+url+"\""+headers+"}";
  1325. uchar data[];
  1326. StringToCharArray(jsonData, data, 0, StringLen(jsonData));
  1327. // Print("Making the heart beat request to the local host");
  1328. POST_function(url,headers,timeout,data,isPost);
  1329. }
  1330. //+------------------------------------------------------------------+
  1331. //| |
  1332. //+------------------------------------------------------------------+
  1333. bool POST_function(string url, string headers, int timeout, uchar &data[], bool &IsPost)
  1334. {
  1335. ResetLastError(); // clear previous error
  1336. static int lastErrorPrinted = 0;
  1337. uchar result[]; // use uchar for WebRequest result
  1338. string resultHeaders;
  1339. int res = WebRequest("POST", url, headers, timeout, data, result, resultHeaders);
  1340. if(res == 200 || res == 201)
  1341. {
  1342. Print("***Request success. HTTP response code POST: ", res);
  1343. string result_string = CharArrayToString(result);
  1344. Print("content POST: ", result_string);
  1345. lastErrorPrinted = 0; // reset remembered error on success
  1346. IsPost = true;
  1347. return true;
  1348. }
  1349. else
  1350. {
  1351. int err = GetLastError(); // read the error once
  1352. // only print when there's a real error and it's different from last time
  1353. if(err != 0 && err != lastErrorPrinted)
  1354. {
  1355. Print("Get last error: ", err);
  1356. Print("***Request failed. HTTP response code: ", res);
  1357. string result_string = CharArrayToString(result);
  1358. Print("content: ", result_string);
  1359. lastErrorPrinted = err; // remember this error so we don't spam it
  1360. }
  1361. IsPost = false;
  1362. return false;
  1363. }
  1364. }
  1365. //+------------------------------------------------------------------+
  1366. //| |
  1367. //+------------------------------------------------------------------+
  1368. void clearOrderArray()
  1369. {
  1370. //Resize to one
  1371. ArrayResize(order_array,1);
  1372. //Clear all data
  1373. order_array[0].symbol = "";
  1374. order_array[0].opentime = 0;
  1375. order_array[0].price = 0;
  1376. order_array[0].ordertype = 0;
  1377. order_array[0].lots = 0;
  1378. order_array[0].stoploss = 0;
  1379. order_array[0].takeprofit = 0;
  1380. order_array[0].ticket = -1;
  1381. order_array[0].magicNo = 0;
  1382. order_array[0].accountBalance=0;
  1383. order_array[0].contractSize=0;
  1384. order_array[0].comments="";
  1385. }
  1386. //+------------------------------------------------------------------+
  1387. //| |
  1388. //+------------------------------------------------------------------+
  1389. void mapHistory()
  1390. {
  1391. for(int i=0; i<PositionsTotal(); i++)
  1392. {
  1393. ulong ticket = PositionGetTicket(i);
  1394. if(PositionSelectByTicket(ticket))
  1395. {
  1396. if(PositionGetInteger(POSITION_MAGIC) > 999)
  1397. {
  1398. addOrderMaster(PositionGetInteger(POSITION_TICKET), PositionGetInteger(POSITION_MAGIC), PositionGetDouble(POSITION_VOLUME), "Market");
  1399. }
  1400. }
  1401. }
  1402. for(int i=0; i<OrdersTotal(); i++)
  1403. {
  1404. ulong ticket = OrderGetTicket(i);
  1405. if(OrderSelect(ticket))
  1406. {
  1407. if(OrderGetInteger(ORDER_MAGIC) > 999)
  1408. {
  1409. addOrderMaster(OrderGetInteger(ORDER_TICKET), OrderGetInteger(ORDER_MAGIC), OrderGetDouble(ORDER_VOLUME_CURRENT), "Pending");
  1410. }
  1411. }
  1412. }
  1413. }
  1414. //+------------------------------------------------------------------+
  1415. //| |
  1416. //+------------------------------------------------------------------+
  1417. bool addToMarketWatch(string symbol)
  1418. {
  1419. Print("Symbol:",symbol);
  1420. bool result=SymbolSelect(symbol,true);
  1421. if(result)
  1422. {
  1423. Print("Successfully added the symbol or already there:", symbol);
  1424. return true;
  1425. }
  1426. else
  1427. {
  1428. Print("Error in adding symbol:",symbol);
  1429. }
  1430. return false;
  1431. }
  1432. //+------------------------------------------------------------------+
  1433. //| |
  1434. //+------------------------------------------------------------------+
  1435. void read_history_file()
  1436. {
  1437. string file_name = "history_trades.csv";
  1438. if(!FileIsExist(file_name, FILE_COMMON))
  1439. {
  1440. Print("File not found: ", file_name);
  1441. return;
  1442. }
  1443. int h = FileOpen(file_name, FILE_SHARE_READ|FILE_CSV|FILE_COMMON|FILE_READ|FILE_ANSI|FILE_TXT|FILE_COMMON);
  1444. if(h == INVALID_HANDLE)
  1445. {
  1446. Print("Error opening file: ", file_name, " Err:", GetLastError());
  1447. return;
  1448. }
  1449. datetime lastFileModified=(datetime)FileGetInteger(h,FILE_MODIFY_DATE);
  1450. long fileSize=FileGetInteger(h,FILE_SIZE);
  1451. if(lastModified1==lastFileModified && fileSize==lastFileSize1)
  1452. {
  1453. FileClose(h);
  1454. return;
  1455. }
  1456. else
  1457. {
  1458. ulong fileTickets[];
  1459. ArrayResize(fileTickets, 0);
  1460. while(!FileIsEnding(h))
  1461. {
  1462. string line = FileReadString(h);
  1463. // split by comma
  1464. string parts[];
  1465. int count = StringSplit(line,',', parts);
  1466. if(count >= 2)
  1467. {
  1468. // convert to integers
  1469. ulong ticket = StringToInteger(parts[0]);
  1470. ulong magic = StringToInteger(parts[1]);
  1471. int newSize = ArraySize(fileTickets) + 1;
  1472. ArrayResize(fileTickets, newSize);
  1473. fileTickets[newSize - 1] = ticket;
  1474. if(!history_ticket_present(ticket))
  1475. add_history_ticket(ticket, magic);
  1476. }
  1477. else
  1478. {
  1479. // Print("Skipped malformed line while reading ", file_name, " : ", line);
  1480. }
  1481. }
  1482. FileClose(h);
  1483. lastModified1=lastFileModified;
  1484. lastFileSize1=fileSize;
  1485. for(int i = 0; i < MaxOrders; i++)
  1486. {
  1487. ulong tk = historyTradeStore[i].ticket;
  1488. if(tk == -1)
  1489. continue;
  1490. bool found = false;
  1491. for(int j = 0; j < ArraySize(fileTickets); j++)
  1492. {
  1493. if(fileTickets[j] == tk)
  1494. {
  1495. found = true;
  1496. break;
  1497. }
  1498. }
  1499. if(!found)
  1500. {
  1501. Print("Removing ticket not found in file: ", tk, " index=", i);
  1502. historyTradeStore[i].ticket = -1;
  1503. historyTradeStore[i].magic = 0;
  1504. }
  1505. }
  1506. }
  1507. }
  1508. //+------------------------------------------------------------------+
  1509. //| |
  1510. //+------------------------------------------------------------------+
  1511. void add_history_ticket(ulong ticket, ulong magicIs)
  1512. {
  1513. for(int i = 0; i < MaxOrders; i++)
  1514. {
  1515. if(historyTradeStore[i].ticket == -1)
  1516. {
  1517. historyTradeStore[i].ticket = ticket;
  1518. historyTradeStore[i].magic = magicIs;
  1519. Print(" -------- add_history_ticket() Added ticket: ", ticket, " Magic: ", magicIs, " ---------------------------- ");
  1520. return;
  1521. }
  1522. }
  1523. Print("historyTradeStore full, cannot add ticket: ", ticket);
  1524. }
  1525. //+------------------------------------------------------------------+
  1526. //| |
  1527. //+------------------------------------------------------------------+
  1528. bool history_ticket_present(ulong ticket)
  1529. {
  1530. for(int i = 0 ; i < MaxOrders ; i++)
  1531. {
  1532. if(historyTradeStore[i].ticket == ticket)
  1533. return true;
  1534. }
  1535. return false;
  1536. }
  1537. //+------------------------------------------------------------------+
  1538. //+------------------------------------------------------------------+
  1539. //| |
  1540. //+------------------------------------------------------------------+