Keine Beschreibung

localHedgingMasterCopierMt5.mq5 154KB

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