Brak opisu

localHedgingMasterCopierMt5.mq5 151KB

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