暂无描述

localHedgingMasterCopierMt5.mq5 160KB

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