Keine Beschreibung

localHedgingMasterCopierMt5.mq5 162KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077
  1. //+------------------------------------------------------------------+
  2. //| localHedgingMasterCopierMt5.mq5 |
  3. //| Copyright 2025, MQL Development |
  4. //| https://www.mqldevelopment.com/ |
  5. //+------------------------------------------------------------------+
  6. #property copyright "Copyright 2025, MQL Development"
  7. #property link "https://www.mqldevelopment.com/"
  8. #property version "1.00"
  9. #include <Trade\Trade.mqh>
  10. CTrade trade;
  11. #define orderCount 2000
  12. #define count1 50
  13. #define testCounter 50
  14. #define MaxOrders 20000
  15. #define daysOfTradesToAdd 20
  16. #property description "Control Panels and Dialogs. Demonstration class CLabel"
  17. #include <Controls\Dialog.mqh>
  18. #include <Controls\Label.mqh>
  19. #include <Controls\Button.mqh>
  20. #include <Controls\RadioButton.mqh>
  21. #include <Controls\RadioGroup.mqh>
  22. #include <Controls\CheckBox.mqh>
  23. #include <Controls\ComboBox.mqh>
  24. //+------------------------------------------------------------------+
  25. //| Expert initialization function |
  26. //+------------------------------------------------------------------+
  27. struct historyTradesClientSide
  28. {
  29. ulong ticket;
  30. ulong magic;
  31. historyTradesClientSide()
  32. {
  33. ticket = -1;
  34. magic = 0;
  35. }
  36. };
  37. historyTradesClientSide historyTradeStore[MaxOrders];
  38. struct masterOrder
  39. {
  40. datetime opentime;
  41. string symbol;
  42. ulong ordertype;
  43. double price;
  44. double lots;
  45. double stoploss;
  46. double takeprofit;
  47. ulong ticket;
  48. ulong magic;
  49. double accountBalance;
  50. int contractSize;
  51. string comment;
  52. masterOrder()
  53. {
  54. ticket=-1;
  55. price=-1;
  56. symbol=Symbol();
  57. ordertype=-1;
  58. lots=0;
  59. stoploss=0;
  60. takeprofit=0;
  61. }
  62. };
  63. masterOrder mod1[orderCount];
  64. struct order
  65. {
  66. ulong ticket;
  67. double price;
  68. datetime opentime;
  69. string symbol;
  70. int ordertype;
  71. double lots;
  72. double stoploss;
  73. double takeprofit;
  74. double accountBalance;
  75. int contractSize;
  76. string comments;
  77. ulong magicNo;
  78. double closedPercentageOfTrade;
  79. order()
  80. {
  81. ticket =-1;
  82. closedPercentageOfTrade = 0;
  83. }
  84. };
  85. struct clientOrder
  86. {
  87. ulong ticket;
  88. double price;
  89. datetime opentime;
  90. string symbol;
  91. int ordertype;
  92. double lots;
  93. double stoploss;
  94. double takeprofit;
  95. ulong magic;
  96. string comments;
  97. double masterLot;
  98. clientOrder()
  99. {
  100. ticket=-1;
  101. price=-1;
  102. symbol=Symbol();
  103. ordertype=-1;
  104. lots=0;
  105. masterLot=0;
  106. stoploss=0;
  107. takeprofit=0;
  108. magic=-1;
  109. comments="";
  110. }
  111. };
  112. clientOrder cod[orderCount];
  113. enum operation_mode
  114. {
  115. Master, //Master
  116. Slave, //Slave
  117. };
  118. enum lotcalculator
  119. {
  120. fix, //Fixed Lot Size
  121. rsk, //Risk Percentage
  122. };
  123. sinput string string_0 = "<><><><><><> General SETTINGS <><><><><><>"; //__
  124. input int magic_no = 333; // Magic no
  125. input string suffix = ""; // Suffix
  126. input string prefix = ""; // Prefix
  127. input double takeprofitTrade = 10; // Fixed Take Profit in Pips
  128. input double stoplossTrade = 10; // Fixed Stop Loss in Pips
  129. input 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(totalLiveLots(), 2));
  1404. }
  1405. //+------------------------------------------------------------------+
  1406. //| |
  1407. //+------------------------------------------------------------------+
  1408. double totalLiveLots()
  1409. {
  1410. double total_lots = 0.0;
  1411. for(int i = 0; i < PositionsTotal(); i++)
  1412. {
  1413. ulong ticket = PositionGetTicket(i);
  1414. if(PositionSelectByTicket(ticket))
  1415. {
  1416. //if(PositionGetInteger(POSITION_MAGIC) == magic_no)
  1417. {
  1418. //if(PositionGetString(POSITION_SYMBOL) == Symbol())
  1419. {
  1420. int type = (int)PositionGetInteger(POSITION_TYPE);
  1421. if(type == POSITION_TYPE_BUY || type == POSITION_TYPE_SELL)
  1422. {
  1423. total_lots += PositionGetDouble(POSITION_VOLUME);
  1424. }
  1425. }
  1426. }
  1427. }
  1428. }
  1429. return total_lots;
  1430. }
  1431. //+------------------------------------------------------------------+
  1432. //| |
  1433. //+------------------------------------------------------------------+
  1434. void store_live_and_history_tickets()
  1435. {
  1436. // cutoff time = now - N days
  1437. datetime cutoff = (datetime)(TimeCurrent() - (datetime)daysOfTradesToAdd * 86400);
  1438. // --- history orders loop (closed / cancelled / executed orders) ---
  1439. // select history for the required period
  1440. if(HistorySelect(cutoff, LONG_MAX))
  1441. {
  1442. int deals_count = (int)HistoryDealsTotal();
  1443. for(int j = deals_count - 1; j >= 0; --j)
  1444. {
  1445. ulong deal_ticket = HistoryDealGetTicket(j);
  1446. if(deal_ticket == 0)
  1447. continue;
  1448. // deal execution time
  1449. long dealTime = (long)HistoryDealGetInteger(deal_ticket, DEAL_TIME);
  1450. if((datetime)dealTime < cutoff)
  1451. continue; // older than cutoff, skip
  1452. // position id related to this deal (the stored "ticket" you track)
  1453. long position_id = (long)HistoryDealGetInteger(deal_ticket, DEAL_POSITION_ID);
  1454. if(position_id <= 0)
  1455. continue; // no position id to store
  1456. if(HistoryDealGetInteger(deal_ticket, DEAL_ENTRY) != DEAL_ENTRY_IN)
  1457. continue;
  1458. ulong ticket = position_id;
  1459. ulong magic = HistoryDealGetInteger(deal_ticket, DEAL_MAGIC);
  1460. double dealInLot = HistoryDealGetDouble(deal_ticket, DEAL_VOLUME);
  1461. double dealOutLot = dealOutLotsCheck(cutoff, position_id);
  1462. if(dealInLot == dealOutLot)
  1463. if(!history_ticket_present(ticket))
  1464. {
  1465. Print(" Position Id: ", position_id," Deal In Lot: ", dealInLot, " Deal Out Lot: ", dealOutLot);
  1466. add_history_ticket(ticket, magic);
  1467. }
  1468. HistorySelect(cutoff, LONG_MAX);
  1469. }
  1470. }
  1471. else
  1472. {
  1473. // optional: failed to select history — you may handle/log if needed
  1474. // Print("HistorySelect failed. LastError=", GetLastError());
  1475. }
  1476. int ordersTotal=HistoryOrdersTotal();
  1477. ulong orderTicket=0;
  1478. for(int j=0; j<ordersTotal; j++)
  1479. {
  1480. orderTicket=HistoryOrderGetTicket(j);
  1481. long type=HistoryOrderGetInteger(orderTicket,ORDER_TYPE);
  1482. if(type==ORDER_TYPE_BUY_LIMIT || type==ORDER_TYPE_SELL_LIMIT || type==ORDER_TYPE_BUY_STOP
  1483. || type==ORDER_TYPE_SELL_STOP ||type==ORDER_TYPE_BUY_STOP_LIMIT || type==ORDER_TYPE_SELL_STOP_LIMIT)
  1484. {
  1485. long state=HistoryOrderGetInteger(orderTicket,ORDER_STATE);
  1486. if(state==ORDER_STATE_CANCELED || state==ORDER_STATE_REJECTED || state==ORDER_STATE_EXPIRED || state==ORDER_STATE_REQUEST_CANCEL)
  1487. {
  1488. datetime openTime = (datetime)HistoryOrderGetInteger(orderTicket, ORDER_TIME_SETUP);
  1489. if(openTime >= cutoff)
  1490. {
  1491. ulong magic = HistoryOrderGetInteger(orderTicket, ORDER_MAGIC);
  1492. if(!history_ticket_present(orderTicket))
  1493. {
  1494. add_history_ticket(orderTicket, magic);
  1495. }
  1496. }
  1497. }
  1498. }
  1499. }
  1500. }
  1501. //+------------------------------------------------------------------+
  1502. //| |
  1503. //+------------------------------------------------------------------+
  1504. double dealOutLotsCheck(datetime cutOffTimeIs, ulong positionId)
  1505. {
  1506. double sumOfLots = 0.0;
  1507. if(HistorySelect(cutOffTimeIs, LONG_MAX))
  1508. {
  1509. int totalDeals = HistoryDealsTotal();
  1510. for(int i = 0; i < totalDeals; i++)
  1511. {
  1512. ulong dealTicket = HistoryDealGetTicket(i);
  1513. ulong dealPositionID = (ulong)HistoryDealGetInteger(dealTicket, DEAL_POSITION_ID);
  1514. if((HistoryDealGetInteger(dealTicket, DEAL_ENTRY) == DEAL_ENTRY_OUT || HistoryDealGetInteger(dealTicket, DEAL_ENTRY) == DEAL_ENTRY_OUT_BY)
  1515. && dealPositionID == positionId)
  1516. {
  1517. sumOfLots += HistoryDealGetDouble(dealTicket, DEAL_VOLUME);
  1518. }
  1519. }
  1520. }
  1521. // if(HistorySelectByPosition(positionId))
  1522. // {
  1523. // int totalDeals = HistoryDealsTotal();
  1524. // for(int i = 0; i < totalDeals; i++)
  1525. // {
  1526. // ulong dealTicket = HistoryDealGetTicket(i);
  1527. // ulong dealPositionID = (ulong)HistoryDealGetInteger(dealTicket, DEAL_POSITION_ID);
  1528. //
  1529. // //Print(" inside : ",positionId," i: ",i," lot: ",HistoryDealGetDouble(dealTicket, DEAL_VOLUME)," dealPositionID: ",dealPositionID," positionId: ",positionId," DEAL Type: ",HistoryDealGetInteger(dealTicket, DEAL_ENTRY));
  1530. // if((HistoryDealGetInteger(dealTicket, DEAL_ENTRY) == DEAL_ENTRY_OUT || HistoryDealGetInteger(dealTicket, DEAL_ENTRY) == DEAL_ENTRY_OUT_BY)
  1531. // && dealPositionID == positionId)
  1532. // {
  1533. // // Print(" inside 2");
  1534. // sumOfLots += HistoryDealGetDouble(dealTicket, DEAL_VOLUME);
  1535. // }
  1536. // }
  1537. // }
  1538. return sumOfLots;
  1539. }
  1540. //+------------------------------------------------------------------+
  1541. //| |
  1542. //+------------------------------------------------------------------+
  1543. bool history_ticket_present(ulong ticket)
  1544. {
  1545. for(int i = 0 ; i < MaxOrders ; i++)
  1546. {
  1547. if(historyTradeStore[i].ticket == ticket)
  1548. return true;
  1549. }
  1550. return false;
  1551. }
  1552. //+------------------------------------------------------------------+
  1553. //| |
  1554. //+------------------------------------------------------------------+
  1555. void add_history_ticket(ulong ticket, ulong magicIs)
  1556. {
  1557. for(int i = 0; i < MaxOrders; i++)
  1558. {
  1559. if(historyTradeStore[i].ticket == -1)
  1560. {
  1561. historyTradeStore[i].ticket = ticket;
  1562. historyTradeStore[i].magic = magicIs;
  1563. Print("Ticket Added to History Structure. Ticket: ", ticket, " Magic: ", magicIs);
  1564. if(!save_history_store("add_history_ticket()"))
  1565. {
  1566. historyTradeStore[i].ticket = -1;
  1567. historyTradeStore[i].magic = 0;
  1568. Print("Ticket Remove from History Structure because file not opened Ticket: ", ticket, " Magic: ", magicIs);
  1569. }
  1570. return;
  1571. }
  1572. }
  1573. Print("historyTradeStore full, cannot add ticket: ", ticket);
  1574. }
  1575. //+------------------------------------------------------------------+
  1576. //| |
  1577. //+------------------------------------------------------------------+
  1578. void clear_history_store()
  1579. {
  1580. for(int i = 0; i < MaxOrders; i++)
  1581. {
  1582. historyTradeStore[i].ticket = -1;
  1583. historyTradeStore[i].magic = 0;
  1584. }
  1585. Print("History store cleaned");
  1586. }
  1587. //+------------------------------------------------------------------+
  1588. //| |
  1589. //+------------------------------------------------------------------+
  1590. bool save_history_store(string calledBy)
  1591. {
  1592. string file_nameIs = "history_trades.csv";
  1593. int fileHandle = FileOpen(file_nameIs, FILE_WRITE | FILE_CSV | FILE_COMMON);
  1594. if(fileHandle != INVALID_HANDLE)
  1595. {
  1596. for(int i = 0; i < MaxOrders; i++)
  1597. {
  1598. if(historyTradeStore[i].ticket != -1)
  1599. {
  1600. string data_to_store = IntegerToString(historyTradeStore[i].ticket) + "," + IntegerToString(historyTradeStore[i].magic) + "\r\n";
  1601. FileWriteString(fileHandle, data_to_store);
  1602. }
  1603. }
  1604. //Print("save_history_store() called by: ", calledBy, " Time: ", TimeToString(TimeCurrent(), TIME_DATE | TIME_SECONDS));
  1605. FileClose(fileHandle);
  1606. return true;
  1607. }
  1608. else
  1609. {
  1610. Print("Error opening file save_history_store(): ", GetLastError());
  1611. }
  1612. return false;
  1613. }
  1614. //+------------------------------------------------------------------+
  1615. //| |
  1616. //+------------------------------------------------------------------+
  1617. void remove_old_tickets_from_store()
  1618. {
  1619. datetime cutoff = TimeCurrent() - (datetime)daysOfTradesToAdd * 86400;
  1620. // Print("remove_old_tickets_from_store: cutoff = ", TimeToString(cutoff, TIME_DATE|TIME_SECONDS));
  1621. // Prepare history selection ranges once (for deals we limit by cutoff; for orders we select full history)
  1622. for(int i = 0; i < MaxOrders; i++)
  1623. {
  1624. ulong tk = historyTradeStore[i].ticket;
  1625. if(tk == -1) // empty slot
  1626. continue;
  1627. bool found = false;
  1628. ulong pos_ticket = (ulong)tk;
  1629. if(HistorySelect(cutoff, TimeCurrent()))
  1630. {
  1631. int deals_count = (int)HistoryDealsTotal();
  1632. for(int j = deals_count - 1; j >= 0; --j)
  1633. {
  1634. ulong deal_ticket = HistoryDealGetTicket(j);
  1635. if(deal_ticket == 0)
  1636. continue;
  1637. // deal execution time
  1638. long dealTime = (long)HistoryDealGetInteger(deal_ticket, DEAL_TIME);
  1639. if((datetime)dealTime < cutoff)
  1640. continue; // older than cutoff, skip
  1641. if(HistoryDealGetInteger(deal_ticket, DEAL_ENTRY) != DEAL_ENTRY_IN)
  1642. continue;
  1643. // position id related to this deal (the stored "ticket" you track)
  1644. long position_id = (long)HistoryDealGetInteger(deal_ticket, DEAL_POSITION_ID);
  1645. if(position_id <= 0)
  1646. continue; // no position id to store
  1647. double dealInLot = HistoryDealGetDouble(deal_ticket, DEAL_VOLUME);
  1648. double dealOutLot = dealOutLotsCheck(cutoff, position_id);
  1649. if(dealInLot == dealOutLot)
  1650. if(position_id == pos_ticket)
  1651. {
  1652. found = true;
  1653. break;
  1654. }
  1655. }
  1656. HistorySelect(cutoff, TimeCurrent());
  1657. }
  1658. else
  1659. {
  1660. // optional: failed to select history — you may handle/log if needed
  1661. // Print("HistorySelect failed. LastError=", GetLastError());
  1662. }
  1663. if(!found)
  1664. {
  1665. int ordersTotal = HistoryOrdersTotal();
  1666. for(int j = 0; j < ordersTotal; j++)
  1667. {
  1668. ulong orderTicket = HistoryOrderGetTicket(j);
  1669. if(orderTicket == 0)
  1670. continue;
  1671. long type = HistoryOrderGetInteger(orderTicket, ORDER_TYPE);
  1672. if(type != ORDER_TYPE_BUY_LIMIT && type != ORDER_TYPE_SELL_LIMIT &&
  1673. type != ORDER_TYPE_BUY_STOP && type != ORDER_TYPE_SELL_STOP)
  1674. continue;
  1675. datetime openTime = (datetime)HistoryOrderGetInteger(orderTicket, ORDER_TIME_SETUP);
  1676. long state=HistoryOrderGetInteger(orderTicket,ORDER_STATE);
  1677. if(state==ORDER_STATE_CANCELED || state==ORDER_STATE_REJECTED || state==ORDER_STATE_EXPIRED || state==ORDER_STATE_REQUEST_CANCEL)
  1678. {
  1679. if(orderTicket == pos_ticket)
  1680. {
  1681. if(openTime > cutoff)
  1682. {
  1683. found = true;
  1684. break;
  1685. }
  1686. }
  1687. }
  1688. }
  1689. }
  1690. // 3) Final action: remove if not found
  1691. if(!found)
  1692. {
  1693. Print("Ticket not found, removing from store: ", tk, " index=", i);
  1694. historyTradeStore[i].ticket = -1;
  1695. historyTradeStore[i].magic = 0;
  1696. // (optionally clear other fields if your struct has them)
  1697. }
  1698. } // for i
  1699. }
  1700. //+------------------------------------------------------------------+
  1701. //+------------------------------------------------------------------+
  1702. //| |
  1703. //+------------------------------------------------------------------+
  1704. //================================================ Dashboard ====================================
  1705. //+------------------------------------------------------------------+
  1706. //| |
  1707. //+------------------------------------------------------------------+
  1708. class CControlsDialog : public CAppDialog
  1709. {
  1710. public:
  1711. CLabel m_label0;
  1712. CButton m_button;
  1713. CButton m_button1;
  1714. CControlsDialog(void);
  1715. ~CControlsDialog(void);
  1716. //--- create
  1717. virtual bool Create(const long chart,const string name,const int subwin,const int x1,const int y1,const int x2,const int y2);
  1718. virtual bool OnEvent(const int id, const long &lparam,const double &dparam, const string &sparam);
  1719. bool CreateLabel0(void);
  1720. bool CreateButton(void);
  1721. bool CreateButton1(void);
  1722. void OnClickButton(void);
  1723. void OnClickButton1(void);
  1724. bool CreatePanel(void);
  1725. };
  1726. //+------------------------------------------------------------------+
  1727. //| |
  1728. //+------------------------------------------------------------------+
  1729. EVENT_MAP_BEGIN(CControlsDialog)
  1730. //ON_EVENT(ON_CLICK,m_button,OnClickButton)
  1731. //ON_EVENT(ON_CLICK,m_button1,OnClickButton1)
  1732. EVENT_MAP_END(CAppDialog)
  1733. //+------------------------------------------------------------------+
  1734. //| Constructor |
  1735. //+------------------------------------------------------------------+
  1736. CControlsDialog::CControlsDialog(void)
  1737. {
  1738. }
  1739. //+------------------------------------------------------------------+
  1740. //| Destructor |
  1741. //+------------------------------------------------------------------+
  1742. CControlsDialog::~CControlsDialog(void)
  1743. {
  1744. }
  1745. //+------------------------------------------------------------------+
  1746. //| Create |
  1747. //+------------------------------------------------------------------+
  1748. bool CControlsDialog::Create(const long chart,const string name,const int subwin,const int x1,const int y1,const int x2,const int y2)
  1749. {
  1750. if(!CAppDialog::Create(chart,name,subwin,20,20,dashWidth,dashHeight))
  1751. return(false);
  1752. //--- create dependent controls
  1753. if(!CreatePanel())
  1754. return(false);
  1755. if(!CreateLabel0())
  1756. return(false);
  1757. if(!CreateButton())
  1758. return(false);
  1759. if(!CreateButton1())
  1760. return(false);
  1761. //--- succeed
  1762. return(true);
  1763. }
  1764. //+------------------------------------------------------------------+
  1765. //| |
  1766. //+------------------------------------------------------------------+
  1767. bool CControlsDialog::CreateLabel0(void) //Trend Info
  1768. {
  1769. //--- coordinates
  1770. int x1 = 20;
  1771. int y1 = yAxisGlobal + 15;
  1772. int x2 = 0;
  1773. int y2 = 0;
  1774. //--- create
  1775. if(!m_label0.Create(m_chart_id,m_name+"Label0",m_subwin,x1,y1,x2,y2))
  1776. return(false);
  1777. if(!m_label0.Text(" Master Trades Lots Calc: 0.00"))
  1778. return(false);
  1779. if(!m_label0.Color(clrBlack))
  1780. return(false);
  1781. if(!m_label0.Font("Calibri"))
  1782. return(false);
  1783. if(!m_label0.FontSize(FontSize))
  1784. return(false);
  1785. if(!Add(m_label0))
  1786. return(false);
  1787. //--- succeed
  1788. return(true);
  1789. }
  1790. //+------------------------------------------------------------------+
  1791. //| |
  1792. //+------------------------------------------------------------------+
  1793. bool CControlsDialog::CreateButton(void)
  1794. {
  1795. //--- coordinates
  1796. // Buy
  1797. int x1 = (dashWidth/2) + 14;
  1798. int y1 = yAxisGlobal + 10;
  1799. int x2 = x1 + 70;
  1800. int y2 = y1 + 30;
  1801. //--- create
  1802. if(!m_button.Create(m_chart_id,"button",m_subwin,x1,y1,x2,y2))
  1803. return(false);
  1804. if(!m_button.ColorBackground(clrSlateGray))
  1805. return(false);
  1806. if(!m_button.Text("Sell"))
  1807. return(false);
  1808. if(!m_button.FontSize(FontSize))
  1809. return(false);
  1810. if(!m_button.ColorBackground(clrRed))
  1811. return(false);
  1812. if(!m_button.Font("Calibri Bold"))
  1813. return(false);
  1814. if(!m_button.Color(clrWhiteSmoke))
  1815. return(false);
  1816. if(!m_button.ColorBorder(clrRed))
  1817. return(false);
  1818. if(!Add(m_button))
  1819. return(false);
  1820. m_button.Locking(true);
  1821. m_button.BringToTop();
  1822. //--- succeed
  1823. return(true);
  1824. }
  1825. //+------------------------------------------------------------------+
  1826. //| |
  1827. //+------------------------------------------------------------------+
  1828. bool CControlsDialog::CreateButton1(void)
  1829. {
  1830. //--- coordinates
  1831. // Sell
  1832. int x1 = (dashWidth/2) + 100;
  1833. int y1 = yAxisGlobal + 10;
  1834. int x2 = x1 + 70;
  1835. int y2 = y1 + 30;
  1836. //--- create
  1837. if(!m_button1.Create(m_chart_id,"button1",m_subwin,x1,y1,x2,y2))
  1838. return(false);
  1839. if(!m_button1.ColorBackground(clrBlue))
  1840. return(false);
  1841. if(!m_button1.Text("Buy"))
  1842. return(false);
  1843. if(!m_button1.FontSize(FontSize))
  1844. return(false);
  1845. if(!m_button1.Font("Calibri Bold"))
  1846. return(false);
  1847. if(!m_button1.Color(clrWhiteSmoke))
  1848. return(false);
  1849. if(!m_button1.ColorBorder(clrBlack))
  1850. return(false);
  1851. if(!Add(m_button1))
  1852. return(false);
  1853. m_button1.Locking(true);
  1854. m_button1.BringToTop();
  1855. //--- succeed
  1856. return(true);
  1857. }
  1858. //+------------------------------------------------------------------+
  1859. //| |
  1860. //+------------------------------------------------------------------+
  1861. void CControlsDialog::OnClickButton(void)
  1862. {
  1863. if(m_button.Pressed())
  1864. {
  1865. Print(" Clicked on Button");
  1866. placeSellTrade();
  1867. m_button.Pressed(false);
  1868. }
  1869. }
  1870. //+------------------------------------------------------------------+
  1871. //| |
  1872. //+------------------------------------------------------------------+
  1873. void CControlsDialog::OnClickButton1(void)
  1874. {
  1875. if(m_button1.Pressed())
  1876. {
  1877. Print(" Clicked on Button 1");
  1878. placeBuyTrade();
  1879. m_button1.Pressed(false);
  1880. }
  1881. }
  1882. //+------------------------------------------------------------------+
  1883. //| |
  1884. //+------------------------------------------------------------------+
  1885. bool CControlsDialog::CreatePanel(void)
  1886. {
  1887. //--- coordinates
  1888. int x1=0;
  1889. int y1=0;
  1890. int x2=dashWidth;
  1891. int y2=dashHeight;
  1892. //--- create
  1893. if(!backgroundPanel.Create(0,ExtDialog.Name()+"backPanel",m_subwin,x1,y1,x2,y2))
  1894. return(false);
  1895. if(!backgroundPanel.ColorBackground(clrWhiteSmoke))
  1896. return(false);
  1897. if(!backgroundPanel.ColorBorder(00128))
  1898. return(false);
  1899. if(!ExtDialog.Add(backgroundPanel))
  1900. return(false);
  1901. ExtDialog.Minimized(false);
  1902. backgroundPanel.Alignment(WND_ALIGN_CLIENT,0,0,0,0);
  1903. //--- succeed
  1904. return(true);
  1905. }
  1906. CControlsDialog ExtDialog;
  1907. CPanel backgroundPanel;
  1908. //+------------------------------------------------------------------+
  1909. //| |
  1910. //+------------------------------------------------------------------+
  1911. //+------------------------------------------------------------------+