Nessuna descrizione

localHedgingClientCopierMt5.mq5 71KB

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