Nenhuma descrição

localHedgingClientCopierMt5.mq5 74KB

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