Brak opisu

localHedgingClientCopierMt5.mq5 72KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753
  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. int symbolContractSize=(int)getDoubleSymbolInfo(symbol,"contract");
  252. ulong tempTicket = PositionGetInteger(POSITION_TICKET);
  253. if(suffix != "")
  254. symbol = StringSubstr(symbol, 0, StringFind(symbol, suffix, 0));
  255. if(prefix != "")
  256. StringReplace(symbol, prefix, "");
  257. long orderType = PositionGetInteger(POSITION_TYPE);
  258. double takeProfit = PositionGetDouble(POSITION_TP), stopLoss = PositionGetDouble(POSITION_SL);
  259. if(doReversal)
  260. {
  261. if(orderType == POSITION_TYPE_BUY)
  262. orderType = POSITION_TYPE_SELL;
  263. else
  264. if(orderType == POSITION_TYPE_SELL)
  265. orderType = POSITION_TYPE_BUY;
  266. takeProfit = PositionGetDouble(POSITION_SL);
  267. stopLoss = PositionGetDouble(POSITION_TP);
  268. }
  269. double sumOfClosed = dealOutLotsCheck(0, PositionGetInteger(POSITION_TICKET));
  270. double currentLot = PositionGetDouble(POSITION_VOLUME);
  271. double totalLot = sumOfClosed + currentLot;
  272. double closedPercentage = 0.0;
  273. if(totalLot > 0.0)
  274. closedPercentage = (sumOfClosed / totalLot) * 100.0;
  275. Print(" Client Closed % = ", closedPercentage);
  276. string OrderToWrite = time+","+symbol+","+IntegerToString(orderType)+","+DoubleToString(PositionGetDouble(POSITION_PRICE_OPEN), (int)digits)+","+DoubleToString(PositionGetDouble(POSITION_VOLUME),2)+","+DoubleToString(stopLoss,(int) digits)+","+DoubleToString(takeProfit, (int) digits)+","+IntegerToString(PositionGetInteger(POSITION_TICKET))+","+IntegerToString(PositionGetInteger(POSITION_MAGIC))+","+(string)AccountInfoDouble(ACCOUNT_BALANCE)+","+DoubleToString(closedPercentage)+","+(string)SymbolInfoDouble(PositionGetString(POSITION_SYMBOL),SYMBOL_TRADE_CONTRACT_SIZE)+PositionGetString(POSITION_COMMENT)+"\r\n";
  277. FileWrite(filehandle,OrderToWrite);
  278. }
  279. }
  280. }
  281. for(int i = OrdersTotal()-1; i >= 0; i--)
  282. {
  283. ulong ticket = OrderGetTicket(i);
  284. if(OrderSelect(ticket))
  285. {
  286. //if(((useMinimumLot && (OrderGetDouble(ORDER_VOLUME_CURRENT) > minimumLot)) || !useMinimumLot) &&
  287. // ((useMaximumLot && (OrderGetDouble(ORDER_VOLUME_CURRENT) < maximumLot)) || !useMaximumLot))
  288. {
  289. string time = TimeToString(OrderGetInteger(ORDER_TIME_SETUP)-gmtDifference, TIME_DATE|TIME_SECONDS);
  290. string symbol = OrderGetString(ORDER_SYMBOL);
  291. double digits = getDoubleSymbolInfo(symbol,"digits");
  292. if(suffix != "")
  293. symbol = StringSubstr(symbol, 0, StringFind(symbol, suffix, 0));
  294. if(prefix != "")
  295. StringReplace(symbol, prefix, "");
  296. long orderType = OrderGetInteger(ORDER_TYPE);
  297. double takeProfit = OrderGetDouble(ORDER_TP);
  298. double stopLoss = OrderGetDouble(ORDER_SL);
  299. if(doReversal)
  300. {
  301. if(orderType == ORDER_TYPE_BUY_STOP)
  302. orderType = ORDER_TYPE_SELL_LIMIT;
  303. else
  304. if(orderType == ORDER_TYPE_SELL_STOP)
  305. orderType = ORDER_TYPE_BUY_LIMIT;
  306. else
  307. if(orderType == ORDER_TYPE_BUY_LIMIT)
  308. orderType = ORDER_TYPE_SELL_STOP;
  309. else
  310. if(orderType == ORDER_TYPE_SELL_LIMIT)
  311. orderType = ORDER_TYPE_BUY_STOP;
  312. takeProfit = OrderGetDouble(ORDER_SL);
  313. stopLoss = OrderGetDouble(ORDER_TP);
  314. }
  315. double closedPercentage = 0;
  316. string OrderToWrite =
  317. time + "," +
  318. symbol + "," +
  319. IntegerToString(orderType) + "," +
  320. DoubleToString(OrderGetDouble(ORDER_PRICE_OPEN),(int)digits) + "," +
  321. DoubleToString(OrderGetDouble(ORDER_VOLUME_CURRENT),2) + "," +
  322. DoubleToString(stopLoss,(int)digits) + "," +
  323. DoubleToString(takeProfit,(int)digits) + "," +
  324. IntegerToString(OrderGetInteger(ORDER_TICKET)) + "," +
  325. IntegerToString(OrderGetInteger(ORDER_MAGIC)) + "," +
  326. (string)AccountInfoDouble(ACCOUNT_BALANCE) + "," +
  327. DoubleToString(closedPercentage) +","+
  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) == 12 || ArraySize(Order_specs) == 13)
  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].closedPercentageOfTrade = StringToDouble(Order_specs[10]);
  647. order_array[ArraySize(order_array)-1].contractSize=StringToInteger(Order_specs[11]);
  648. if(ArraySize(Order_specs) == 13)
  649. order_array[ArraySize(order_array)-1].comments=Order_specs[12];
  650. else
  651. order_array[ArraySize(order_array)-1].comments="";
  652. if(ArraySize(Order_specs) == 13)
  653. {
  654. StringReplace(Order_specs[12],"from #","");
  655. StringReplace(Order_specs[12]," ","");
  656. Print(" Order_specs[12] ",Order_specs[12]," order_array[ArraySize(order_array)-1].ticket ",order_array[ArraySize(order_array)-1].ticket);
  657. for(int l=0; l<orderCount; l++)
  658. {
  659. if(cod[l].magic == int(Order_specs[12]))
  660. {
  661. cod[l].magic = order_array[ArraySize(order_array)-1].ticket;
  662. }
  663. }
  664. }
  665. Print(" Symbol: ", order_array[ArraySize(order_array)-1].symbol,
  666. " Open Price: ", order_array[ArraySize(order_array)-1].price,
  667. " Lot: ", order_array[ArraySize(order_array)-1].lots,
  668. " Open time: ", order_array[ArraySize(order_array)-1].opentime,
  669. " Closed %: ", order_array[ArraySize(order_array)-1].closedPercentageOfTrade);
  670. ArrayResize(order_array,ArraySize(order_array)+1);
  671. addToMarketWatch(symbol);
  672. }
  673. }
  674. }
  675. lastModified=lastFileModified;
  676. lastFileSize=fileSize;
  677. FileClose(filehandle);
  678. }
  679. int arraySize=ArraySize(order_array);
  680. if(ArraySize(order_array) == 1) //
  681. {
  682. if(PositionsTotal() > 0)
  683. {
  684. for(int i=PositionsTotal()-1; i>=0; i--)
  685. {
  686. ulong ticket = PositionGetTicket(i);
  687. if(PositionSelectByTicket(ticket))
  688. {
  689. if(history_ticket_present(PositionGetInteger(POSITION_MAGIC)))
  690. if(!trade.PositionClose(ticket))
  691. {
  692. Print(" Order Close Error on No Master Trade: "+IntegerToString(GetLastError()));
  693. }
  694. else
  695. Print(" ------------- Order Close by empty array ------------------ ");
  696. }
  697. }
  698. }
  699. if(OrdersTotal() > 0)
  700. {
  701. for(int i=OrdersTotal()-1; i>=0; i--)
  702. {
  703. ulong ticket = OrderGetTicket(i);
  704. if(OrderSelect(ticket))
  705. {
  706. if(history_ticket_present(OrderGetInteger(ORDER_MAGIC)))
  707. if(!trade.OrderDelete(ticket))
  708. {
  709. Print(" Error in Deleting Pending Order (Empty Array) : "+IntegerToString(GetLastError()));
  710. }
  711. else
  712. Print("Order Close by empty array (Empty Array)");
  713. }
  714. }
  715. }
  716. deleteAllArray();
  717. }
  718. else
  719. {
  720. for(int i=0; i<ArraySize(order_array); i++)
  721. {
  722. //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);
  723. int trade_taken = 2;
  724. int partialCloseOrderPosition=-1;
  725. double percentageToClose = 0;
  726. double closedPercentage = 0.0;
  727. double currentLot = 0.0;
  728. double totalLot = 0;
  729. for(int j=0; j<orderCount; j++)
  730. {
  731. //if(OrderSelect(cod[j].ticket,SELECT_BY_POS))
  732. if(cod[j].ticket!=-1)
  733. {
  734. if(cod[j].magic==order_array[i].ticket)
  735. {
  736. trade_taken = 0;
  737. }
  738. if(PositionSelectByTicket(cod[j].ticket))
  739. {
  740. double sumOfClosed = dealOutLotsCheck(0, PositionGetInteger(POSITION_TICKET));
  741. currentLot = PositionGetDouble(POSITION_VOLUME);
  742. totalLot = sumOfClosed + currentLot;
  743. if(totalLot > 0.0)
  744. closedPercentage = (sumOfClosed / totalLot) * 100.0;
  745. }
  746. //Print(" Magic: ", cod[j].magic, " Ticket: ", order_array[i].ticket, " Master Lot: ", cod[j].masterLot, " Client Lot: ", order_array[i].lots);
  747. if(cod[j].magic==order_array[i].ticket)
  748. {
  749. if(closedPercentage < order_array[i].closedPercentageOfTrade)
  750. {
  751. percentageToClose = MathAbs(order_array[i].closedPercentageOfTrade - closedPercentage);
  752. //Print(" Cod Lot Size: ", cod[j].masterLot, " Order Array Lot: ", order_array[i].lots);
  753. Print("Closed % = ", closedPercentage, " Master Ticket Percentage: ", order_array[i].closedPercentageOfTrade);
  754. Print("Order is partial close:",cod[j].magic, " Percentage To Be Closed: ", percentageToClose);
  755. trade_taken=1;
  756. partialCloseOrderPosition=j;
  757. }
  758. }
  759. }
  760. }
  761. if(order_array[i].ticket != -1)
  762. {
  763. if(trade_taken==1)
  764. {
  765. //current order need to close partially
  766. if(partialCloseOrderPosition!=-1)
  767. {
  768. bool isOrderClose=false;
  769. double lotClosePer = NormalizeDouble((totalLot * percentageToClose) / 100,2);
  770. if(percentageToClose > 0)
  771. {
  772. if(!trade.PositionClosePartial(cod[partialCloseOrderPosition].ticket, lotClosePer))
  773. {
  774. // ExpertRemove();
  775. Print("Partial order did not close:",cod[partialCloseOrderPosition].ticket, " Lot To Close is: ", lotClosePer);
  776. }
  777. else
  778. {
  779. isOrderClose=true;
  780. //cod[partialCloseOrderPosition].lots=cod[partialCloseOrderPosition].lots-closeLot; //PositionGetDouble(POSITION_VOLUME);
  781. //cod[partialCloseOrderPosition].masterLot = order_array[i].lots;
  782. Print("Order Partial Close. currentLot Was =", currentLot,
  783. " Percentage to close = ", percentageToClose,
  784. " Lot I am Going To close = ", lotClosePer);
  785. }
  786. }
  787. }
  788. }
  789. else
  790. if(trade_taken == 2)
  791. {
  792. int diff1=((int)TimeCurrent()-(int)order_array[i].opentime)-gmtDifference;// ,diff2=TimeSeconds(TimeCurrent()-order_array[i].opentime);
  793. if(diff1 <= sec)
  794. {
  795. Print("Symbol: ",order_array[i].opentime," ",diff1," <= ",sec);
  796. trade.SetExpertMagicNumber(IntegerToString(order_array[i].ticket));
  797. trade.SetDeviationInPoints(10);
  798. trade.SetTypeFilling(ORDER_FILLING_IOC);
  799. trade.LogLevel(LOG_LEVEL_ALL);
  800. trade.SetAsyncMode(false);
  801. if(order_array[i].ordertype == ORDER_TYPE_BUY)
  802. {
  803. double tempSlip=MathAbs(order_array[i].price- SymbolInfoDouble(order_array[i].symbol,SYMBOL_ASK))/SymbolInfoDouble(order_array[i].symbol,SYMBOL_POINT);
  804. if((MathAbs(order_array[i].price-SymbolInfoDouble(order_array[i].symbol,SYMBOL_ASK))/SymbolInfoDouble(order_array[i].symbol,SYMBOL_POINT)) <= slip*10)
  805. {
  806. double lotsize = getLotSize(order_array[i].symbol, order_array[i].accountBalance, order_array[i].lots, order_array[i].contractSize);
  807. double Stoploss=0.0;
  808. double ask=NormalizeDouble(SymbolInfoDouble(order_array[i].symbol,SYMBOL_ASK),(int)SymbolInfoInteger(order_array[i].symbol,SYMBOL_DIGITS));
  809. if(trade.PositionOpen(order_array[i].symbol,ORDER_TYPE_BUY,lotsize,ask,order_array[i].stoploss,order_array[i].takeprofit,""))
  810. {
  811. if(addOrderMaster(trade.ResultOrder(),order_array[i].ticket,order_array[i].lots, "Market"))
  812. {
  813. Print(" Buy Order Ticket:",trade.ResultOrder()," Stored!!!");
  814. }
  815. else
  816. {
  817. //Print("Order Ticket is not stotred: ",trade.ResultOrder()," Error is: ", GetLastError());
  818. }
  819. }
  820. else
  821. {
  822. Print("Copy Buy Order Send Error: "+IntegerToString(GetLastError()));
  823. }
  824. }
  825. }
  826. if(order_array[i].ordertype == ORDER_TYPE_SELL)
  827. {
  828. if((MathAbs(order_array[i].price-SymbolInfoDouble(order_array[i].symbol,SYMBOL_BID))/SymbolInfoDouble(order_array[i].symbol,SYMBOL_POINT)) <= slip*10)
  829. {
  830. double lotsize = getLotSize(order_array[i].symbol, order_array[i].accountBalance, order_array[i].lots, order_array[i].contractSize);
  831. double Stoploss=0.0;
  832. double bid=NormalizeDouble(SymbolInfoDouble(order_array[i].symbol,SYMBOL_BID),(int)SymbolInfoInteger(order_array[i].symbol,SYMBOL_DIGITS));
  833. if(trade.PositionOpen(order_array[i].symbol,ORDER_TYPE_SELL,lotsize,bid,order_array[i].stoploss,order_array[i].takeprofit,""))
  834. {
  835. if(addOrderMaster(trade.ResultOrder(),order_array[i].ticket,order_array[i].lots, "Market"))
  836. {
  837. Print(" Sell Order Ticket:",trade.ResultOrder()," Stored!!!");
  838. }
  839. }
  840. else
  841. {
  842. Print("Copy Buy Order Send Error: "+IntegerToString(GetLastError()));
  843. }
  844. }
  845. }
  846. if(order_array[i].ordertype == ORDER_TYPE_BUY_STOP)
  847. {
  848. // Not Checking Slippage
  849. double lotsize = getLotSize(order_array[i].symbol, order_array[i].accountBalance, order_array[i].lots, order_array[i].contractSize);
  850. if(trade.BuyStop(lotsize, order_array[i].price, order_array[i].symbol, order_array[i].stoploss, order_array[i].takeprofit, 0, 0, ""))
  851. {
  852. if(addOrderMaster(trade.ResultOrder(),order_array[i].ticket,order_array[i].lots, "Pending"))
  853. {
  854. Print("Order Ticket Buy Stop:",trade.ResultOrder()," Stored!!!");
  855. }
  856. }
  857. else
  858. {
  859. Print("Error in Order Buy Stop Order: "+Symbol()+" ",GetLastError());
  860. }
  861. }
  862. if(order_array[i].ordertype == ORDER_TYPE_SELL_STOP)
  863. {
  864. double lotsize = getLotSize(order_array[i].symbol, order_array[i].accountBalance, order_array[i].lots, order_array[i].contractSize);
  865. if(trade.SellStop(lotsize, order_array[i].price, order_array[i].symbol, order_array[i].stoploss, order_array[i].takeprofit, 0, 0, ""))
  866. {
  867. if(addOrderMaster(trade.ResultOrder(),order_array[i].ticket,order_array[i].lots, "Pending"))
  868. {
  869. Print("Order Ticket Sell Stop:",trade.ResultOrder()," Stored!!!");
  870. }
  871. }
  872. else
  873. {
  874. Print("Error in Order Sell Stop Order: "+Symbol()+" ",GetLastError());
  875. }
  876. }
  877. if(order_array[i].ordertype == ORDER_TYPE_BUY_LIMIT)
  878. {
  879. double lotsize = getLotSize(order_array[i].symbol, order_array[i].accountBalance, order_array[i].lots, order_array[i].contractSize);
  880. if(trade.BuyLimit(lotsize, order_array[i].price, order_array[i].symbol, order_array[i].stoploss, order_array[i].takeprofit, 0, 0, ""))
  881. {
  882. if(addOrderMaster(trade.ResultOrder(),order_array[i].ticket,order_array[i].lots, "Pending"))
  883. {
  884. Print("Order Ticket Buy Limit:",trade.ResultOrder()," Stored!!!");
  885. }
  886. }
  887. else
  888. {
  889. Print("Error in Order Buy Limit: "+Symbol()+" ",GetLastError());
  890. }
  891. }
  892. if(order_array[i].ordertype == ORDER_TYPE_SELL_LIMIT)
  893. {
  894. double lotsize = getLotSize(order_array[i].symbol, order_array[i].accountBalance, order_array[i].lots, order_array[i].contractSize);
  895. if(trade.SellLimit(lotsize, order_array[i].price, order_array[i].symbol, order_array[i].stoploss, order_array[i].takeprofit, 0, 0, ""))
  896. {
  897. if(addOrderMaster(trade.ResultOrder(),order_array[i].ticket,order_array[i].lots, "Pending"))
  898. {
  899. Print("Order Ticket Sell Limit: ",trade.ResultOrder()," Stored!!! ", " Tp: ", order_array[i].takeprofit, " Sl: ", order_array[i].stoploss);
  900. }
  901. }
  902. else
  903. {
  904. Print("Error in Order Sell Limit: "+Symbol()+" ",GetLastError());
  905. }
  906. }
  907. }
  908. }
  909. }
  910. }
  911. for(int i=0; i<orderCount; i++)
  912. {
  913. bool trade_close = true;
  914. if(PositionSelectByTicket(cod[i].ticket))
  915. {
  916. for(int j=0; j<ArraySize(order_array); j++)
  917. {
  918. if(cod[i].magic == (order_array[j].ticket))
  919. {
  920. int digitss = getDoubleSymbolInfo(PositionGetString(POSITION_SYMBOL), "digits");
  921. trade_close = false;
  922. //Print("TP/SL | norm cod TP=",NormalizeDouble(cod[i].takeprofit,digitss),
  923. // " norm order TP=",NormalizeDouble(order_array[j].takeprofit,digitss),
  924. // " | norm cod SL=",NormalizeDouble(cod[i].stoploss,digitss),
  925. // " norm order SL=",NormalizeDouble(order_array[j].stoploss,digitss));
  926. if(NormalizeDouble(cod[i].takeprofit, digitss) != NormalizeDouble(order_array[j].takeprofit, digitss))
  927. {
  928. if(NormalizeDouble(order_array[j].takeprofit, digitss) == NormalizeDouble(PositionGetDouble(POSITION_TP), digitss))
  929. {
  930. Print(" Client Position Tp Was Manually Modified. ");
  931. cod[i].takeprofit=NormalizeDouble(order_array[j].takeprofit, digitss);
  932. }
  933. }
  934. if(NormalizeDouble(cod[i].stoploss, digitss) != NormalizeDouble(order_array[j].stoploss, digitss))
  935. {
  936. if(NormalizeDouble(order_array[j].stoploss, digitss) == NormalizeDouble(PositionGetDouble(POSITION_SL), digitss))
  937. {
  938. Print(" Client Position SL Was Manually Modified. ");
  939. cod[i].stoploss = NormalizeDouble(order_array[j].stoploss, digitss);
  940. }
  941. }
  942. if(NormalizeDouble(cod[i].takeprofit, digitss) != NormalizeDouble(order_array[j].takeprofit, digitss) || NormalizeDouble(cod[i].stoploss, digitss) != NormalizeDouble(order_array[j].stoploss, digitss))
  943. {
  944. if(trade.PositionModify(PositionGetInteger(POSITION_TICKET),order_array[j].stoploss,order_array[j].takeprofit))
  945. {
  946. Print("Order modified ticket:",PositionGetInteger(POSITION_TICKET));
  947. cod[i].takeprofit=NormalizeDouble(order_array[j].takeprofit, digitss);
  948. cod[i].stoploss=NormalizeDouble(order_array[j].stoploss, digitss);
  949. }
  950. else
  951. {
  952. //ExpertRemove();
  953. Print("Order not modified error:",GetLastError());
  954. }
  955. }
  956. }
  957. }
  958. if(trade_close == true)
  959. {
  960. if(PositionGetInteger(POSITION_TYPE)== ORDER_TYPE_BUY)
  961. {
  962. if(!trade.PositionClose(PositionGetInteger(POSITION_TICKET)))
  963. {
  964. Print("Buy Order Close Error on Master Trade Close: "+IntegerToString(GetLastError()));
  965. }
  966. else
  967. {
  968. Print("Order close by no master copy of trade");
  969. cod[i].ticket=-1;
  970. }
  971. }
  972. if(PositionGetInteger(POSITION_TYPE)== ORDER_TYPE_SELL)
  973. {
  974. if(!trade.PositionClose(PositionGetInteger(POSITION_TICKET)))
  975. {
  976. Print("Sell Order Close Error on Master Trade Close: "+IntegerToString(GetLastError()));
  977. }
  978. else
  979. {
  980. Print("Order close by no master copy of trade");
  981. cod[i].ticket=-1;
  982. }
  983. }
  984. }
  985. }
  986. if(OrderSelect(cod[i].ticket))
  987. {
  988. for(int j=0; j<ArraySize(order_array); j++)
  989. {
  990. if(cod[i].magic == (order_array[j].ticket))
  991. {
  992. trade_close = false;
  993. if(OrderGetDouble(ORDER_TP)!=order_array[j].takeprofit || OrderGetDouble(ORDER_SL)!=order_array[j].stoploss || OrderGetDouble(ORDER_PRICE_OPEN)!=order_array[j].price)
  994. {
  995. if(trade.OrderModify(OrderGetInteger(ORDER_TICKET),order_array[j].price,order_array[j].stoploss,order_array[j].takeprofit, 0, 0, 0))
  996. {
  997. Print("Pending Order modified ticket:",PositionGetInteger(POSITION_TICKET));
  998. cod[i].takeprofit=order_array[j].takeprofit;
  999. cod[i].stoploss=order_array[j].stoploss;
  1000. cod[i].price = order_array[j].price;
  1001. }
  1002. else
  1003. {
  1004. Print("Order not modified error:",GetLastError());
  1005. }
  1006. }
  1007. }
  1008. }
  1009. if(trade_close == true)
  1010. {
  1011. 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)
  1012. {
  1013. if(!trade.OrderDelete(OrderGetInteger(ORDER_TICKET)))
  1014. {
  1015. Print("Error in Deleting Pending Order: "+IntegerToString(GetLastError()));
  1016. }
  1017. else
  1018. {
  1019. Print("Pending Order Deleted. Ticket is: ", cod[i].ticket);
  1020. cod[i].ticket=-1;
  1021. }
  1022. }
  1023. }
  1024. }
  1025. }
  1026. }
  1027. }
  1028. }
  1029. }
  1030. //+------------------------------------------------------------------+
  1031. //| |
  1032. //+------------------------------------------------------------------+
  1033. void print()
  1034. {
  1035. for(int i=0; i<orderCount; i++)
  1036. {
  1037. if(cod[i].ticket!=-1)
  1038. {
  1039. Print("Ticket : ",cod[i].ticket," OPen price: ",cod[i].price, " Type: ",cod[i].ordertype);
  1040. }
  1041. }
  1042. }
  1043. //+------------------------------------------------------------------+
  1044. //| |
  1045. //+------------------------------------------------------------------+
  1046. bool isOrderThere(ulong ticket,int &index)
  1047. {
  1048. for(int i=0; i<ArraySize(mod1); i++)
  1049. {
  1050. if(ticket != -1)
  1051. {
  1052. if(mod1[i].ticket==ticket)
  1053. {
  1054. index=i;
  1055. return true;
  1056. }
  1057. }
  1058. }
  1059. return false;
  1060. }
  1061. //+------------------------------------------------------------------+
  1062. //| |
  1063. //+------------------------------------------------------------------+
  1064. void emptyStruct()
  1065. {
  1066. for(int i = 0 ; i < orderCount ; i++)
  1067. {
  1068. if(mod1[i].ticket != -1)
  1069. {
  1070. mod1[i].ticket=-1;
  1071. mod1[i].magic=0;
  1072. mod1[i].price=-1;
  1073. mod1[i].symbol="";
  1074. mod1[i].ordertype=-1;
  1075. mod1[i].lots=0;
  1076. mod1[i].stoploss=0;
  1077. mod1[i].takeprofit=0;
  1078. }
  1079. }
  1080. }
  1081. //+------------------------------------------------------------------+
  1082. //| |
  1083. //+------------------------------------------------------------------+
  1084. void deleteAllArray()
  1085. {
  1086. for(int i=0; i<orderCount; i++)
  1087. {
  1088. if(cod[i].ticket!=-1)
  1089. {
  1090. cod[i].ticket=-1;
  1091. }
  1092. }
  1093. }
  1094. //+------------------------------------------------------------------+
  1095. //| |
  1096. //+------------------------------------------------------------------+
  1097. double dealOutLotsCheck(datetime cutOffTimeIs, ulong positionId)
  1098. {
  1099. double sumOfLots = 0.0;
  1100. if(HistorySelect(cutOffTimeIs,LONG_MAX))
  1101. {
  1102. int totalDeals = HistoryDealsTotal();
  1103. for(int i = 0; i < totalDeals; i++)
  1104. {
  1105. ulong dealTicket = HistoryDealGetTicket(i);
  1106. ulong dealPositionID = (ulong)HistoryDealGetInteger(dealTicket, DEAL_POSITION_ID);
  1107. if(HistoryDealGetInteger(dealTicket, DEAL_ENTRY) == DEAL_ENTRY_OUT
  1108. && dealPositionID == positionId)
  1109. {
  1110. sumOfLots += HistoryDealGetDouble(dealTicket, DEAL_VOLUME);
  1111. }
  1112. }
  1113. }
  1114. return sumOfLots;
  1115. }
  1116. //+------------------------------------------------------------------+
  1117. //| |
  1118. //+------------------------------------------------------------------+
  1119. bool addOrderMaster(ulong ticket,ulong magic,double lot, string calledBy)
  1120. {
  1121. Print("in addOrderMaster: ", ticket);
  1122. bool notFoundPosition=false;//Use to look in to the order loop in case order isn't converted
  1123. if(OrderSelect(ticket))
  1124. {
  1125. Print("Inside order selection:");
  1126. Print("Order State:",(ENUM_ORDER_STATE)OrderGetInteger(ORDER_STATE));
  1127. Print("Order Time done:",(datetime)OrderGetInteger(ORDER_TIME_DONE));
  1128. Print("Order Type:",(ENUM_ORDER_TYPE)OrderGetInteger(ORDER_TYPE));
  1129. }
  1130. else
  1131. if(HistoryOrderSelect(ticket))
  1132. {
  1133. Print("Inside history order selection:");
  1134. Print("Order State:",(ENUM_ORDER_STATE)HistoryOrderGetInteger(ticket,ORDER_STATE));
  1135. Print("Order Time done:",(datetime)HistoryOrderGetInteger(ticket,ORDER_TIME_DONE));
  1136. Print("Order Type:",(ENUM_ORDER_TYPE)HistoryOrderGetInteger(ticket,ORDER_TYPE));
  1137. }
  1138. else
  1139. {
  1140. PrintFormat("OrderSelect(%I64u) failed. Error %d", ticket, GetLastError());
  1141. }
  1142. for(int i=0; i<orderCount; i++)
  1143. {
  1144. if(cod[i].ticket==-1)
  1145. {
  1146. if(calledBy == "Market")
  1147. {
  1148. if(PositionSelectByTicket(ticket))
  1149. {
  1150. cod[i].ticket=PositionGetInteger(POSITION_TICKET);
  1151. cod[i].price=PositionGetDouble(POSITION_PRICE_OPEN);
  1152. cod[i].symbol=PositionGetString(POSITION_SYMBOL);
  1153. cod[i].ordertype=PositionGetInteger(POSITION_TYPE);
  1154. cod[i].lots=PositionGetDouble(POSITION_VOLUME);
  1155. cod[i].stoploss=PositionGetDouble(POSITION_SL);
  1156. cod[i].takeprofit=PositionGetDouble(POSITION_TP);
  1157. cod[i].magic=PositionGetInteger(POSITION_MAGIC);
  1158. cod[i].comments=PositionGetString(POSITION_COMMENT);
  1159. cod[i].masterLot = lot;
  1160. Print("Ticket stored in master:",PositionGetInteger(POSITION_TICKET)," stored in index:",i);
  1161. Print("========== CLIENT ORDER STORED ==========");
  1162. Print(" index=", i,
  1163. " | master_magic=", cod[i].magic,
  1164. " | client_ticket=", cod[i].ticket,
  1165. " | symbol=", cod[i].symbol,
  1166. " | order_type=", cod[i].ordertype,
  1167. " | open_price=", DoubleToString(cod[i].price, _Digits),
  1168. " | lots=", DoubleToString(cod[i].lots, 2),
  1169. " | master_lot=", DoubleToString(cod[i].masterLot, 2),
  1170. " | sl=", DoubleToString(cod[i].stoploss, _Digits),
  1171. " | tp=", DoubleToString(cod[i].takeprofit, _Digits),
  1172. " | comment=", cod[i].comments);
  1173. Print("========================================");
  1174. return true;
  1175. }
  1176. else
  1177. {
  1178. Print("Ticket:",ticket," not found in the position list");
  1179. notFoundPosition=true;
  1180. }
  1181. }
  1182. if(calledBy == "Pending" || notFoundPosition)
  1183. {
  1184. if(OrderSelect(ticket))
  1185. {
  1186. cod[i].ticket=OrderGetInteger(ORDER_TICKET);
  1187. cod[i].price=OrderGetDouble(ORDER_PRICE_OPEN);
  1188. cod[i].symbol=OrderGetString(ORDER_SYMBOL);
  1189. cod[i].ordertype=OrderGetInteger(ORDER_TYPE);
  1190. cod[i].lots=OrderGetDouble(ORDER_VOLUME_CURRENT);
  1191. cod[i].stoploss=OrderGetDouble(ORDER_SL);
  1192. cod[i].takeprofit=OrderGetDouble(ORDER_TP);
  1193. cod[i].magic=OrderGetInteger(ORDER_MAGIC);
  1194. cod[i].comments=OrderGetString(ORDER_COMMENT);
  1195. cod[i].masterLot = lot;
  1196. Print("Pending Order Ticket in master:",OrderGetInteger(ORDER_TICKET)," stored in index:",i);
  1197. return true;
  1198. }
  1199. else
  1200. {
  1201. Print("Ticket:",ticket," not found in the order list");
  1202. }
  1203. }
  1204. }
  1205. }
  1206. return false;
  1207. }
  1208. //+------------------------------------------------------------------+
  1209. //+------------------------------------------------------------------+
  1210. //| |
  1211. //+------------------------------------------------------------------+
  1212. double getDoubleSymbolInfo(string symbol,string info)
  1213. {
  1214. long digits=8;
  1215. //Symbol without the suffix and prefix
  1216. string updatedSymbol=symbol;
  1217. if(suffix!="")
  1218. updatedSymbol = StringSubstr(updatedSymbol,0,StringFind(updatedSymbol,suffix,0));
  1219. if(prefix!="")
  1220. StringReplace(updatedSymbol,prefix,"");
  1221. //Digits calculation could be used in other calculations
  1222. digits = SymbolInfoInteger(symbol,SYMBOL_DIGITS);
  1223. if(digits==0)
  1224. {
  1225. digits=SymbolInfoInteger(updatedSymbol,SYMBOL_DIGITS);
  1226. if(digits==0)
  1227. digits=8;
  1228. }
  1229. if(info=="digits")
  1230. {
  1231. return (double)digits;
  1232. }
  1233. else
  1234. if(info=="point" || info=="points")
  1235. {
  1236. double points=SymbolInfoDouble(symbol, SYMBOL_POINT);
  1237. if(points==0)
  1238. {
  1239. points=SymbolInfoDouble(updatedSymbol,SYMBOL_POINT);
  1240. if(points==0)
  1241. points=0.00001;
  1242. }
  1243. return points;
  1244. }
  1245. else
  1246. if(info=="ask")
  1247. {
  1248. double ask = SymbolInfoDouble(symbol, SYMBOL_ASK);
  1249. if(ask==0)
  1250. {
  1251. ask=SymbolInfoDouble(updatedSymbol,SYMBOL_ASK);
  1252. if(ask==0)
  1253. ask=0.00001;
  1254. }
  1255. return NormalizeDouble(ask,(int)digits);
  1256. }
  1257. else
  1258. if(info=="bid")
  1259. {
  1260. double bid=SymbolInfoDouble(symbol, SYMBOL_BID);
  1261. if(bid==0)
  1262. {
  1263. bid=SymbolInfoDouble(updatedSymbol,SYMBOL_BID);
  1264. if(bid==0)
  1265. bid=0.00001;
  1266. }
  1267. return NormalizeDouble(bid,(int)digits);
  1268. }
  1269. else
  1270. if(info=="contract"||info=="contractSize")
  1271. {
  1272. double contract=SymbolInfoDouble(symbol,SYMBOL_TRADE_CONTRACT_SIZE);
  1273. if(contract==0)
  1274. {
  1275. contract=SymbolInfoDouble(updatedSymbol,SYMBOL_TRADE_CONTRACT_SIZE);
  1276. }
  1277. return contract;
  1278. }
  1279. else
  1280. if(info=="lotStep")
  1281. {
  1282. double step=SymbolInfoDouble(symbol, SYMBOL_VOLUME_STEP);
  1283. if(step==0)
  1284. {
  1285. step=SymbolInfoDouble(updatedSymbol,SYMBOL_VOLUME_STEP);
  1286. }
  1287. return step;
  1288. }
  1289. else
  1290. if(info=="minLot")
  1291. {
  1292. double minLot=SymbolInfoDouble(symbol, SYMBOL_VOLUME_MIN);
  1293. if(minLot==0)
  1294. {
  1295. minLot = SymbolInfoDouble(updatedSymbol, SYMBOL_VOLUME_MIN);
  1296. }
  1297. return minLot;
  1298. }
  1299. else
  1300. if(info=="maxLot")
  1301. {
  1302. double maxLot=SymbolInfoDouble(symbol,SYMBOL_VOLUME_MAX);
  1303. if(maxLot==0)
  1304. {
  1305. maxLot=SymbolInfoDouble(updatedSymbol,SYMBOL_VOLUME_MAX);
  1306. }
  1307. return maxLot;
  1308. }
  1309. return 0;
  1310. }
  1311. //+------------------------------------------------------------------+
  1312. //| |
  1313. //+------------------------------------------------------------------+
  1314. string getSymbol(string symbol)
  1315. {
  1316. if(mappingSymbol!="")
  1317. {
  1318. string symbollist[];
  1319. StringSplit(mappingSymbol,';',symbollist);
  1320. for(int i=0; i<ArraySize(symbollist); i++)
  1321. {
  1322. string symbolPairs[];
  1323. StringSplit(symbollist[i],',',symbolPairs);
  1324. if(ArraySize(symbolPairs)==2)
  1325. {
  1326. if(symbol==symbolPairs[0])
  1327. return symbolPairs[1];
  1328. }
  1329. }
  1330. }
  1331. else
  1332. {
  1333. return prefix+symbol+suffix;
  1334. }
  1335. return prefix+symbol+suffix;
  1336. }
  1337. //+------------------------------------------------------------------+
  1338. //| |
  1339. //+------------------------------------------------------------------+
  1340. double getLotSize(string symbol,double masterAccountBalance,double masterLot,int masterContractSize)
  1341. {
  1342. double lotsize = fixed;
  1343. Print("------> Symbol:",symbol," master Account balance:",masterAccountBalance," master lot:",masterLot," master Contract:",masterContractSize);
  1344. if(lotoption == mul)
  1345. {
  1346. lotsize = NormalizeDouble(masterLot*mult,2);
  1347. }
  1348. else
  1349. if(lotoption == Balance)
  1350. {
  1351. lotsize=((AccountInfoDouble(ACCOUNT_BALANCE)/masterAccountBalance)*masterLot)*Bmult;
  1352. }
  1353. else
  1354. if(lotoption == slaveLotCal)
  1355. {
  1356. lotsize = masterLot * (maxDd / recoveryAmount);
  1357. }
  1358. Print("Before Lot Size: ",lotsize);
  1359. if(contractChk)
  1360. {
  1361. int clientContractSize=getDoubleSymbolInfo(symbol,"contract");
  1362. Print("Client Contract size:",clientContractSize);
  1363. if(masterContractSize!=0 && clientContractSize!=0)
  1364. {
  1365. lotsize=((masterContractSize*1.0)/clientContractSize)*lotsize;
  1366. }
  1367. }
  1368. int roundDigit=0;
  1369. double step=getDoubleSymbolInfo(symbol, "lotStep");
  1370. while(step<1)
  1371. {
  1372. roundDigit++;
  1373. step=step*10;
  1374. }
  1375. Print("Round Digits:",roundDigit);
  1376. lotsize = NormalizeDouble(lotsize,roundDigit);
  1377. if(lotsize<getDoubleSymbolInfo(symbol,"minLot"))
  1378. lotsize=getDoubleSymbolInfo(symbol,"minLot");
  1379. else
  1380. if(lotsize>getDoubleSymbolInfo(symbol,"maxLot"))
  1381. lotsize=getDoubleSymbolInfo(symbol,"maxLot");
  1382. Print("Lot Size: ",lotsize);
  1383. return lotsize;
  1384. }
  1385. //+------------------------------------------------------------------+
  1386. //| |
  1387. //+------------------------------------------------------------------+
  1388. void adminHeartBeat()
  1389. {
  1390. string headers = "apikey:"+localApiKey+"\r\naccept: */* \r\nContent-Type: application/json\r\nUser-Agent: MetaTraderApi";
  1391. string url =localHB_req_link;// Request_link+(string)accountNumber;
  1392. bool isPost;
  1393. int timeout = 100000;
  1394. string lastConnected=TimeToString(TimeCurrent());
  1395. StringReplace(lastConnected,".","-");
  1396. StringReplace(lastConnected," ","T");
  1397. string gmtTime=TimeToString(TimeGMT());
  1398. string jsonData="{\"sLogin\":\""+(string)accountNumber+"\",\"sServer\":\""+clientServer+"\",\"sVersion\":\"5\" ,\"sLastConnected\":\""+gmtTime+"\"}";//\",\"url\":"+"\""+url+"\""+headers+"}";
  1399. uchar data[];
  1400. StringToCharArray(jsonData, data, 0, StringLen(jsonData));
  1401. // Print("Making the heart beat request to the local host");
  1402. POST_function(url,headers,timeout,data,isPost);
  1403. }
  1404. //+------------------------------------------------------------------+
  1405. //| |
  1406. //+------------------------------------------------------------------+
  1407. bool POST_function(string url, string headers, int timeout, uchar &data[], bool &IsPost)
  1408. {
  1409. ResetLastError(); // clear previous error
  1410. static int lastErrorPrinted = 0;
  1411. uchar result[]; // use uchar for WebRequest result
  1412. string resultHeaders;
  1413. int res = WebRequest("POST", url, headers, timeout, data, result, resultHeaders);
  1414. if(res == 200 || res == 201)
  1415. {
  1416. Print("***Request success. HTTP response code POST: ", res);
  1417. string result_string = CharArrayToString(result);
  1418. Print("content POST: ", result_string);
  1419. lastErrorPrinted = 0; // reset remembered error on success
  1420. IsPost = true;
  1421. return true;
  1422. }
  1423. else
  1424. {
  1425. int err = GetLastError(); // read the error once
  1426. // only print when there's a real error and it's different from last time
  1427. if(err != 0 && err != lastErrorPrinted)
  1428. {
  1429. Print("Get last error: ", err);
  1430. Print("***Request failed. HTTP response code: ", res);
  1431. string result_string = CharArrayToString(result);
  1432. Print("content: ", result_string);
  1433. lastErrorPrinted = err; // remember this error so we don't spam it
  1434. }
  1435. IsPost = false;
  1436. return false;
  1437. }
  1438. }
  1439. //+------------------------------------------------------------------+
  1440. //| |
  1441. //+------------------------------------------------------------------+
  1442. void clearOrderArray()
  1443. {
  1444. //Resize to one
  1445. ArrayResize(order_array,1);
  1446. //Clear all data
  1447. order_array[0].symbol = "";
  1448. order_array[0].opentime = 0;
  1449. order_array[0].price = 0;
  1450. order_array[0].ordertype = 0;
  1451. order_array[0].lots = 0;
  1452. order_array[0].stoploss = 0;
  1453. order_array[0].takeprofit = 0;
  1454. order_array[0].ticket = -1;
  1455. order_array[0].magicNo = 0;
  1456. order_array[0].accountBalance=0;
  1457. order_array[0].contractSize=0;
  1458. order_array[0].comments="";
  1459. order_array[0].closedPercentageOfTrade = 0;
  1460. }
  1461. //+------------------------------------------------------------------+
  1462. //| |
  1463. //+------------------------------------------------------------------+
  1464. void mapHistory()
  1465. {
  1466. for(int i=0; i<PositionsTotal(); i++)
  1467. {
  1468. ulong ticket = PositionGetTicket(i);
  1469. if(PositionSelectByTicket(ticket))
  1470. {
  1471. if(PositionGetInteger(POSITION_MAGIC) > 999)
  1472. {
  1473. addOrderMaster(PositionGetInteger(POSITION_TICKET), PositionGetInteger(POSITION_MAGIC), PositionGetDouble(POSITION_VOLUME), "Market");
  1474. }
  1475. }
  1476. }
  1477. for(int i=0; i<OrdersTotal(); i++)
  1478. {
  1479. ulong ticket = OrderGetTicket(i);
  1480. if(OrderSelect(ticket))
  1481. {
  1482. if(OrderGetInteger(ORDER_MAGIC) > 999)
  1483. {
  1484. addOrderMaster(OrderGetInteger(ORDER_TICKET), OrderGetInteger(ORDER_MAGIC), OrderGetDouble(ORDER_VOLUME_CURRENT), "Pending");
  1485. }
  1486. }
  1487. }
  1488. }
  1489. //+------------------------------------------------------------------+
  1490. //| |
  1491. //+------------------------------------------------------------------+
  1492. bool addToMarketWatch(string symbol)
  1493. {
  1494. Print("Symbol:",symbol);
  1495. bool result=SymbolSelect(symbol,true);
  1496. if(result)
  1497. {
  1498. Print("Successfully added the symbol or already there:", symbol);
  1499. return true;
  1500. }
  1501. else
  1502. {
  1503. Print("Error in adding symbol:",symbol);
  1504. }
  1505. return false;
  1506. }
  1507. //+------------------------------------------------------------------+
  1508. //| |
  1509. //+------------------------------------------------------------------+
  1510. void read_history_file()
  1511. {
  1512. string file_name = "history_trades.csv";
  1513. if(!FileIsExist(file_name, FILE_COMMON))
  1514. {
  1515. Print("File not found: ", file_name);
  1516. return;
  1517. }
  1518. int h = FileOpen(file_name, FILE_SHARE_READ|FILE_CSV|FILE_COMMON|FILE_READ|FILE_ANSI|FILE_TXT|FILE_COMMON);
  1519. if(h == INVALID_HANDLE)
  1520. {
  1521. Print("Error opening file: ", file_name, " Err:", GetLastError());
  1522. return;
  1523. }
  1524. datetime lastFileModified=(datetime)FileGetInteger(h,FILE_MODIFY_DATE);
  1525. long fileSize=FileGetInteger(h,FILE_SIZE);
  1526. if(lastModified1==lastFileModified && fileSize==lastFileSize1)
  1527. {
  1528. FileClose(h);
  1529. return;
  1530. }
  1531. else
  1532. {
  1533. ulong fileTickets[];
  1534. ArrayResize(fileTickets, 0);
  1535. while(!FileIsEnding(h))
  1536. {
  1537. string line = FileReadString(h);
  1538. // split by comma
  1539. string parts[];
  1540. int count = StringSplit(line,',', parts);
  1541. if(count >= 2)
  1542. {
  1543. // convert to integers
  1544. ulong ticket = StringToInteger(parts[0]);
  1545. ulong magic = StringToInteger(parts[1]);
  1546. int newSize = ArraySize(fileTickets) + 1;
  1547. ArrayResize(fileTickets, newSize);
  1548. fileTickets[newSize - 1] = ticket;
  1549. if(!history_ticket_present(ticket))
  1550. add_history_ticket(ticket, magic);
  1551. }
  1552. else
  1553. {
  1554. // Print("Skipped malformed line while reading ", file_name, " : ", line);
  1555. }
  1556. }
  1557. FileClose(h);
  1558. lastModified1=lastFileModified;
  1559. lastFileSize1=fileSize;
  1560. for(int i = 0; i < MaxOrders; i++)
  1561. {
  1562. ulong tk = historyTradeStore[i].ticket;
  1563. if(tk == -1)
  1564. continue;
  1565. bool found = false;
  1566. for(int j = 0; j < ArraySize(fileTickets); j++)
  1567. {
  1568. if(fileTickets[j] == tk)
  1569. {
  1570. found = true;
  1571. break;
  1572. }
  1573. }
  1574. if(!found)
  1575. {
  1576. Print("Removing ticket not found in file: ", tk, " index=", i);
  1577. historyTradeStore[i].ticket = -1;
  1578. historyTradeStore[i].magic = 0;
  1579. }
  1580. }
  1581. }
  1582. }
  1583. //+------------------------------------------------------------------+
  1584. //| |
  1585. //+------------------------------------------------------------------+
  1586. void add_history_ticket(ulong ticket, ulong magicIs)
  1587. {
  1588. for(int i = 0; i < MaxOrders; i++)
  1589. {
  1590. if(historyTradeStore[i].ticket == -1)
  1591. {
  1592. historyTradeStore[i].ticket = ticket;
  1593. historyTradeStore[i].magic = magicIs;
  1594. Print(" -------- add_history_ticket() Added ticket: ", ticket, " Magic: ", magicIs, " ---------------------------- ");
  1595. return;
  1596. }
  1597. }
  1598. Print("historyTradeStore full, cannot add ticket: ", ticket);
  1599. }
  1600. //+------------------------------------------------------------------+
  1601. //| |
  1602. //+------------------------------------------------------------------+
  1603. bool history_ticket_present(ulong ticket)
  1604. {
  1605. for(int i = 0 ; i < MaxOrders ; i++)
  1606. {
  1607. if(historyTradeStore[i].ticket == ticket)
  1608. return true;
  1609. }
  1610. return false;
  1611. }
  1612. //+------------------------------------------------------------------+
  1613. //+------------------------------------------------------------------+
  1614. //| |
  1615. //+------------------------------------------------------------------+