Brak opisu

localHedgingMasterCopierMt5.mq5 166KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123
  1. //+------------------------------------------------------------------+
  2. //| localHedgingMasterCopierMt5.mq5 |
  3. //| Copyright 2025, MQL Development |
  4. //| https://www.mqldevelopment.com/ |
  5. //+------------------------------------------------------------------+
  6. #property copyright "Copyright 2025, MQL Development"
  7. #property link "https://www.mqldevelopment.com/"
  8. #property version "1.00"
  9. #include <Trade\Trade.mqh>
  10. CTrade trade;
  11. #define orderCount 2000
  12. #define count1 50
  13. #define testCounter 50
  14. #define MaxOrders 20000
  15. #define daysOfTradesToAdd 20
  16. #property description "Control Panels and Dialogs. Demonstration class CLabel"
  17. #include <Controls\Dialog.mqh>
  18. #include <Controls\Label.mqh>
  19. #include <Controls\Button.mqh>
  20. #include <Controls\RadioButton.mqh>
  21. #include <Controls\RadioGroup.mqh>
  22. #include <Controls\CheckBox.mqh>
  23. #include <Controls\ComboBox.mqh>
  24. //+------------------------------------------------------------------+
  25. //| Expert initialization function |
  26. //+------------------------------------------------------------------+
  27. struct historyTradesClientSide
  28. {
  29. ulong ticket;
  30. ulong magic;
  31. historyTradesClientSide()
  32. {
  33. ticket = -1;
  34. magic = 0;
  35. }
  36. };
  37. historyTradesClientSide historyTradeStore[MaxOrders];
  38. struct masterOrder
  39. {
  40. datetime opentime;
  41. string symbol;
  42. ulong ordertype;
  43. double price;
  44. double lots;
  45. double stoploss;
  46. double takeprofit;
  47. ulong ticket;
  48. ulong magic;
  49. double accountBalance;
  50. int contractSize;
  51. string comment;
  52. masterOrder()
  53. {
  54. ticket=-1;
  55. price=-1;
  56. symbol=Symbol();
  57. ordertype=-1;
  58. lots=0;
  59. stoploss=0;
  60. takeprofit=0;
  61. }
  62. };
  63. masterOrder mod1[orderCount];
  64. struct order
  65. {
  66. ulong ticket;
  67. double price;
  68. datetime opentime;
  69. string symbol;
  70. int ordertype;
  71. double lots;
  72. double stoploss;
  73. double takeprofit;
  74. double accountBalance;
  75. int contractSize;
  76. string comments;
  77. ulong magicNo;
  78. double closedPercentageOfTrade;
  79. order()
  80. {
  81. ticket =-1;
  82. closedPercentageOfTrade = 0;
  83. }
  84. };
  85. struct clientOrder
  86. {
  87. ulong ticket;
  88. double price;
  89. datetime opentime;
  90. string symbol;
  91. int ordertype;
  92. double lots;
  93. double stoploss;
  94. double takeprofit;
  95. ulong magic;
  96. string comments;
  97. double masterLot;
  98. clientOrder()
  99. {
  100. ticket=-1;
  101. price=-1;
  102. symbol=Symbol();
  103. ordertype=-1;
  104. lots=0;
  105. masterLot=0;
  106. stoploss=0;
  107. takeprofit=0;
  108. magic=-1;
  109. comments="";
  110. }
  111. };
  112. clientOrder cod[orderCount];
  113. enum operation_mode
  114. {
  115. Master, //Master
  116. Slave, //Slave
  117. };
  118. enum lotcalculator
  119. {
  120. fix, //Fixed Lot Size
  121. rsk, //Risk Percentage
  122. };
  123. sinput string string_0 = "<><><><><><> General SETTINGS <><><><><><>"; //__
  124. input int magic_no = 333; // Magic no
  125. input string suffix = ""; // Suffix
  126. input string prefix = ""; // Prefix
  127. input bool useMinimumLot = false; // Use Minimum Lot Threshold
  128. input double takeprofitTrade = 10; // Fixed Take Profit in Pips
  129. input double stoplossTrade = 10; // Fixed Stop Loss in Pips
  130. input double inpPips = 0.2; // Pips To Start Copy
  131. input double minimumLot = 0.01; // Minimum Lot
  132. input bool useMaximumLot = false; // Use Maximum Lot Threshold
  133. input double maximumLot = 0.01; // Maximum Lot
  134. input string string_0_3 = "<><><><><><> Lot Management<><><><><><>"; //__
  135. input double lot_size = 0.1; // Lot Size
  136. input lotcalculator lot_calculator = fix; // Lot Size Calculator
  137. input double risk = 0.1; // Risk in Percentage %
  138. // Heart Beat
  139. sinput string string_1 = "<><><><><><> HeartBeat Setting <><><><><><>"; //__
  140. input string slaveServer = ""; // Slave Server
  141. input string slaveId = ""; // Slave Login ID
  142. input string masterServer = ""; // Master Server
  143. input string slaveVersion = "4"; // Slave Version
  144. input string localApiKey = "U2FsdGVkX18vBY4H1uzQiZwuh8B++8VBtCGJ3yGr2XPII0qCodmfuhjssKu5oug1J4e97bkwPtDQLi4py1OODQ=="; // Local API Key
  145. input string localHB_req_link = "http://localhost/api/mlastConnected"; // Request Link For LastConnected
  146. input string dashboardSettings = "<><><><><><> Dashboard Settings<><><><><><>";
  147. input int DashHeight = 115; // Enter Height of Dashboard
  148. input int DashWidth = 490; // Enter Width of Dashboard
  149. input int FontSize = 10; // Text Font Size
  150. // Global Variables
  151. int filehandle;
  152. int gmtDifference = 0;
  153. bool doReversal = true; // Reverse Trades
  154. bool auth = false;
  155. datetime last_check_expiry;
  156. ENUM_TIMEFRAMES check_expiry_timeframe = PERIOD_H1;
  157. int orderTotal=0;
  158. bool fileLastEmpty=false;
  159. bool fileHandlerIssue=false;
  160. int counter = 0, testCounterVar = 0;
  161. int yAxisGlobal = 5;
  162. int dashHeight; // Height of Dashboard
  163. int dashWidth; // Width of Dashboard
  164. long accountNumber = AccountInfoInteger(ACCOUNT_LOGIN);
  165. operation_mode mode1=Master; //Working Mode
  166. order order_array[];
  167. long lastFileSize=0;
  168. datetime lastModified=0;
  169. string symbolExclude = ""; // Symbol to Exclude
  170. string mappingSymbol = ""; // Mapping Pairs Inp,Out;Inp,Out
  171. int OnInit()
  172. {
  173. //---
  174. trade.SetExpertMagicNumber(magic_no);
  175. trade.SetDeviationInPoints(10);
  176. trade.SetTypeFilling(ORDER_FILLING_IOC);
  177. trade.LogLevel(LOG_LEVEL_ALL);
  178. trade.SetAsyncMode(false);
  179. if(!ObjectFind(0,"mode") || ObjectGetString(0,"mode",OBJPROP_TEXT,0)!=EnumToString(mode1)+" Account")
  180. {
  181. ObjectDelete(0,"mode");
  182. ObjectCreate(0,"mode",OBJ_LABEL,0,0,0);
  183. ObjectSetInteger(0,"mode",OBJPROP_XDISTANCE,10);
  184. ObjectSetInteger(0,"mode",OBJPROP_YDISTANCE,25);
  185. ObjectSetInteger(0,"mode",OBJPROP_CORNER,CORNER_RIGHT_UPPER);
  186. ObjectSetInteger(0,"mode",OBJPROP_ANCHOR,ANCHOR_RIGHT_UPPER);
  187. ObjectSetInteger(0,"mode",OBJPROP_COLOR,clrLightBlue);
  188. ObjectSetString(0,"mode",OBJPROP_TEXT,EnumToString(mode1)+" Account");
  189. ObjectSetInteger(0,"mode",OBJPROP_FONTSIZE,14);
  190. }
  191. dashHeight = DashHeight;
  192. dashWidth = DashWidth;
  193. double width = double(ChartGetInteger(0,CHART_WIDTH_IN_PIXELS));
  194. double height = double(ChartGetInteger(0,CHART_HEIGHT_IN_PIXELS));
  195. double minHeight = (110/height) * (height);
  196. double minWidth = (480.0/width) * (width);
  197. Print(" Minimum Required minHeight = ",minHeight," minWidth ",minWidth);
  198. if(dashWidth < minWidth)
  199. {
  200. dashWidth = (int)minWidth;
  201. Print(" Dashboard width is updated because user input is less than required width ");
  202. }
  203. if(dashHeight < minHeight)
  204. {
  205. dashHeight = (int)minHeight;
  206. Print(" Dashboard Height is updated because user input is less than required Height ");
  207. }
  208. if(!ExtDialog.Create(0,"Local Hedge Master",10,10,40,dashWidth,dashHeight)) // the panel position
  209. return(INIT_FAILED);
  210. ExtDialog.Run();
  211. gmtDifference = (int)TimeCurrent() - (int)TimeGMT();
  212. Print("GMT Difference(sec): ",gmtDifference);
  213. EventSetMillisecondTimer(1000);
  214. //---
  215. return(INIT_SUCCEEDED);
  216. }
  217. //+------------------------------------------------------------------+
  218. //| Expert deinitialization function |
  219. //+------------------------------------------------------------------+
  220. void OnDeinit(const int reason)
  221. {
  222. //---
  223. ExtDialog.Destroy(reason);
  224. EventKillTimer();
  225. }
  226. //+------------------------------------------------------------------+
  227. //| Expert tick function |
  228. //+------------------------------------------------------------------+
  229. void OnTimer()
  230. {
  231. gmtDifference = (int)TimeCurrent() - (int)TimeGMT();
  232. dashboard_data();
  233. remove_old_tickets_from_store();
  234. store_live_and_history_tickets();
  235. writeData();
  236. readDataCofClient();
  237. }
  238. //+------------------------------------------------------------------+
  239. //| |
  240. //+------------------------------------------------------------------+
  241. void OnTick()
  242. {
  243. //---
  244. }
  245. //+------------------------------------------------------------------+
  246. //| |
  247. //+------------------------------------------------------------------+
  248. void OnChartEvent(const int id,
  249. const long &lparam,
  250. const double &dparam,
  251. const string &sparam)
  252. {
  253. //---
  254. ExtDialog.ChartEvent(id,lparam,dparam,sparam);
  255. }
  256. //+------------------------------------------------------------------+
  257. //| |
  258. //+------------------------------------------------------------------+
  259. void readDataCofClient()
  260. {
  261. int fileHandleClient = 0;
  262. fileHandleClient = FileOpen("COF_client.csv",
  263. FILE_SHARE_READ|FILE_CSV|FILE_COMMON|FILE_READ|FILE_ANSI|FILE_TXT|FILE_COMMON);
  264. if(fileHandleClient != INVALID_HANDLE)
  265. {
  266. datetime lastFileModified = (datetime)FileGetInteger(fileHandleClient, FILE_MODIFY_DATE);
  267. long fileSize = FileGetInteger(fileHandleClient, FILE_SIZE);
  268. if(lastModified == lastFileModified && fileSize == lastFileSize)
  269. {
  270. FileClose(fileHandleClient);
  271. }
  272. else
  273. {
  274. clearOrderArray();
  275. while(!FileIsEnding(fileHandleClient))
  276. {
  277. string OrderToRead = FileReadString(fileHandleClient);
  278. string Order_specs[];
  279. StringSplit(OrderToRead, StringGetCharacter(",", 0), Order_specs);
  280. if(ArraySize(Order_specs) == 12 || ArraySize(Order_specs) == 13)
  281. {
  282. string symbol = getSymbol(Order_specs[1]);
  283. int orderType = StringToInteger(Order_specs[2]);
  284. ArrayResize(order_array, ArraySize(order_array) + 1);
  285. order_array[ArraySize(order_array)-1].symbol = symbol;
  286. order_array[ArraySize(order_array)-1].opentime = StringToTime(Order_specs[0]);
  287. order_array[ArraySize(order_array)-1].price = StringToDouble(Order_specs[3]);
  288. order_array[ArraySize(order_array)-1].ordertype = orderType;
  289. order_array[ArraySize(order_array)-1].lots = StringToDouble(Order_specs[4]);
  290. order_array[ArraySize(order_array)-1].stoploss = StringToDouble(Order_specs[5]);
  291. order_array[ArraySize(order_array)-1].takeprofit = StringToDouble(Order_specs[6]);
  292. order_array[ArraySize(order_array)-1].ticket = StringToInteger(Order_specs[7]);
  293. order_array[ArraySize(order_array)-1].magicNo = StringToInteger(Order_specs[8]);
  294. order_array[ArraySize(order_array)-1].accountBalance=StringToDouble(Order_specs[9]);
  295. order_array[ArraySize(order_array)-1].closedPercentageOfTrade = StringToDouble(Order_specs[10]);
  296. order_array[ArraySize(order_array)-1].contractSize=StringToInteger(Order_specs[11]);
  297. if(ArraySize(Order_specs) == 13)
  298. order_array[ArraySize(order_array)-1].comments=Order_specs[12];
  299. else
  300. order_array[ArraySize(order_array)-1].comments="";
  301. if(ArraySize(Order_specs) == 13)
  302. {
  303. StringReplace(Order_specs[12],"from #","");
  304. StringReplace(Order_specs[12]," ","");
  305. Print(" Order_specs[12] ",Order_specs[12],
  306. " order_array[ArraySize(order_array)-1].ticket ",order_array[ArraySize(order_array)-1].ticket);
  307. }
  308. Print(" Client Magic: ", order_array[ArraySize(order_array)-1].magicNo,
  309. " | Client Ticket: ", order_array[ArraySize(order_array)-1].ticket,
  310. " | Symbol: ", order_array[ArraySize(order_array)-1].symbol,
  311. " | Open Price: ", order_array[ArraySize(order_array)-1].price,
  312. " | Lot: ", order_array[ArraySize(order_array)-1].lots,
  313. " | Lot Closed %: ", order_array[ArraySize(order_array)-1].closedPercentageOfTrade,
  314. " | Open time: ", order_array[ArraySize(order_array)-1].opentime);
  315. }
  316. }
  317. lastModified = lastFileModified;
  318. lastFileSize = fileSize;
  319. FileClose(fileHandleClient);
  320. }
  321. }
  322. // Order Operations
  323. int arraySize=ArraySize(order_array);
  324. if(ArraySize(order_array) == 0) //
  325. {
  326. //if(PositionsTotal() > 0)
  327. // {
  328. // for(int i=PositionsTotal()-1; i>=0; i--)
  329. // {
  330. // ulong ticket = PositionGetTicket(i);
  331. // if(PositionSelectByTicket(ticket))
  332. // {
  333. // if(history_ticket_present(PositionGetInteger(POSITION_MAGIC)))
  334. // if(!trade.PositionClose(ticket))
  335. // {
  336. // Print(" Order Close Error on No Master Trade: "+IntegerToString(GetLastError()));
  337. // }
  338. // else
  339. // Print(" ------------- Order Close by empty array ------------------ ");
  340. // }
  341. // }
  342. // }
  343. //if(OrdersTotal() > 0)
  344. // {
  345. // for(int i=OrdersTotal()-1; i>=0; i--)
  346. // {
  347. // ulong ticket = OrderGetTicket(i);
  348. // if(OrderSelect(ticket))
  349. // {
  350. // if(history_ticket_present(OrderGetInteger(ORDER_MAGIC)))
  351. // if(!trade.OrderDelete(ticket))
  352. // {
  353. // Print(" Error in Deleting Pending Order (Empty Array) : "+IntegerToString(GetLastError()));
  354. // }
  355. // else
  356. // Print("Order Close by empty array (Empty Array)");
  357. // }
  358. // }
  359. // }
  360. //deleteAllArray();
  361. }
  362. //else
  363. {
  364. for(int i=0; i<ArraySize(order_array); i++)
  365. {
  366. int trade_taken = 2;
  367. int partialCloseOrderPosition=-1;
  368. double percentageToClose = 0;
  369. double closedPercentage = 0.0;
  370. double currentLot = 0.0;
  371. double totalLot = 0;
  372. int index = -1;
  373. for(int j=0; j<orderCount; j++)
  374. {
  375. if(cod[j].ticket!=-1)
  376. {
  377. // select order directly by magic number
  378. if(cod[j].magic == order_array[i].magicNo)
  379. if(PositionSelectByTicket(cod[j].magic)) // ==
  380. {
  381. trade_taken = 0;
  382. }
  383. if(cod[j].magic == order_array[i].magicNo)
  384. if(OrderSelect(order_array[i].magicNo))
  385. {
  386. trade_taken = 0;
  387. }
  388. if(PositionSelectByTicket(cod[j].magic))
  389. {
  390. double sumOfClosed = dealOutLotsCheck(0, PositionGetInteger(POSITION_TICKET));
  391. currentLot = PositionGetDouble(POSITION_VOLUME);
  392. totalLot = sumOfClosed + currentLot;
  393. if(totalLot > 0.0)
  394. closedPercentage = NormalizeDouble((sumOfClosed / totalLot) * 100.0, 1);
  395. }
  396. if(cod[j].magic == order_array[i].magicNo)
  397. {
  398. if(closedPercentage < order_array[i].closedPercentageOfTrade)
  399. {
  400. percentageToClose = MathAbs(order_array[i].closedPercentageOfTrade - closedPercentage);
  401. trade_taken=1;
  402. partialCloseOrderPosition=j;
  403. }
  404. }
  405. }
  406. }
  407. if(order_array[i].ticket != -1)
  408. {
  409. if(trade_taken==1)
  410. {
  411. //current order need to close partially
  412. if(partialCloseOrderPosition!=-1)
  413. {
  414. bool isOrderClose=false;
  415. int roundDigit=0;
  416. double step=SymbolInfoDouble(cod[partialCloseOrderPosition].symbol,SYMBOL_VOLUME_STEP);
  417. while(step<1)
  418. {
  419. roundDigit++;
  420. step=step*10;
  421. }
  422. double lotClosePer = NormalizeDouble((totalLot * percentageToClose) / 100, roundDigit);
  423. if(percentageToClose > 0 && lotClosePer > SymbolInfoDouble(cod[partialCloseOrderPosition].symbol,SYMBOL_VOLUME_MIN))
  424. {
  425. if(!trade.PositionClosePartial(cod[partialCloseOrderPosition].magic, lotClosePer))
  426. {
  427. Print("Partial order did not close:",cod[partialCloseOrderPosition].magic, " Lot To Close is: ", lotClosePer);
  428. }
  429. else
  430. {
  431. isOrderClose=true;
  432. Print("Order Partial Close. currentLot Was =", currentLot,
  433. " Percentage to close = ", percentageToClose,
  434. " Lot I am Going To close = ", lotClosePer);
  435. }
  436. }
  437. }
  438. }
  439. else
  440. if(trade_taken == 2)
  441. {
  442. // Live Orders
  443. if(PositionSelectByTicket(order_array[i].magicNo))
  444. {
  445. int index = findEmptyIndexClientStructure();
  446. cod[index].ticket = order_array[i].ticket;
  447. cod[index].price = order_array[i].price;
  448. cod[index].symbol = order_array[i].symbol;
  449. cod[index].ordertype = order_array[i].ordertype;
  450. cod[index].lots = order_array[i].lots;
  451. cod[index].stoploss = order_array[i].stoploss;
  452. cod[index].takeprofit = order_array[i].takeprofit;
  453. cod[index].magic = order_array[i].magicNo;
  454. cod[index].masterLot = PositionGetDouble(POSITION_VOLUME);
  455. cod[index].comments = order_array[i].comments;
  456. Print("========== CLIENT ORDER STORED ==========");
  457. int digitss = (int)getDoubleSymbolInfo(PositionGetString(POSITION_SYMBOL), "digits");
  458. Print(" index=", index,
  459. " | master_magic=", cod[index].magic,
  460. " | client_ticket=", cod[index].ticket,
  461. " | symbol=", cod[index].symbol,
  462. " | order_type=", cod[index].ordertype,
  463. " | open_price=", DoubleToString(cod[index].price, digitss),
  464. " | lots=", DoubleToString(cod[index].lots, 2),
  465. " | master_lot=", DoubleToString(cod[index].masterLot, 2),
  466. " | sl=", DoubleToString(cod[index].stoploss, digitss),
  467. " | tp=", DoubleToString(cod[index].takeprofit, digitss),
  468. " | comment=", cod[index].comments);
  469. Print("========================================");
  470. }
  471. // Pending Orders
  472. if(OrderSelect(order_array[i].magicNo))
  473. {
  474. int index = findEmptyIndexClientStructure();
  475. cod[index].ticket = order_array[i].ticket;
  476. cod[index].price = order_array[i].price;
  477. cod[index].symbol = order_array[i].symbol;
  478. cod[index].ordertype = order_array[i].ordertype;
  479. cod[index].lots = order_array[i].lots;
  480. cod[index].stoploss = order_array[i].stoploss;
  481. cod[index].takeprofit = order_array[i].takeprofit;
  482. cod[index].magic = order_array[i].magicNo;
  483. cod[index].masterLot = OrderGetDouble(ORDER_VOLUME_CURRENT);
  484. cod[index].comments = order_array[i].comments;
  485. Print("========== CLIENT PENDING ORDER STORED ==========");
  486. int digitss = (int)getDoubleSymbolInfo(cod[index].symbol, "digits");
  487. Print(" index=", index,
  488. " | master_magic=", cod[index].magic,
  489. " | client_ticket=", cod[index].ticket,
  490. " | symbol=", cod[index].symbol,
  491. " | order_type=", cod[index].ordertype,
  492. " | open_price=", DoubleToString(cod[index].price, digitss),
  493. " | lots=", DoubleToString(cod[index].lots, 2),
  494. " | master_lot=", DoubleToString(cod[index].masterLot, 2),
  495. " | sl=", DoubleToString(cod[index].stoploss, digitss),
  496. " | tp=", DoubleToString(cod[index].takeprofit, digitss),
  497. " | comment=", cod[index].comments);
  498. Print("===============================================");
  499. }
  500. }
  501. }
  502. }
  503. for(int i=0; i<orderCount; i++)
  504. {
  505. bool trade_close = true;
  506. if(cod[i].ticket != -1)
  507. {
  508. if(PositionSelectByTicket(cod[i].magic))
  509. {
  510. for(int j=0; j<ArraySize(order_array); j++)
  511. {
  512. //Print(" Ticket: ", cod[i].magic," Client Magic Number: ", order_array[j].magicNo, " Index: ", i);
  513. if(cod[i].magic == (order_array[j].magicNo))
  514. {
  515. int digitss = (int)getDoubleSymbolInfo(PositionGetString(POSITION_SYMBOL), "digits");
  516. trade_close = false;
  517. if(NormalizeDouble(cod[i].takeprofit, digitss) != NormalizeDouble(order_array[j].takeprofit, digitss))
  518. {
  519. if(NormalizeDouble(order_array[j].takeprofit, digitss) == NormalizeDouble(PositionGetDouble(POSITION_TP), digitss))
  520. {
  521. Print(" Master Position Tp Was Manually Modified. ");
  522. cod[i].takeprofit=NormalizeDouble(order_array[j].takeprofit, digitss);
  523. }
  524. }
  525. if(NormalizeDouble(cod[i].stoploss, digitss) != NormalizeDouble(order_array[j].stoploss, digitss))
  526. {
  527. if(NormalizeDouble(order_array[j].stoploss, digitss) == NormalizeDouble(PositionGetDouble(POSITION_SL), digitss))
  528. {
  529. Print(" Master Position SL Was Manually Modified. ");
  530. cod[i].stoploss = NormalizeDouble(order_array[j].stoploss, digitss);
  531. }
  532. }
  533. // if(PositionGetDouble(POSITION_TP)!=order_array[j].takeprofit || PositionGetDouble(POSITION_SL)!=order_array[j].stoploss)
  534. if(NormalizeDouble(cod[i].takeprofit, digitss) != NormalizeDouble(order_array[j].takeprofit, digitss) || NormalizeDouble(cod[i].stoploss, digitss) != NormalizeDouble(order_array[j].stoploss, digitss))
  535. {
  536. if(trade.PositionModify(PositionGetInteger(POSITION_TICKET),order_array[j].stoploss,order_array[j].takeprofit))
  537. {
  538. Print("Order modified ticket:",PositionGetInteger(POSITION_TICKET));
  539. cod[i].takeprofit=NormalizeDouble(order_array[j].takeprofit, digitss);
  540. cod[i].stoploss=NormalizeDouble(order_array[j].stoploss, digitss);
  541. }
  542. else
  543. {
  544. Print("Order not modified error:",GetLastError());
  545. }
  546. }
  547. }
  548. }
  549. if(trade_close == true)
  550. {
  551. if(PositionGetInteger(POSITION_TYPE)== ORDER_TYPE_BUY)
  552. {
  553. if(!trade.PositionClose(PositionGetInteger(POSITION_TICKET)))
  554. {
  555. Print("Buy Order Close Error on Master Trade Close: "+IntegerToString(GetLastError()));
  556. }
  557. else
  558. {
  559. Print("Order close by no master copy of trade");
  560. cod[i].ticket=-1;
  561. cod[i].magic = 0;
  562. }
  563. }
  564. if(PositionGetInteger(POSITION_TYPE)== ORDER_TYPE_SELL)
  565. {
  566. if(!trade.PositionClose(PositionGetInteger(POSITION_TICKET)))
  567. {
  568. Print("Sell Order Close Error on Master Trade Close: "+IntegerToString(GetLastError()));
  569. }
  570. else
  571. {
  572. Print("Order close by no master copy of trade");
  573. cod[i].ticket=-1;
  574. cod[i].magic = 0;
  575. }
  576. }
  577. }
  578. }
  579. if(OrderSelect(cod[i].magic))
  580. {
  581. for(int j=0; j<ArraySize(order_array); j++)
  582. {
  583. // Print(" Pending Ticket: ", cod[i].magic," Client Magic Number: ", order_array[j].magicNo, " Index: ", i);
  584. if(cod[i].magic == (order_array[j].magicNo))
  585. {
  586. trade_close = false;
  587. int digitss = (int)getDoubleSymbolInfo(PositionGetString(POSITION_SYMBOL), "digits");
  588. if(NormalizeDouble(cod[i].takeprofit, digitss) != NormalizeDouble(order_array[j].takeprofit, digitss))
  589. {
  590. if(NormalizeDouble(order_array[j].takeprofit, digitss) == NormalizeDouble(OrderGetDouble(ORDER_TP), digitss))
  591. {
  592. Print(" Pending Master Position Tp Was Manually Modified. ");
  593. cod[i].takeprofit=NormalizeDouble(order_array[j].takeprofit, digitss);
  594. }
  595. }
  596. if(NormalizeDouble(cod[i].stoploss, digitss) != NormalizeDouble(order_array[j].stoploss, digitss))
  597. {
  598. if(NormalizeDouble(order_array[j].stoploss, digitss) == NormalizeDouble(OrderGetDouble(ORDER_SL), digitss))
  599. {
  600. Print(" Pending Master Position SL Was Manually Modified. ");
  601. cod[i].stoploss = NormalizeDouble(order_array[j].stoploss, digitss);
  602. }
  603. }
  604. if(NormalizeDouble(cod[i].price, digitss) != NormalizeDouble(order_array[j].price, digitss))
  605. {
  606. if(NormalizeDouble(order_array[j].price, digitss) == NormalizeDouble(OrderGetDouble(ORDER_PRICE_OPEN), digitss))
  607. {
  608. Print(" Pending Master Position Price Was Manually Modified. ");
  609. cod[i].price = NormalizeDouble(order_array[j].price, digitss);
  610. }
  611. }
  612. // if(OrderGetDouble(ORDER_TP)!=order_array[j].takeprofit || OrderGetDouble(ORDER_SL)!=order_array[j].stoploss || OrderGetDouble(ORDER_PRICE_OPEN)!=order_array[j].price)
  613. 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))
  614. {
  615. if(trade.OrderModify(OrderGetInteger(ORDER_TICKET),order_array[j].price,order_array[j].stoploss,order_array[j].takeprofit, 0, 0, 0))
  616. {
  617. Print("Pending Order modified ticket:",PositionGetInteger(POSITION_TICKET));
  618. cod[i].takeprofit=order_array[j].takeprofit;
  619. cod[i].stoploss=order_array[j].stoploss;
  620. cod[i].price = order_array[j].price;
  621. }
  622. else
  623. {
  624. Print("Order not modified error:",GetLastError());
  625. }
  626. }
  627. }
  628. }
  629. if(trade_close == true)
  630. {
  631. 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)
  632. {
  633. if(!trade.OrderDelete(OrderGetInteger(ORDER_TICKET)))
  634. {
  635. Print("Error in Deleting Pending Order: "+IntegerToString(GetLastError()));
  636. }
  637. else
  638. {
  639. Print("Pending Order Deleted. Ticket is: ", cod[i].ticket);
  640. cod[i].ticket=-1;
  641. }
  642. }
  643. }
  644. }
  645. }
  646. }
  647. }
  648. }
  649. //+------------------------------------------------------------------+
  650. //| |
  651. //+------------------------------------------------------------------+
  652. int findEmptyIndexClientStructure()
  653. {
  654. for(int i = 0; i < orderCount; i++)
  655. {
  656. if(cod[i].ticket == -1)
  657. {
  658. return i;
  659. }
  660. }
  661. return -1;
  662. }
  663. //+------------------------------------------------------------------+
  664. //| |
  665. //+------------------------------------------------------------------+
  666. void print()
  667. {
  668. for(int i=0; i<orderCount; i++)
  669. {
  670. if(cod[i].ticket!=-1)
  671. {
  672. Print(" ------------------------ Magic: ", cod[i].magic," | Ticket : ",cod[i].ticket," | Open price: ",cod[i].price, " | Type: ",cod[i].ordertype, " --------------------------");
  673. }
  674. }
  675. }
  676. //+------------------------------------------------------------------+
  677. //| |
  678. //+------------------------------------------------------------------+
  679. bool ticket_present(ulong ticket)
  680. {
  681. for(int i = 0 ; i < orderCount ; i++)
  682. {
  683. if(cod[i].ticket == ticket)
  684. return true;
  685. }
  686. return false;
  687. }
  688. //+------------------------------------------------------------------+
  689. //| |
  690. //+------------------------------------------------------------------+
  691. void writeData()
  692. {
  693. if(PositionsTotal()==0 && OrdersTotal() == 0 && !fileLastEmpty && TerminalInfoInteger(TERMINAL_CONNECTED)) // && IsConnected()
  694. {
  695. filehandle=FileOpen("COF.csv",FILE_WRITE|FILE_CSV|FILE_COMMON);
  696. if(filehandle!=INVALID_HANDLE)
  697. {
  698. Print("Writing file to empty");
  699. FileWrite(filehandle,"");
  700. FileClose(filehandle);
  701. fileLastEmpty=true;
  702. emptyStruct();
  703. }
  704. else
  705. {
  706. Print("File handler issue:",GetLastError());
  707. }
  708. }
  709. else
  710. {
  711. bool updationReq=checkOrderUpdate();
  712. if(updationReq || fileHandlerIssue)
  713. {
  714. filehandle=FileOpen("COF.csv",FILE_WRITE|FILE_CSV|FILE_COMMON);
  715. if(filehandle!=INVALID_HANDLE)
  716. {
  717. fileHandlerIssue=false;
  718. for(int i = PositionsTotal()-1 ; i >= 0 ; i--)
  719. {
  720. ulong ticket = PositionGetTicket(i);
  721. if(PositionSelectByTicket(ticket))
  722. {
  723. if(((useMinimumLot && (PositionGetDouble(POSITION_VOLUME) > minimumLot))||!useMinimumLot) &&
  724. ((useMaximumLot && (PositionGetDouble(POSITION_VOLUME) < maximumLot)) || !useMaximumLot))
  725. {
  726. string time = TimeToString(PositionGetInteger(POSITION_TIME)-gmtDifference,TIME_DATE|TIME_SECONDS);
  727. string symbol = PositionGetString(POSITION_SYMBOL);
  728. double digits=getDoubleSymbolInfo(symbol,"digits");
  729. int symbolContractSize=(int)getDoubleSymbolInfo(symbol,"contract");
  730. ulong tempTicket = PositionGetInteger(POSITION_TICKET);
  731. if(suffix != "")
  732. symbol = StringSubstr(symbol, 0, StringFind(symbol, suffix, 0));
  733. if(prefix != "")
  734. StringReplace(symbol, prefix, "");
  735. long orderType = PositionGetInteger(POSITION_TYPE);
  736. double takeProfit = PositionGetDouble(POSITION_TP), stopLoss = PositionGetDouble(POSITION_SL);
  737. if(doReversal)
  738. {
  739. if(orderType == POSITION_TYPE_BUY)
  740. orderType = POSITION_TYPE_SELL;
  741. else
  742. if(orderType == POSITION_TYPE_SELL)
  743. orderType = POSITION_TYPE_BUY;
  744. takeProfit = PositionGetDouble(POSITION_SL);
  745. stopLoss = PositionGetDouble(POSITION_TP);
  746. }
  747. double sumOfClosed = dealOutLotsCheck(0, PositionGetInteger(POSITION_TICKET));
  748. double currentLot = PositionGetDouble(POSITION_VOLUME);
  749. double totalLot = sumOfClosed + currentLot;
  750. double closedPercentage = 0.0;
  751. if(totalLot > 0.0)
  752. closedPercentage = (sumOfClosed / totalLot) * 100.0;
  753. Print("Closed % = ", closedPercentage);
  754. 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";
  755. FileWrite(filehandle,OrderToWrite);
  756. }
  757. }
  758. }
  759. for(int i = OrdersTotal()-1 ; i >= 0 ; i--)
  760. {
  761. ulong ticket = OrderGetTicket(i);
  762. if(OrderSelect(ticket))
  763. {
  764. if(((useMinimumLot && (OrderGetDouble(ORDER_VOLUME_CURRENT) > minimumLot))||!useMinimumLot) &&
  765. ((useMaximumLot && (OrderGetDouble(ORDER_VOLUME_CURRENT) < maximumLot))||!useMaximumLot))
  766. {
  767. string time = TimeToString(OrderGetInteger(ORDER_TIME_SETUP)-gmtDifference,TIME_DATE|TIME_SECONDS);
  768. string symbol = OrderGetString(ORDER_SYMBOL);
  769. double digits=getDoubleSymbolInfo(symbol,"digits");
  770. int symbolContractSize=(int)getDoubleSymbolInfo(symbol,"contract");
  771. ulong tempTicket = OrderGetInteger(ORDER_TICKET);
  772. if(suffix != "")
  773. symbol = StringSubstr(symbol, 0, StringFind(symbol, suffix, 0));
  774. if(prefix != "")
  775. StringReplace(symbol, prefix, "");
  776. long orderType = OrderGetInteger(ORDER_TYPE);
  777. double takeProfit = OrderGetDouble(ORDER_TP), stopLoss = OrderGetDouble(ORDER_SL);
  778. if(doReversal)
  779. {
  780. if(orderType == ORDER_TYPE_BUY_STOP)
  781. orderType = ORDER_TYPE_SELL_LIMIT;
  782. else
  783. if(orderType == ORDER_TYPE_SELL_STOP)
  784. orderType = ORDER_TYPE_BUY_LIMIT;
  785. else
  786. if(orderType == ORDER_TYPE_BUY_LIMIT)
  787. orderType = ORDER_TYPE_SELL_STOP;
  788. else
  789. if(orderType == ORDER_TYPE_SELL_LIMIT)
  790. orderType = ORDER_TYPE_BUY_STOP;
  791. takeProfit = OrderGetDouble(ORDER_SL);
  792. stopLoss = OrderGetDouble(ORDER_TP);
  793. }
  794. double closedPercentage = 0;
  795. string OrderToWrite = time+","+symbol+","+IntegerToString(orderType)+","+DoubleToString(OrderGetDouble(ORDER_PRICE_OPEN), (int)digits)+","+DoubleToString(OrderGetDouble(ORDER_VOLUME_CURRENT),2)+","+DoubleToString(stopLoss,(int) digits)+","+DoubleToString(takeProfit, (int) digits)+","+IntegerToString(OrderGetInteger(ORDER_TICKET))+","+IntegerToString(OrderGetInteger(ORDER_MAGIC))+","+(string)AccountInfoDouble(ACCOUNT_BALANCE)+","+DoubleToString(closedPercentage)+","+(string)SymbolInfoDouble(OrderGetString(ORDER_SYMBOL),SYMBOL_TRADE_CONTRACT_SIZE)+OrderGetString(ORDER_COMMENT)+"\r\n";
  796. Print("Writing Pending Order Block.");
  797. FileWrite(filehandle,OrderToWrite);
  798. }
  799. }
  800. }
  801. FileClose(filehandle);
  802. fileLastEmpty=false;
  803. Print("File Updated:",TimeCurrent());
  804. }
  805. else
  806. {
  807. Print("File Handle Issue: ", GetLastError());
  808. }
  809. }
  810. else
  811. {
  812. if(counter>=count1 && TerminalInfoInteger(TERMINAL_CONNECTED))
  813. {
  814. if(testCounterVar>=testCounter)
  815. {
  816. testCounterVar=0;
  817. }
  818. adminHeartBeat();
  819. counter=0;
  820. }
  821. counter++;
  822. testCounterVar++;
  823. }
  824. }
  825. }
  826. //+------------------------------------------------------------------+
  827. //| |
  828. //+------------------------------------------------------------------+
  829. void adminHeartBeat()
  830. {
  831. string headers = "apikey:"+localApiKey+"\r\naccept: */* \r\nContent-Type: application/json\r\nUser-Agent: MetaTraderApi";
  832. string url =localHB_req_link;// Request_link+(string)accountNumber;
  833. bool isPost;
  834. int timeout = 100000;
  835. string lastConnected=TimeToString(TimeCurrent());
  836. StringReplace(lastConnected,".","-");
  837. StringReplace(lastConnected," ","T");
  838. string gmtTime=TimeToString(TimeGMT());
  839. string jsonData="{\"mLogin\":\""+(string)accountNumber+"\",\"mServer\":\""+masterServer+"\",\"mVersion\":\"5\" ,\"sLogin\":\""+slaveId+"\",\"sServer\":\""+slaveServer+"\",\"sVersion\":\""+slaveVersion+"\" ,\"mLastConnected\":\""+gmtTime+"\"}";//\",\"url\":"+"\""+url+"\""+headers+"}";
  840. uchar data[];
  841. StringToCharArray(jsonData, data, 0, StringLen(jsonData));
  842. // Print("Making the heart beat request to the local host");
  843. POST_function(url,headers,timeout,data,isPost);
  844. }
  845. //+------------------------------------------------------------------+
  846. //| |
  847. //+------------------------------------------------------------------+
  848. bool POST_function(string url, string headers, int timeout, uchar &data[], bool &IsPost)
  849. {
  850. ResetLastError(); // clear previous error
  851. static int lastErrorPrinted = 0;
  852. uchar result[]; // use uchar for WebRequest result
  853. string resultHeaders;
  854. int res = WebRequest("POST", url, headers, timeout, data, result, resultHeaders);
  855. if(res == 200 || res == 201)
  856. {
  857. Print("***Request success. HTTP response code POST: ", res);
  858. string result_string = CharArrayToString(result);
  859. Print("content POST: ", result_string);
  860. lastErrorPrinted = 0; // reset remembered error on success
  861. IsPost = true;
  862. return true;
  863. }
  864. else
  865. {
  866. int err = GetLastError(); // read the error once
  867. // only print when there's a real error and it's different from last time
  868. if(err != 0 && err != lastErrorPrinted)
  869. {
  870. Print("Get last error: ", err);
  871. Print("***Request failed. HTTP response code: ", res);
  872. string result_string = CharArrayToString(result);
  873. Print("content: ", result_string);
  874. lastErrorPrinted = err; // remember this error so we don't spam it
  875. }
  876. IsPost = false;
  877. return false;
  878. }
  879. }
  880. //+------------------------------------------------------------------+
  881. //| |
  882. //+------------------------------------------------------------------+
  883. void removeDeleteOrderMaster()
  884. {
  885. for(int i=0; i<orderCount; i++)
  886. {
  887. bool isPresent=false;
  888. if(mod1[i].ticket!=-1)
  889. {
  890. for(int j = PositionsTotal()-1; j>=0; j--)
  891. {
  892. ulong ticket = PositionGetTicket(j);
  893. if(PositionSelectByTicket(ticket))
  894. {
  895. if(ticket==mod1[i].ticket)
  896. {
  897. isPresent=true;
  898. }
  899. }
  900. }
  901. if(!isPresent)
  902. {
  903. Print("The order ticket:",mod1[i].ticket," found no more");
  904. //delete from list
  905. mod1[i].ticket=-1;
  906. }
  907. }
  908. }
  909. }
  910. //+------------------------------------------------------------------+
  911. //| |
  912. //+------------------------------------------------------------------+
  913. void clearOrderArray()
  914. {
  915. //Resize to one
  916. ArrayFree(order_array);
  917. ArrayResize(order_array,0);
  918. //Clear all data
  919. //order_array[0].symbol = "";
  920. //order_array[0].opentime = 0;
  921. //order_array[0].price = 0;
  922. //order_array[0].ordertype = 0;
  923. //order_array[0].lots = 0;
  924. //order_array[0].stoploss = 0;
  925. //order_array[0].takeprofit = 0;
  926. //order_array[0].ticket = -1;
  927. //order_array[0].magicNo = 0;
  928. //order_array[0].accountBalance=0;
  929. //order_array[0].contractSize=0;
  930. //order_array[0].comments="";
  931. //order_array[0].closedPercentageOfTrade = 0;
  932. }
  933. //+------------------------------------------------------------------+
  934. //| |
  935. //+------------------------------------------------------------------+
  936. void deleteAllArray()
  937. {
  938. for(int i=0; i<orderCount; i++)
  939. {
  940. if(cod[i].ticket!=-1)
  941. {
  942. cod[i].ticket = -1;
  943. cod[i].magic = 0;
  944. }
  945. }
  946. }
  947. //+------------------------------------------------------------------+
  948. //| |
  949. //+------------------------------------------------------------------+
  950. bool checkorderpips(double openPrice,int type,string symbol)
  951. {
  952. double points = inpPips*10*SymbolInfoDouble(symbol,SYMBOL_POINT);
  953. if(type == 0)
  954. {
  955. if(SymbolInfoDouble(symbol,SYMBOL_ASK) - openPrice > points)
  956. {
  957. return true;
  958. }
  959. }
  960. else
  961. {
  962. if(openPrice - SymbolInfoDouble(symbol,SYMBOL_BID) > points)
  963. {
  964. return true;
  965. }
  966. }
  967. return false;
  968. }
  969. //+------------------------------------------------------------------+
  970. //| |
  971. //+------------------------------------------------------------------+
  972. bool isOrderThere(ulong ticket,int &index)
  973. {
  974. for(int i=0; i<ArraySize(mod1); i++)
  975. {
  976. if(ticket != -1)
  977. {
  978. if(mod1[i].ticket==ticket)
  979. {
  980. index=i;
  981. return true;
  982. }
  983. }
  984. }
  985. return false;
  986. }
  987. //+------------------------------------------------------------------+
  988. //| |
  989. //+------------------------------------------------------------------+
  990. bool addOrderMaster(ulong ticket, string calledBy)
  991. {
  992. for(int i=0; i<ArraySize(mod1); i++)
  993. {
  994. if(mod1[i].ticket==-1)
  995. {
  996. if(calledBy == "Market")
  997. {
  998. //ulong ticket = PositionGetTicket(orderTicket);
  999. if(PositionSelectByTicket(ticket))
  1000. {
  1001. //Symbol Updation
  1002. string symbol=PositionGetString(POSITION_SYMBOL);
  1003. if(suffix!="")
  1004. symbol = StringSubstr(symbol,0,StringFind(PositionGetString(POSITION_SYMBOL),suffix,0));
  1005. if(prefix!="")
  1006. StringReplace(symbol,prefix,"");
  1007. //Digits
  1008. double digits=getDoubleSymbolInfo(PositionGetString(POSITION_SYMBOL),"digits");
  1009. //time
  1010. datetime time = (datetime)(PositionGetInteger(POSITION_TIME)-gmtDifference);
  1011. mod1[i].opentime=time;
  1012. mod1[i].symbol=symbol;
  1013. mod1[i].ordertype=PositionGetInteger(POSITION_TYPE);
  1014. mod1[i].price=NormalizeDouble(PositionGetDouble(POSITION_PRICE_OPEN),(int)digits);
  1015. mod1[i].lots=NormalizeDouble(PositionGetDouble(POSITION_VOLUME),2);
  1016. mod1[i].stoploss=NormalizeDouble(PositionGetDouble(POSITION_SL),(int)digits);
  1017. mod1[i].takeprofit=NormalizeDouble(PositionGetDouble(POSITION_TP),(int)digits);
  1018. mod1[i].ticket=PositionGetInteger(POSITION_TICKET);
  1019. mod1[i].magic=(int)PositionGetInteger(POSITION_MAGIC);
  1020. mod1[i].comment=PositionGetString(POSITION_COMMENT);
  1021. Print("Ticket:",PositionGetInteger(POSITION_TICKET)," stored in index:",i);
  1022. return true;
  1023. }
  1024. }
  1025. if(calledBy == "Pending")
  1026. {
  1027. if(OrderSelect(ticket))
  1028. {
  1029. string symbol = OrderGetString(ORDER_SYMBOL);
  1030. if(suffix!="")
  1031. symbol = StringSubstr(symbol,0,StringFind(OrderGetString(ORDER_SYMBOL),suffix,0));
  1032. if(prefix!="")
  1033. StringReplace(symbol,prefix,"");
  1034. //Digits
  1035. double digits=getDoubleSymbolInfo(OrderGetString(ORDER_SYMBOL),"digits");
  1036. //time
  1037. datetime time = (datetime)(OrderGetInteger(ORDER_TIME_SETUP) - gmtDifference);
  1038. mod1[i].opentime=time;
  1039. mod1[i].symbol=symbol;
  1040. mod1[i].ordertype=OrderGetInteger(ORDER_TYPE);
  1041. mod1[i].price=NormalizeDouble(OrderGetDouble(ORDER_PRICE_OPEN),(int)digits);
  1042. mod1[i].lots=NormalizeDouble(OrderGetDouble(ORDER_VOLUME_CURRENT),2);
  1043. mod1[i].stoploss=NormalizeDouble(OrderGetDouble(ORDER_SL),(int)digits);
  1044. mod1[i].takeprofit=NormalizeDouble(OrderGetDouble(ORDER_TP),(int)digits);
  1045. mod1[i].ticket=OrderGetInteger(ORDER_TICKET);
  1046. mod1[i].magic=(int)OrderGetInteger(ORDER_MAGIC);
  1047. mod1[i].comment=OrderGetString(ORDER_COMMENT);
  1048. Print("Ticket: ",OrderGetInteger(ORDER_TICKET)," stored in index by pending order:",i);
  1049. return true;
  1050. }
  1051. }
  1052. }
  1053. }
  1054. return false;
  1055. }
  1056. //+------------------------------------------------------------------+
  1057. //| |
  1058. //+------------------------------------------------------------------+
  1059. void emptyStruct()
  1060. {
  1061. for(int i = 0 ; i < orderCount ; i++)
  1062. {
  1063. if(mod1[i].ticket != -1)
  1064. {
  1065. mod1[i].ticket=-1;
  1066. mod1[i].price=-1;
  1067. mod1[i].symbol="";
  1068. mod1[i].ordertype=-1;
  1069. mod1[i].lots=0;
  1070. mod1[i].stoploss=0;
  1071. mod1[i].takeprofit=0;
  1072. }
  1073. }
  1074. }
  1075. //+------------------------------------------------------------------+
  1076. //| |
  1077. //+------------------------------------------------------------------+
  1078. bool checkOrderUpdate()
  1079. {
  1080. bool updationRequired=false,currCheck=false;
  1081. for(int i = PositionsTotal()-1 ; i >= 0 ; i--)
  1082. {
  1083. ulong ticket = PositionGetTicket(i);
  1084. if(PositionSelectByTicket(ticket))
  1085. {
  1086. int orderIndex=-1;
  1087. bool alreadyAdded=isOrderThere(ticket, orderIndex);
  1088. if(!alreadyAdded)
  1089. {
  1090. currCheck=false;
  1091. currCheck=addOrderMaster(ticket, "Market");
  1092. if(!updationRequired)
  1093. updationRequired=currCheck;
  1094. }
  1095. else
  1096. {
  1097. if(orderIndex!=-1)
  1098. {
  1099. currCheck=false;
  1100. currCheck=IsOrderChanged(PositionGetInteger(POSITION_TICKET),orderIndex, "Market");
  1101. if(!updationRequired)
  1102. {
  1103. updationRequired=currCheck;
  1104. }
  1105. }
  1106. }
  1107. }
  1108. }
  1109. for(int i = OrdersTotal()-1 ; i >= 0 ; i--)
  1110. {
  1111. ulong ticket = OrderGetTicket(i);
  1112. if(OrderSelect(ticket))
  1113. {
  1114. if(OrderGetInteger(ORDER_TYPE) != ORDER_TYPE_BUY && OrderGetInteger(ORDER_TYPE) != ORDER_TYPE_SELL && OrderGetInteger(ORDER_TYPE) != ORDER_TYPE_CLOSE_BY)
  1115. {
  1116. int orderIndex=-1;
  1117. bool alreadyAdded=isOrderThere(ticket, orderIndex);
  1118. if(!alreadyAdded)
  1119. {
  1120. Print("Inside pending Adding to master order: ",ticket," type: ",OrderGetInteger(ORDER_TYPE)," ",OrdersTotal()," ",ORDER_TYPE_CLOSE_BY);
  1121. currCheck=false;
  1122. currCheck=addOrderMaster(ticket, "Pending");
  1123. if(!updationRequired)
  1124. updationRequired=currCheck;
  1125. }
  1126. else
  1127. {
  1128. if(orderIndex!=-1)
  1129. {
  1130. currCheck=false;
  1131. currCheck=IsOrderChanged(OrderGetInteger(ORDER_TICKET), orderIndex, "Pending");
  1132. if(!updationRequired)
  1133. {
  1134. updationRequired=currCheck;
  1135. }
  1136. }
  1137. }
  1138. }
  1139. }
  1140. }
  1141. for(int i=0; i<ArraySize(mod1); i++)
  1142. {
  1143. bool isPresent=false;
  1144. if(mod1[i].ticket !=-1)
  1145. {
  1146. for(int j = PositionsTotal()-1; j>=0; j--)
  1147. {
  1148. ulong ticket = PositionGetTicket(j);
  1149. if(PositionSelectByTicket(ticket))
  1150. {
  1151. if(ticket==mod1[i].ticket)
  1152. {
  1153. isPresent=true;
  1154. break;
  1155. }
  1156. }
  1157. }
  1158. // Pending Order
  1159. for(int j = OrdersTotal()-1; j>=0; j--)
  1160. {
  1161. ulong ticket = OrderGetTicket(j);
  1162. if(OrderSelect(ticket))
  1163. {
  1164. if(ticket==mod1[i].ticket)
  1165. {
  1166. isPresent=true;
  1167. break;
  1168. }
  1169. }
  1170. }
  1171. if(!isPresent)
  1172. {
  1173. Print("Ticket is closed so removed from struct: ",mod1[i].ticket);
  1174. mod1[i].ticket=-1;
  1175. mod1[i].price=-1;
  1176. mod1[i].symbol="";
  1177. mod1[i].ordertype=-1;
  1178. mod1[i].lots=0;
  1179. mod1[i].stoploss=0;
  1180. mod1[i].takeprofit=0;
  1181. currCheck=true;
  1182. //currCheck=clearStructIndex(mod1[i].ticket);
  1183. if(!updationRequired)
  1184. updationRequired=currCheck;
  1185. }
  1186. }
  1187. }
  1188. return updationRequired;
  1189. }
  1190. //+------------------------------------------------------------------+
  1191. //| |
  1192. //+------------------------------------------------------------------+
  1193. bool clearStructIndex(ulong ticket)
  1194. {
  1195. for(int index=0; index<ArraySize(mod1); index++)
  1196. {
  1197. if(mod1[index].ticket == ticket)
  1198. {
  1199. mod1[index].ticket=-1;
  1200. mod1[index].price=-1;
  1201. mod1[index].symbol="";
  1202. mod1[index].ordertype=-1;
  1203. mod1[index].lots=0;
  1204. mod1[index].stoploss=0;
  1205. mod1[index].takeprofit=0;
  1206. Print("Clear Structure Called. ");
  1207. return true;
  1208. }
  1209. }
  1210. return false;
  1211. }
  1212. //+------------------------------------------------------------------+
  1213. //| |
  1214. //+------------------------------------------------------------------+
  1215. bool IsOrderChanged(ulong orderTicket, int index, string calledBy)
  1216. {
  1217. if(mod1[index].ticket!=-1)
  1218. {
  1219. if(calledBy == "Market")
  1220. {
  1221. if(PositionSelectByTicket(orderTicket))
  1222. {
  1223. //Digits
  1224. double digits=getDoubleSymbolInfo(PositionGetString(POSITION_SYMBOL),"digits");
  1225. double tp=NormalizeDouble(PositionGetDouble(POSITION_TP), (int)digits),
  1226. sl=NormalizeDouble(PositionGetDouble(POSITION_SL),(int)digits),
  1227. lot=NormalizeDouble(PositionGetDouble(POSITION_VOLUME),2);
  1228. 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))
  1229. {
  1230. Print(" Inside IsOrderChanged() ",mod1[index].lots," lot: ",lot," calledBy: ",calledBy," mod1 ticket ",mod1[index].ticket," orderTicket: ",orderTicket);
  1231. // Time
  1232. datetime time = (datetime)(PositionGetInteger(POSITION_TIME) - gmtDifference);
  1233. mod1[index].opentime=time;
  1234. mod1[index].lots=lot;
  1235. mod1[index].stoploss=sl;
  1236. mod1[index].takeprofit=tp;
  1237. mod1[index].comment=PositionGetString(POSITION_COMMENT);
  1238. mod1[index].ordertype=PositionGetInteger(POSITION_TYPE);
  1239. mod1[index].price=PositionGetDouble(POSITION_PRICE_OPEN);
  1240. return true;
  1241. }
  1242. }
  1243. }
  1244. if(calledBy == "Pending")
  1245. {
  1246. if(OrderSelect(orderTicket))
  1247. {
  1248. double digits=getDoubleSymbolInfo(OrderGetString(ORDER_SYMBOL),"digits");
  1249. double tp=NormalizeDouble(OrderGetDouble(ORDER_TP), (int)digits),
  1250. sl=NormalizeDouble(OrderGetDouble(ORDER_SL),(int)digits),
  1251. lot=NormalizeDouble(OrderGetDouble(ORDER_VOLUME_CURRENT),2);
  1252. 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))
  1253. {
  1254. //time
  1255. datetime time = (datetime)(OrderGetDouble(ORDER_PRICE_OPEN) - gmtDifference);
  1256. mod1[index].opentime=time;
  1257. mod1[index].lots=lot;
  1258. mod1[index].stoploss=sl;
  1259. mod1[index].takeprofit=tp;
  1260. mod1[index].comment=OrderGetString(ORDER_COMMENT);
  1261. mod1[index].ordertype=OrderGetInteger(ORDER_TYPE);
  1262. mod1[index].price=OrderGetDouble(ORDER_PRICE_OPEN);
  1263. return true;
  1264. }
  1265. }
  1266. }
  1267. }
  1268. return false;
  1269. }
  1270. //+------------------------------------------------------------------+
  1271. //| |
  1272. //+------------------------------------------------------------------+
  1273. double getlot(double stop_loss)
  1274. {
  1275. Print("Tick Value: ",SymbolInfoDouble(Symbol(),SYMBOL_TRADE_TICK_VALUE));
  1276. Print("Tick Size: ",SymbolInfoDouble(Symbol(),SYMBOL_TRADE_TICK_SIZE));
  1277. double modeTickV=SymbolInfoDouble(Symbol(),SYMBOL_TRADE_TICK_VALUE)
  1278. ,modeTickS=SymbolInfoDouble(Symbol(),SYMBOL_TRADE_TICK_SIZE);
  1279. // Print("Pip value: ", NormalizeDouble(((SymbolInfoDouble(Symbol(),SYMBOL_TRADE_TICK_VALUE)/(SymbolInfoDouble(Symbol(),SYMBOL_TRADE_TICK_SIZE)/Point))*10),2));
  1280. double pipvalue = NormalizeDouble(((SymbolInfoDouble(Symbol(),SYMBOL_TRADE_TICK_VALUE)/(SymbolInfoDouble(Symbol(),SYMBOL_TRADE_TICK_SIZE)/Point()))*10),2);
  1281. // pipvalue=NormalizeDouble((modeTickV/modeTickS/Point()),)
  1282. // pipvalue=
  1283. pipvalue = pipvalue / 10;
  1284. double lotSize = lot_size;
  1285. if(lot_calculator==rsk) //calculating risk
  1286. {
  1287. double riskamount=(risk/100)*AccountInfoDouble(ACCOUNT_BALANCE);
  1288. double pipvalue_required=riskamount/stop_loss;
  1289. lotSize = pipvalue_required/pipvalue;
  1290. //sl=riskamount/pipValuelot
  1291. int roundDigit=0;
  1292. double step=SymbolInfoDouble(Symbol(),SYMBOL_VOLUME_STEP);
  1293. while(step<1)
  1294. {
  1295. roundDigit++;
  1296. step=step*10;
  1297. }
  1298. Print("Round Digits:",roundDigit);
  1299. lotSize = NormalizeDouble(lotSize,roundDigit);
  1300. //
  1301. }
  1302. Print("Lot Size: ",lotSize);
  1303. if(lotSize > SymbolInfoDouble(Symbol(),SYMBOL_VOLUME_MAX))
  1304. {
  1305. lotSize=SymbolInfoDouble(Symbol(),SYMBOL_VOLUME_MAX);
  1306. }
  1307. else
  1308. if(lotSize<SymbolInfoDouble(Symbol(),SYMBOL_VOLUME_MIN))
  1309. {
  1310. lotSize=SymbolInfoDouble(Symbol(),SYMBOL_VOLUME_MIN);
  1311. }
  1312. //---
  1313. return lotSize;
  1314. }
  1315. //+------------------------------------------------------------------+
  1316. //| |
  1317. //+------------------------------------------------------------------+
  1318. double getDoubleSymbolInfo(string symbol,string info)
  1319. {
  1320. long digits=8;
  1321. //Symbol without the suffix and prefix
  1322. string updatedSymbol=symbol;
  1323. if(suffix!="")
  1324. updatedSymbol = StringSubstr(updatedSymbol,0,StringFind(updatedSymbol,suffix,0));
  1325. if(prefix!="")
  1326. StringReplace(updatedSymbol,prefix,"");
  1327. //Digits calculation could be used in other calculations
  1328. digits = SymbolInfoInteger(symbol,SYMBOL_DIGITS);
  1329. if(digits==0)
  1330. {
  1331. digits=SymbolInfoInteger(updatedSymbol,SYMBOL_DIGITS);
  1332. if(digits==0)
  1333. digits=8;
  1334. }
  1335. if(info=="digits")
  1336. {
  1337. return (double)digits;
  1338. }
  1339. else
  1340. if(info=="point" || info=="points")
  1341. {
  1342. double points=SymbolInfoDouble(symbol, SYMBOL_POINT);
  1343. if(points==0)
  1344. {
  1345. points=SymbolInfoDouble(updatedSymbol,SYMBOL_POINT);
  1346. if(points==0)
  1347. points=0.00001;
  1348. }
  1349. return points;
  1350. }
  1351. else
  1352. if(info=="ask")
  1353. {
  1354. double ask = SymbolInfoDouble(symbol, SYMBOL_ASK);
  1355. if(ask==0)
  1356. {
  1357. ask=SymbolInfoDouble(updatedSymbol,SYMBOL_ASK);
  1358. }
  1359. return NormalizeDouble(ask,(int)digits);
  1360. }
  1361. else
  1362. if(info=="bid")
  1363. {
  1364. double bid=SymbolInfoDouble(symbol, SYMBOL_BID);
  1365. if(bid==0)
  1366. {
  1367. bid=SymbolInfoDouble(updatedSymbol,SYMBOL_BID);
  1368. }
  1369. return NormalizeDouble(bid,(int)digits);
  1370. }
  1371. else
  1372. if(info=="contract"||info=="contractSize")
  1373. {
  1374. double contract=SymbolInfoDouble(symbol,SYMBOL_TRADE_CONTRACT_SIZE);
  1375. if(contract==0)
  1376. {
  1377. contract=SymbolInfoDouble(updatedSymbol,SYMBOL_TRADE_CONTRACT_SIZE);
  1378. }
  1379. return contract;
  1380. }
  1381. return 0;
  1382. }
  1383. //+------------------------------------------------------------------+
  1384. //| |
  1385. //+------------------------------------------------------------------+
  1386. string getSymbol(string symbol)
  1387. {
  1388. if(mappingSymbol!="")
  1389. {
  1390. string symbollist[];
  1391. StringSplit(mappingSymbol,';',symbollist);
  1392. for(int i=0; i<ArraySize(symbollist); i++)
  1393. {
  1394. string symbolPairs[];
  1395. StringSplit(symbollist[i],',',symbolPairs);
  1396. if(ArraySize(symbolPairs)==2)
  1397. {
  1398. if(symbol==symbolPairs[0])
  1399. return symbolPairs[1];
  1400. }
  1401. }
  1402. }
  1403. else
  1404. {
  1405. return prefix+symbol+suffix;
  1406. }
  1407. return prefix+symbol+suffix;
  1408. }
  1409. //+------------------------------------------------------------------+
  1410. //| |
  1411. //+------------------------------------------------------------------+
  1412. void placeBuyTrade()
  1413. {
  1414. double buySL = 0, buyTp=0;
  1415. //openPrice = SymbolInfoDouble(Symbol(),SYMBOL_ASK);
  1416. double Ask = SymbolInfoDouble(Symbol(),SYMBOL_ASK);
  1417. double Bid = SymbolInfoDouble(Symbol(),SYMBOL_BID);
  1418. if(stoplossTrade != 0)
  1419. {
  1420. buySL = Ask - (stoplossTrade * 10 * Point());
  1421. }
  1422. if(takeprofitTrade != 0)
  1423. {
  1424. buyTp = Ask + (takeprofitTrade * 10 * Point());
  1425. }
  1426. double sl_distance = ((Ask - buySL) / Point());
  1427. if(trade.PositionOpen(Symbol(),ORDER_TYPE_BUY,getlot(sl_distance),Ask,buySL,buyTp,"Buy Trade Placed"))
  1428. {
  1429. Print("Buy Trade Placed: ",trade.ResultOrder());
  1430. }
  1431. else
  1432. {
  1433. Print("Error in placing Buy: "+Symbol()+" ",GetLastError());
  1434. }
  1435. }
  1436. //+------------------------------------------------------------------+
  1437. //| |
  1438. //+------------------------------------------------------------------+
  1439. void placeSellTrade()
  1440. {
  1441. double sellSL = 0, sellTp = 0;
  1442. //openPrice = SymbolInfoDouble(Symbol(),SYMBOL_BID);
  1443. double Ask = SymbolInfoDouble(Symbol(),SYMBOL_ASK);
  1444. double Bid = SymbolInfoDouble(Symbol(),SYMBOL_BID);
  1445. if(stoplossTrade != 0)
  1446. {
  1447. sellSL = Bid + (stoplossTrade * 10 * Point());
  1448. }
  1449. if(takeprofitTrade != 0)
  1450. {
  1451. sellTp = Bid - (takeprofitTrade * 10 * Point());
  1452. }
  1453. double sl_distance = ((sellSL - Bid) / Point());
  1454. if(trade.PositionOpen(Symbol(),ORDER_TYPE_SELL,getlot(sl_distance),Bid,sellSL,sellTp,"Sell Trade Placed"))
  1455. {
  1456. Print("Sell Trade PLaced: ",trade.ResultOrder());
  1457. }
  1458. else
  1459. {
  1460. Print("Error in placing Sell: "+Symbol()+" ",GetLastError());
  1461. }
  1462. }
  1463. //+------------------------------------------------------------------+
  1464. //| |
  1465. //+------------------------------------------------------------------+
  1466. void dashboard_data()
  1467. {
  1468. ExtDialog.m_label0.Text(" Master Trades Lots Calc: " + DoubleToString(totalLiveLots(), 2));
  1469. }
  1470. //+------------------------------------------------------------------+
  1471. //| |
  1472. //+------------------------------------------------------------------+
  1473. double totalLiveLots()
  1474. {
  1475. double total_lots = 0.0;
  1476. for(int i = 0; i < PositionsTotal(); i++)
  1477. {
  1478. ulong ticket = PositionGetTicket(i);
  1479. if(PositionSelectByTicket(ticket))
  1480. {
  1481. //if(PositionGetInteger(POSITION_MAGIC) == magic_no)
  1482. {
  1483. //if(PositionGetString(POSITION_SYMBOL) == Symbol())
  1484. {
  1485. int type = (int)PositionGetInteger(POSITION_TYPE);
  1486. if(type == POSITION_TYPE_BUY || type == POSITION_TYPE_SELL)
  1487. {
  1488. total_lots += PositionGetDouble(POSITION_VOLUME);
  1489. }
  1490. }
  1491. }
  1492. }
  1493. }
  1494. return total_lots;
  1495. }
  1496. //+------------------------------------------------------------------+
  1497. //| |
  1498. //+------------------------------------------------------------------+
  1499. void store_live_and_history_tickets()
  1500. {
  1501. // cutoff time = now - N days
  1502. datetime cutoff = (datetime)(TimeCurrent() - (datetime)daysOfTradesToAdd * 86400);
  1503. // --- history orders loop (closed / cancelled / executed orders) ---
  1504. // select history for the required period
  1505. if(HistorySelect(cutoff, TimeCurrent()))
  1506. {
  1507. int deals_count = (int)HistoryDealsTotal();
  1508. for(int j = deals_count - 1; j >= 0; --j)
  1509. {
  1510. ulong deal_ticket = HistoryDealGetTicket(j);
  1511. if(deal_ticket == 0)
  1512. continue;
  1513. // deal execution time
  1514. long dealTime = (long)HistoryDealGetInteger(deal_ticket, DEAL_TIME);
  1515. if((datetime)dealTime < cutoff)
  1516. continue; // older than cutoff, skip
  1517. // position id related to this deal (the stored "ticket" you track)
  1518. long position_id = (long)HistoryDealGetInteger(deal_ticket, DEAL_POSITION_ID);
  1519. if(position_id <= 0)
  1520. continue; // no position id to store
  1521. if(HistoryDealGetInteger(deal_ticket, DEAL_ENTRY) != DEAL_ENTRY_IN)
  1522. continue;
  1523. ulong ticket = position_id;
  1524. ulong magic = HistoryDealGetInteger(deal_ticket, DEAL_MAGIC);
  1525. double dealInLot = HistoryDealGetDouble(deal_ticket, DEAL_VOLUME);
  1526. double dealOutLot = dealOutLotsCheck(cutoff, position_id);
  1527. if(dealInLot == dealOutLot)
  1528. if(!history_ticket_present(ticket))
  1529. {
  1530. Print(" Position Id: ", position_id," Deal In Lot: ", dealInLot, " Deal Out Lot: ", dealOutLot);
  1531. add_history_ticket(ticket, magic);
  1532. }
  1533. }
  1534. }
  1535. else
  1536. {
  1537. // optional: failed to select history — you may handle/log if needed
  1538. // Print("HistorySelect failed. LastError=", GetLastError());
  1539. }
  1540. int ordersTotal=HistoryOrdersTotal();
  1541. ulong orderTicket=0;
  1542. for(int j=0; j<ordersTotal; j++)
  1543. {
  1544. orderTicket=HistoryOrderGetTicket(j);
  1545. long type=HistoryOrderGetInteger(orderTicket,ORDER_TYPE);
  1546. if(type==ORDER_TYPE_BUY_LIMIT || type==ORDER_TYPE_SELL_LIMIT || type==ORDER_TYPE_BUY_STOP
  1547. || type==ORDER_TYPE_SELL_STOP ||type==ORDER_TYPE_BUY_STOP_LIMIT || type==ORDER_TYPE_SELL_STOP_LIMIT)
  1548. {
  1549. long state=HistoryOrderGetInteger(orderTicket,ORDER_STATE);
  1550. if(state==ORDER_STATE_CANCELED || state==ORDER_STATE_REJECTED || state==ORDER_STATE_EXPIRED || state==ORDER_STATE_REQUEST_CANCEL)
  1551. {
  1552. datetime openTime = (datetime)HistoryOrderGetInteger(orderTicket, ORDER_TIME_SETUP);
  1553. if(openTime >= cutoff)
  1554. {
  1555. ulong magic = HistoryOrderGetInteger(orderTicket, ORDER_MAGIC);
  1556. if(!history_ticket_present(orderTicket))
  1557. {
  1558. add_history_ticket(orderTicket, magic);
  1559. }
  1560. }
  1561. }
  1562. }
  1563. }
  1564. }
  1565. //+------------------------------------------------------------------+
  1566. //| |
  1567. //+------------------------------------------------------------------+
  1568. double dealOutLotsCheck(datetime cutOffTimeIs, ulong positionId)
  1569. {
  1570. double sumOfLots = 0.0;
  1571. if(HistorySelect(cutOffTimeIs, LONG_MAX))
  1572. {
  1573. int totalDeals = HistoryDealsTotal();
  1574. for(int i = 0; i < totalDeals; i++)
  1575. {
  1576. ulong dealTicket = HistoryDealGetTicket(i);
  1577. ulong dealPositionID = (ulong)HistoryDealGetInteger(dealTicket, DEAL_POSITION_ID);
  1578. if(HistoryDealGetInteger(dealTicket, DEAL_ENTRY) == DEAL_ENTRY_OUT
  1579. && dealPositionID == positionId)
  1580. {
  1581. sumOfLots += HistoryDealGetDouble(dealTicket, DEAL_VOLUME);
  1582. }
  1583. }
  1584. }
  1585. return sumOfLots;
  1586. }
  1587. //+------------------------------------------------------------------+
  1588. //| |
  1589. //+------------------------------------------------------------------+
  1590. bool history_ticket_present(ulong ticket)
  1591. {
  1592. for(int i = 0 ; i < MaxOrders ; i++)
  1593. {
  1594. if(historyTradeStore[i].ticket == ticket)
  1595. return true;
  1596. }
  1597. return false;
  1598. }
  1599. //+------------------------------------------------------------------+
  1600. //| |
  1601. //+------------------------------------------------------------------+
  1602. void add_history_ticket(ulong ticket, ulong magicIs)
  1603. {
  1604. for(int i = 0; i < MaxOrders; i++)
  1605. {
  1606. if(historyTradeStore[i].ticket == -1)
  1607. {
  1608. historyTradeStore[i].ticket = ticket;
  1609. historyTradeStore[i].magic = magicIs;
  1610. Print("Ticket Added to History Structure. Ticket: ", ticket, " Magic: ", magicIs);
  1611. save_history_store("add_history_ticket()");
  1612. return;
  1613. }
  1614. }
  1615. Print("historyTradeStore full, cannot add ticket: ", ticket);
  1616. }
  1617. //+------------------------------------------------------------------+
  1618. //| |
  1619. //+------------------------------------------------------------------+
  1620. void clear_history_store()
  1621. {
  1622. for(int i = 0; i < MaxOrders; i++)
  1623. {
  1624. historyTradeStore[i].ticket = -1;
  1625. historyTradeStore[i].magic = 0;
  1626. }
  1627. Print("History store cleaned");
  1628. }
  1629. //+------------------------------------------------------------------+
  1630. //| |
  1631. //+------------------------------------------------------------------+
  1632. void save_history_store(string calledBy)
  1633. {
  1634. string file_nameIs = "history_trades.csv";
  1635. int fileHandle = FileOpen(file_nameIs, FILE_WRITE | FILE_CSV | FILE_COMMON);
  1636. if(fileHandle != INVALID_HANDLE)
  1637. {
  1638. for(int i = 0; i < MaxOrders; i++)
  1639. {
  1640. if(historyTradeStore[i].ticket != -1)
  1641. {
  1642. string data_to_store = IntegerToString(historyTradeStore[i].ticket) + "," + IntegerToString(historyTradeStore[i].magic) + "\r\n";
  1643. FileWriteString(fileHandle, data_to_store);
  1644. }
  1645. }
  1646. //Print("save_history_store() called by: ", calledBy, " Time: ", TimeToString(TimeCurrent(), TIME_DATE | TIME_SECONDS));
  1647. FileClose(fileHandle);
  1648. }
  1649. else
  1650. {
  1651. Print("Error opening file save_history_store(): ", GetLastError());
  1652. }
  1653. }
  1654. //+------------------------------------------------------------------+
  1655. //| |
  1656. //+------------------------------------------------------------------+
  1657. void remove_old_tickets_from_store()
  1658. {
  1659. datetime cutoff = TimeCurrent() - (datetime)daysOfTradesToAdd * 86400;
  1660. // Print("remove_old_tickets_from_store: cutoff = ", TimeToString(cutoff, TIME_DATE|TIME_SECONDS));
  1661. // Prepare history selection ranges once (for deals we limit by cutoff; for orders we select full history)
  1662. for(int i = 0; i < MaxOrders; i++)
  1663. {
  1664. ulong tk = historyTradeStore[i].ticket;
  1665. if(tk == -1) // empty slot
  1666. continue;
  1667. bool found = false;
  1668. ulong pos_ticket = (ulong)tk;
  1669. if(HistorySelect(cutoff, TimeCurrent()))
  1670. {
  1671. int deals_count = (int)HistoryDealsTotal();
  1672. for(int j = deals_count - 1; j >= 0; --j)
  1673. {
  1674. ulong deal_ticket = HistoryDealGetTicket(j);
  1675. if(deal_ticket == 0)
  1676. continue;
  1677. // deal execution time
  1678. long dealTime = (long)HistoryDealGetInteger(deal_ticket, DEAL_TIME);
  1679. if((datetime)dealTime < cutoff)
  1680. continue; // older than cutoff, skip
  1681. if(HistoryDealGetInteger(deal_ticket, DEAL_ENTRY) != DEAL_ENTRY_IN)
  1682. continue;
  1683. // position id related to this deal (the stored "ticket" you track)
  1684. long position_id = (long)HistoryDealGetInteger(deal_ticket, DEAL_POSITION_ID);
  1685. if(position_id <= 0)
  1686. continue; // no position id to store
  1687. double dealInLot = HistoryDealGetDouble(deal_ticket, DEAL_VOLUME);
  1688. double dealOutLot = dealOutLotsCheck(cutoff, position_id);
  1689. if(dealInLot == dealOutLot)
  1690. if(position_id == pos_ticket)
  1691. {
  1692. found = true;
  1693. break;
  1694. }
  1695. }
  1696. }
  1697. else
  1698. {
  1699. // optional: failed to select history — you may handle/log if needed
  1700. // Print("HistorySelect failed. LastError=", GetLastError());
  1701. }
  1702. if(!found)
  1703. {
  1704. int ordersTotal = HistoryOrdersTotal();
  1705. for(int j = 0; j < ordersTotal; j++)
  1706. {
  1707. ulong orderTicket = HistoryOrderGetTicket(j);
  1708. if(orderTicket == 0)
  1709. continue;
  1710. long type = HistoryOrderGetInteger(orderTicket, ORDER_TYPE);
  1711. if(type != ORDER_TYPE_BUY_LIMIT && type != ORDER_TYPE_SELL_LIMIT &&
  1712. type != ORDER_TYPE_BUY_STOP && type != ORDER_TYPE_SELL_STOP)
  1713. continue;
  1714. datetime openTime = (datetime)HistoryOrderGetInteger(orderTicket, ORDER_TIME_SETUP);
  1715. long state=HistoryOrderGetInteger(orderTicket,ORDER_STATE);
  1716. if(state==ORDER_STATE_CANCELED || state==ORDER_STATE_REJECTED || state==ORDER_STATE_EXPIRED || state==ORDER_STATE_REQUEST_CANCEL)
  1717. {
  1718. if(orderTicket == pos_ticket)
  1719. {
  1720. if(openTime > cutoff)
  1721. {
  1722. found = true;
  1723. break;
  1724. }
  1725. }
  1726. }
  1727. }
  1728. }
  1729. // 3) Final action: remove if not found
  1730. if(!found)
  1731. {
  1732. Print("Ticket not found, removing from store: ", tk, " index=", i);
  1733. historyTradeStore[i].ticket = -1;
  1734. historyTradeStore[i].magic = 0;
  1735. // (optionally clear other fields if your struct has them)
  1736. }
  1737. } // for i
  1738. }
  1739. //+------------------------------------------------------------------+
  1740. //+------------------------------------------------------------------+
  1741. //| |
  1742. //+------------------------------------------------------------------+
  1743. //================================================ Dashboard ====================================
  1744. //+------------------------------------------------------------------+
  1745. //| |
  1746. //+------------------------------------------------------------------+
  1747. class CControlsDialog : public CAppDialog
  1748. {
  1749. public:
  1750. CLabel m_label0;
  1751. CButton m_button;
  1752. CButton m_button1;
  1753. CControlsDialog(void);
  1754. ~CControlsDialog(void);
  1755. //--- create
  1756. virtual bool Create(const long chart,const string name,const int subwin,const int x1,const int y1,const int x2,const int y2);
  1757. virtual bool OnEvent(const int id, const long &lparam,const double &dparam, const string &sparam);
  1758. bool CreateLabel0(void);
  1759. bool CreateButton(void);
  1760. bool CreateButton1(void);
  1761. void OnClickButton(void);
  1762. void OnClickButton1(void);
  1763. bool CreatePanel(void);
  1764. };
  1765. //+------------------------------------------------------------------+
  1766. //| |
  1767. //+------------------------------------------------------------------+
  1768. EVENT_MAP_BEGIN(CControlsDialog)
  1769. ON_EVENT(ON_CLICK,m_button,OnClickButton)
  1770. ON_EVENT(ON_CLICK,m_button1,OnClickButton1)
  1771. EVENT_MAP_END(CAppDialog)
  1772. //+------------------------------------------------------------------+
  1773. //| Constructor |
  1774. //+------------------------------------------------------------------+
  1775. CControlsDialog::CControlsDialog(void)
  1776. {
  1777. }
  1778. //+------------------------------------------------------------------+
  1779. //| Destructor |
  1780. //+------------------------------------------------------------------+
  1781. CControlsDialog::~CControlsDialog(void)
  1782. {
  1783. }
  1784. //+------------------------------------------------------------------+
  1785. //| Create |
  1786. //+------------------------------------------------------------------+
  1787. bool CControlsDialog::Create(const long chart,const string name,const int subwin,const int x1,const int y1,const int x2,const int y2)
  1788. {
  1789. if(!CAppDialog::Create(chart,name,subwin,20,20,dashWidth,dashHeight))
  1790. return(false);
  1791. //--- create dependent controls
  1792. if(!CreatePanel())
  1793. return(false);
  1794. if(!CreateLabel0())
  1795. return(false);
  1796. if(!CreateButton())
  1797. return(false);
  1798. if(!CreateButton1())
  1799. return(false);
  1800. //--- succeed
  1801. return(true);
  1802. }
  1803. //+------------------------------------------------------------------+
  1804. //| |
  1805. //+------------------------------------------------------------------+
  1806. bool CControlsDialog::CreateLabel0(void) //Trend Info
  1807. {
  1808. //--- coordinates
  1809. int x1 = (dashWidth/2) - 235;
  1810. int y1 = yAxisGlobal + 15;
  1811. int x2 = 0;
  1812. int y2 = 0;
  1813. //--- create
  1814. if(!m_label0.Create(m_chart_id,m_name+"Label0",m_subwin,x1,y1,x2,y2))
  1815. return(false);
  1816. if(!m_label0.Text(" Master Trades Lots Calc: 0.00"))
  1817. return(false);
  1818. if(!m_label0.Color(clrBlack))
  1819. return(false);
  1820. if(!m_label0.Font("Calibri"))
  1821. return(false);
  1822. if(!m_label0.FontSize(FontSize))
  1823. return(false);
  1824. if(!Add(m_label0))
  1825. return(false);
  1826. //--- succeed
  1827. return(true);
  1828. }
  1829. //+------------------------------------------------------------------+
  1830. //| |
  1831. //+------------------------------------------------------------------+
  1832. bool CControlsDialog::CreateButton(void)
  1833. {
  1834. //--- coordinates
  1835. // Buy
  1836. int x1 = (dashWidth/2) + 14;
  1837. int y1 = yAxisGlobal + 10;
  1838. int x2 = x1 + 70;
  1839. int y2 = y1 + 30;
  1840. //--- create
  1841. if(!m_button.Create(m_chart_id,"button",m_subwin,x1,y1,x2,y2))
  1842. return(false);
  1843. if(!m_button.ColorBackground(clrSlateGray))
  1844. return(false);
  1845. if(!m_button.Text("Sell"))
  1846. return(false);
  1847. if(!m_button.FontSize(FontSize))
  1848. return(false);
  1849. if(!m_button.ColorBackground(clrRed))
  1850. return(false);
  1851. if(!m_button.Font("Calibri Bold"))
  1852. return(false);
  1853. if(!m_button.Color(clrWhiteSmoke))
  1854. return(false);
  1855. if(!m_button.ColorBorder(clrRed))
  1856. return(false);
  1857. if(!Add(m_button))
  1858. return(false);
  1859. m_button.Locking(true);
  1860. m_button.BringToTop();
  1861. //--- succeed
  1862. return(true);
  1863. }
  1864. //+------------------------------------------------------------------+
  1865. //| |
  1866. //+------------------------------------------------------------------+
  1867. bool CControlsDialog::CreateButton1(void)
  1868. {
  1869. //--- coordinates
  1870. // Sell
  1871. int x1 = (dashWidth/2) + 100;
  1872. int y1 = yAxisGlobal + 10;
  1873. int x2 = x1 + 70;
  1874. int y2 = y1 + 30;
  1875. //--- create
  1876. if(!m_button1.Create(m_chart_id,"button1",m_subwin,x1,y1,x2,y2))
  1877. return(false);
  1878. if(!m_button1.ColorBackground(clrBlue))
  1879. return(false);
  1880. if(!m_button1.Text("Buy"))
  1881. return(false);
  1882. if(!m_button1.FontSize(FontSize))
  1883. return(false);
  1884. if(!m_button1.Font("Calibri Bold"))
  1885. return(false);
  1886. if(!m_button1.Color(clrWhiteSmoke))
  1887. return(false);
  1888. if(!m_button1.ColorBorder(clrBlack))
  1889. return(false);
  1890. if(!Add(m_button1))
  1891. return(false);
  1892. m_button1.Locking(true);
  1893. m_button1.BringToTop();
  1894. //--- succeed
  1895. return(true);
  1896. }
  1897. //+------------------------------------------------------------------+
  1898. //| |
  1899. //+------------------------------------------------------------------+
  1900. void CControlsDialog::OnClickButton(void)
  1901. {
  1902. if(m_button.Pressed())
  1903. {
  1904. Print(" Clicked on Button");
  1905. m_button.Pressed(false);
  1906. placeSellTrade();
  1907. }
  1908. }
  1909. //+------------------------------------------------------------------+
  1910. //| |
  1911. //+------------------------------------------------------------------+
  1912. void CControlsDialog::OnClickButton1(void)
  1913. {
  1914. if(m_button1.Pressed())
  1915. {
  1916. Print(" Clicked on Button 1");
  1917. m_button1.Pressed(false);
  1918. placeBuyTrade();
  1919. }
  1920. }
  1921. //+------------------------------------------------------------------+
  1922. //| |
  1923. //+------------------------------------------------------------------+
  1924. bool CControlsDialog::CreatePanel(void)
  1925. {
  1926. //--- coordinates
  1927. int x1=0;
  1928. int y1=0;
  1929. int x2=dashWidth;
  1930. int y2=dashHeight;
  1931. //--- create
  1932. if(!backgroundPanel.Create(0,ExtDialog.Name()+"backPanel",m_subwin,x1,y1,x2,y2))
  1933. return(false);
  1934. if(!backgroundPanel.ColorBackground(clrWhiteSmoke))
  1935. return(false);
  1936. if(!backgroundPanel.ColorBorder(00128))
  1937. return(false);
  1938. if(!ExtDialog.Add(backgroundPanel))
  1939. return(false);
  1940. ExtDialog.Minimized(false);
  1941. backgroundPanel.Alignment(WND_ALIGN_CLIENT,0,0,0,0);
  1942. //--- succeed
  1943. return(true);
  1944. }
  1945. CControlsDialog ExtDialog;
  1946. CPanel backgroundPanel;
  1947. //+------------------------------------------------------------------+
  1948. //| |
  1949. //+------------------------------------------------------------------+
  1950. //+------------------------------------------------------------------+