Keine Beschreibung

localHedgingMasterCopierMt5.mq5 162KB

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