説明なし

localHedgingMasterCopierMt5.mq5 165KB

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