Nenhuma descrição

localHedgingMasterCopierMt5.mq5 163KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085
  1. //+------------------------------------------------------------------+
  2. //| localHedgingMasterCopierMt5.mq5 |
  3. //| Copyright 2025, MQL Development |
  4. //| https://www.mqldevelopment.com/ |
  5. //+------------------------------------------------------------------+
  6. #property copyright "Copyright 2025, MQL Development"
  7. #property link "https://www.mqldevelopment.com/"
  8. #property version "1.00"
  9. #include <Trade\Trade.mqh>
  10. CTrade trade;
  11. #define orderCount 2000
  12. #define count1 50
  13. #define testCounter 50
  14. #define MaxOrders 20000
  15. #define daysOfTradesToAdd 20
  16. #property description "Control Panels and Dialogs. Demonstration class CLabel"
  17. #include <Controls\Dialog.mqh>
  18. #include <Controls\Label.mqh>
  19. #include <Controls\Button.mqh>
  20. #include <Controls\RadioButton.mqh>
  21. #include <Controls\RadioGroup.mqh>
  22. #include <Controls\CheckBox.mqh>
  23. #include <Controls\ComboBox.mqh>
  24. //+------------------------------------------------------------------+
  25. //| Expert initialization function |
  26. //+------------------------------------------------------------------+
  27. struct historyTradesClientSide
  28. {
  29. ulong ticket;
  30. ulong magic;
  31. historyTradesClientSide()
  32. {
  33. ticket = -1;
  34. magic = 0;
  35. }
  36. };
  37. historyTradesClientSide historyTradeStore[MaxOrders];
  38. struct masterOrder
  39. {
  40. datetime opentime;
  41. string symbol;
  42. ulong ordertype;
  43. double price;
  44. double lots;
  45. double stoploss;
  46. double takeprofit;
  47. ulong ticket;
  48. ulong magic;
  49. double accountBalance;
  50. int contractSize;
  51. string comment;
  52. masterOrder()
  53. {
  54. ticket=-1;
  55. price=-1;
  56. symbol=Symbol();
  57. ordertype=-1;
  58. lots=0;
  59. stoploss=0;
  60. takeprofit=0;
  61. }
  62. };
  63. masterOrder mod1[orderCount];
  64. struct order
  65. {
  66. ulong ticket;
  67. double price;
  68. datetime opentime;
  69. string symbol;
  70. int ordertype;
  71. double lots;
  72. double stoploss;
  73. double takeprofit;
  74. double accountBalance;
  75. int contractSize;
  76. string comments;
  77. ulong magicNo;
  78. double closedPercentageOfTrade;
  79. order()
  80. {
  81. ticket =-1;
  82. closedPercentageOfTrade = 0;
  83. }
  84. };
  85. struct clientOrder
  86. {
  87. ulong ticket;
  88. double price;
  89. datetime opentime;
  90. string symbol;
  91. int ordertype;
  92. double lots;
  93. double stoploss;
  94. double takeprofit;
  95. ulong magic;
  96. string comments;
  97. double masterLot;
  98. clientOrder()
  99. {
  100. ticket=-1;
  101. price=-1;
  102. symbol=Symbol();
  103. ordertype=-1;
  104. lots=0;
  105. masterLot=0;
  106. stoploss=0;
  107. takeprofit=0;
  108. magic=-1;
  109. comments="";
  110. }
  111. };
  112. clientOrder cod[orderCount];
  113. enum operation_mode
  114. {
  115. Master, //Master
  116. Slave, //Slave
  117. };
  118. enum lotcalculator
  119. {
  120. fix, //Fixed Lot Size
  121. rsk, //Risk Percentage
  122. };
  123. sinput string string_0 = "<><><><><><> General SETTINGS <><><><><><>"; //__
  124. input int magic_no = 333; // Magic no
  125. input string suffix = ""; // Suffix
  126. input string prefix = ""; // Prefix
  127. input double takeprofitTrade = 10; // Fixed Take Profit in Pips
  128. input double stoplossTrade = 10; // Fixed Stop Loss in Pips
  129. input double inpPips = 0.2; // Pips To Start Copy
  130. input bool useMinimumLot = false; // Use Minimum Lot Threshold
  131. input double minimumLot = 0.01; // Minimum Lot
  132. input bool useMaximumLot = false; // Use Maximum Lot Threshold
  133. input double maximumLot = 0.01; // Maximum Lot
  134. input string string_0_3 = "<><><><><><> Lot Management<><><><><><>"; //__
  135. input double lot_size = 0.1; // Lot Size
  136. input lotcalculator lot_calculator = fix; // Lot Size Calculator
  137. input double risk = 0.1; // Risk in Percentage %
  138. input string dashboardSettings = "<><><><><><> Dashboard Settings<><><><><><>";
  139. input int DashHeight = 115; // Enter Height of Dashboard
  140. input int DashWidth = 490; // Enter Width of Dashboard
  141. input int FontSize = 10; // Text Font Size
  142. // Global Variables
  143. int filehandle;
  144. int gmtDifference = 0;
  145. bool doReversal = true; // Reverse Trades
  146. bool auth = false;
  147. datetime last_check_expiry;
  148. ENUM_TIMEFRAMES check_expiry_timeframe = PERIOD_H1;
  149. int orderTotal=0;
  150. bool fileLastEmpty=false;
  151. bool fileHandlerIssue=false;
  152. int yAxisGlobal = 5;
  153. int dashHeight; // Height of Dashboard
  154. int dashWidth; // Width of Dashboard
  155. long accountNumber = AccountInfoInteger(ACCOUNT_LOGIN);
  156. operation_mode mode1=Master; //Working Mode
  157. order order_array[];
  158. long lastFileSize=0;
  159. datetime lastModified=0;
  160. string symbolExclude = ""; // Symbol to Exclude
  161. string mappingSymbol = ""; // Mapping Pairs Inp,Out;Inp,Out
  162. bool autoStart = true;
  163. int OnInit()
  164. {
  165. //---
  166. trade.SetExpertMagicNumber(magic_no);
  167. trade.SetDeviationInPoints(10);
  168. trade.SetTypeFilling(ORDER_FILLING_IOC);
  169. trade.LogLevel(LOG_LEVEL_ALL);
  170. trade.SetAsyncMode(false);
  171. if(!ObjectFind(0,"mode") || ObjectGetString(0,"mode",OBJPROP_TEXT,0)!=EnumToString(mode1)+" Account")
  172. {
  173. ObjectDelete(0,"mode");
  174. ObjectCreate(0,"mode",OBJ_LABEL,0,0,0);
  175. ObjectSetInteger(0,"mode",OBJPROP_XDISTANCE,10);
  176. ObjectSetInteger(0,"mode",OBJPROP_YDISTANCE,25);
  177. ObjectSetInteger(0,"mode",OBJPROP_CORNER,CORNER_RIGHT_UPPER);
  178. ObjectSetInteger(0,"mode",OBJPROP_ANCHOR,ANCHOR_RIGHT_UPPER);
  179. ObjectSetInteger(0,"mode",OBJPROP_COLOR,clrLightBlue);
  180. ObjectSetString(0,"mode",OBJPROP_TEXT,EnumToString(mode1)+" Account");
  181. ObjectSetInteger(0,"mode",OBJPROP_FONTSIZE,14);
  182. }
  183. dashHeight = DashHeight;
  184. dashWidth = DashWidth;
  185. double width = double(ChartGetInteger(0,CHART_WIDTH_IN_PIXELS));
  186. double height = double(ChartGetInteger(0,CHART_HEIGHT_IN_PIXELS));
  187. double minHeight = (110/height) * (height);
  188. double minWidth = (480.0/width) * (width);
  189. Print(" Minimum Required minHeight = ",minHeight," minWidth ",minWidth);
  190. if(dashWidth < minWidth)
  191. {
  192. dashWidth = (int)minWidth;
  193. Print(" Dashboard width is updated because user input is less than required width ");
  194. }
  195. if(dashHeight < minHeight)
  196. {
  197. dashHeight = (int)minHeight;
  198. Print(" Dashboard Height is updated because user input is less than required Height ");
  199. }
  200. if(!ExtDialog.Create(0,"Local Hedge Master",10,10,40,dashWidth,dashHeight)) // the panel position
  201. return(INIT_FAILED);
  202. ExtDialog.Run();
  203. gmtDifference = (int)TimeCurrent() - (int)TimeGMT();
  204. Print("GMT Difference(sec): ",gmtDifference);
  205. EventSetMillisecondTimer(1000);
  206. //---
  207. return(INIT_SUCCEEDED);
  208. }
  209. //+------------------------------------------------------------------+
  210. //| Expert deinitialization function |
  211. //+------------------------------------------------------------------+
  212. void OnDeinit(const int reason)
  213. {
  214. //---
  215. ExtDialog.Destroy(reason);
  216. EventKillTimer();
  217. }
  218. //+------------------------------------------------------------------+
  219. //| Expert tick function |
  220. //+------------------------------------------------------------------+
  221. void OnTimer()
  222. {
  223. gmtDifference = (int)TimeCurrent() - (int)TimeGMT();
  224. 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 checkorderpips(double openPrice,int type,string symbol)
  895. {
  896. double points = inpPips*10*SymbolInfoDouble(symbol,SYMBOL_POINT);
  897. if(type == 0)
  898. {
  899. if(SymbolInfoDouble(symbol,SYMBOL_ASK) - openPrice > points)
  900. {
  901. return true;
  902. }
  903. }
  904. else
  905. {
  906. if(openPrice - SymbolInfoDouble(symbol,SYMBOL_BID) > points)
  907. {
  908. return true;
  909. }
  910. }
  911. return false;
  912. }
  913. //+------------------------------------------------------------------+
  914. //| |
  915. //+------------------------------------------------------------------+
  916. bool isOrderThere(ulong ticket,int &index)
  917. {
  918. for(int i=0; i<ArraySize(mod1); i++)
  919. {
  920. if(ticket != -1)
  921. {
  922. if(mod1[i].ticket==ticket)
  923. {
  924. index=i;
  925. return true;
  926. }
  927. }
  928. }
  929. return false;
  930. }
  931. //+------------------------------------------------------------------+
  932. //| |
  933. //+------------------------------------------------------------------+
  934. bool addOrderMaster(ulong ticket, string calledBy)
  935. {
  936. for(int i=0; i<ArraySize(mod1); i++)
  937. {
  938. if(mod1[i].ticket==-1)
  939. {
  940. if(calledBy == "Market")
  941. {
  942. //ulong ticket = PositionGetTicket(orderTicket);
  943. if(PositionSelectByTicket(ticket))
  944. {
  945. //Symbol Updation
  946. string symbol=PositionGetString(POSITION_SYMBOL);
  947. if(suffix!="")
  948. symbol = StringSubstr(symbol,0,StringFind(PositionGetString(POSITION_SYMBOL),suffix,0));
  949. if(prefix!="")
  950. StringReplace(symbol,prefix,"");
  951. //Digits
  952. double digits=getDoubleSymbolInfo(PositionGetString(POSITION_SYMBOL),"digits");
  953. //time
  954. datetime time = (datetime)(PositionGetInteger(POSITION_TIME)-gmtDifference);
  955. mod1[i].opentime=time;
  956. mod1[i].symbol=symbol;
  957. mod1[i].ordertype=PositionGetInteger(POSITION_TYPE);
  958. mod1[i].price=NormalizeDouble(PositionGetDouble(POSITION_PRICE_OPEN),(int)digits);
  959. mod1[i].lots=NormalizeDouble(PositionGetDouble(POSITION_VOLUME),2);
  960. mod1[i].stoploss=NormalizeDouble(PositionGetDouble(POSITION_SL),(int)digits);
  961. mod1[i].takeprofit=NormalizeDouble(PositionGetDouble(POSITION_TP),(int)digits);
  962. mod1[i].ticket=PositionGetInteger(POSITION_TICKET);
  963. mod1[i].magic=(int)PositionGetInteger(POSITION_MAGIC);
  964. mod1[i].comment=PositionGetString(POSITION_COMMENT);
  965. Print("Ticket:",PositionGetInteger(POSITION_TICKET)," stored in index:",i);
  966. return true;
  967. }
  968. }
  969. if(calledBy == "Pending")
  970. {
  971. if(OrderSelect(ticket))
  972. {
  973. string symbol = OrderGetString(ORDER_SYMBOL);
  974. if(suffix!="")
  975. symbol = StringSubstr(symbol,0,StringFind(OrderGetString(ORDER_SYMBOL),suffix,0));
  976. if(prefix!="")
  977. StringReplace(symbol,prefix,"");
  978. //Digits
  979. double digits=getDoubleSymbolInfo(OrderGetString(ORDER_SYMBOL),"digits");
  980. //time
  981. datetime time = (datetime)(OrderGetInteger(ORDER_TIME_SETUP) - gmtDifference);
  982. mod1[i].opentime=time;
  983. mod1[i].symbol=symbol;
  984. mod1[i].ordertype=OrderGetInteger(ORDER_TYPE);
  985. mod1[i].price=NormalizeDouble(OrderGetDouble(ORDER_PRICE_OPEN),(int)digits);
  986. mod1[i].lots=NormalizeDouble(OrderGetDouble(ORDER_VOLUME_CURRENT),2);
  987. mod1[i].stoploss=NormalizeDouble(OrderGetDouble(ORDER_SL),(int)digits);
  988. mod1[i].takeprofit=NormalizeDouble(OrderGetDouble(ORDER_TP),(int)digits);
  989. mod1[i].ticket=OrderGetInteger(ORDER_TICKET);
  990. mod1[i].magic=(int)OrderGetInteger(ORDER_MAGIC);
  991. mod1[i].comment=OrderGetString(ORDER_COMMENT);
  992. Print("Ticket: ",OrderGetInteger(ORDER_TICKET)," stored in index by pending order:",i);
  993. return true;
  994. }
  995. }
  996. }
  997. }
  998. return false;
  999. }
  1000. //+------------------------------------------------------------------+
  1001. //| |
  1002. //+------------------------------------------------------------------+
  1003. void emptyStruct()
  1004. {
  1005. for(int i = 0 ; i < orderCount ; i++)
  1006. {
  1007. if(mod1[i].ticket != -1)
  1008. {
  1009. mod1[i].ticket=-1;
  1010. mod1[i].price=-1;
  1011. mod1[i].symbol="";
  1012. mod1[i].ordertype=-1;
  1013. mod1[i].lots=0;
  1014. mod1[i].stoploss=0;
  1015. mod1[i].takeprofit=0;
  1016. }
  1017. }
  1018. }
  1019. //+------------------------------------------------------------------+
  1020. //| |
  1021. //+------------------------------------------------------------------+
  1022. bool checkOrderUpdate()
  1023. {
  1024. bool updationRequired=false,currCheck=false;
  1025. for(int i = PositionsTotal()-1 ; i >= 0 ; i--)
  1026. {
  1027. ulong ticket = PositionGetTicket(i);
  1028. if(PositionSelectByTicket(ticket))
  1029. {
  1030. int orderIndex=-1;
  1031. bool alreadyAdded=isOrderThere(ticket, orderIndex);
  1032. if(!alreadyAdded)
  1033. {
  1034. currCheck=false;
  1035. currCheck=addOrderMaster(ticket, "Market");
  1036. if(!updationRequired)
  1037. updationRequired=currCheck;
  1038. }
  1039. else
  1040. {
  1041. if(orderIndex!=-1)
  1042. {
  1043. currCheck=false;
  1044. currCheck=IsOrderChanged(PositionGetInteger(POSITION_TICKET),orderIndex, "Market");
  1045. if(!updationRequired)
  1046. {
  1047. updationRequired=currCheck;
  1048. }
  1049. }
  1050. }
  1051. }
  1052. }
  1053. for(int i = OrdersTotal()-1 ; i >= 0 ; i--)
  1054. {
  1055. ulong ticket = OrderGetTicket(i);
  1056. if(OrderSelect(ticket))
  1057. {
  1058. if(OrderGetInteger(ORDER_TYPE) != ORDER_TYPE_BUY && OrderGetInteger(ORDER_TYPE) != ORDER_TYPE_SELL && OrderGetInteger(ORDER_TYPE) != ORDER_TYPE_CLOSE_BY)
  1059. {
  1060. int orderIndex=-1;
  1061. bool alreadyAdded=isOrderThere(ticket, orderIndex);
  1062. if(!alreadyAdded)
  1063. {
  1064. Print("Inside pending Adding to master order: ",ticket," type: ",OrderGetInteger(ORDER_TYPE)," ",OrdersTotal()," ",ORDER_TYPE_CLOSE_BY);
  1065. currCheck=false;
  1066. currCheck=addOrderMaster(ticket, "Pending");
  1067. if(!updationRequired)
  1068. updationRequired=currCheck;
  1069. }
  1070. else
  1071. {
  1072. if(orderIndex!=-1)
  1073. {
  1074. currCheck=false;
  1075. currCheck=IsOrderChanged(OrderGetInteger(ORDER_TICKET), orderIndex, "Pending");
  1076. if(!updationRequired)
  1077. {
  1078. updationRequired=currCheck;
  1079. }
  1080. }
  1081. }
  1082. }
  1083. }
  1084. }
  1085. for(int i=0; i<ArraySize(mod1); i++)
  1086. {
  1087. bool isPresent=false;
  1088. if(mod1[i].ticket !=-1)
  1089. {
  1090. for(int j = PositionsTotal()-1; j>=0; j--)
  1091. {
  1092. ulong ticket = PositionGetTicket(j);
  1093. if(PositionSelectByTicket(ticket))
  1094. {
  1095. if(ticket==mod1[i].ticket)
  1096. {
  1097. isPresent=true;
  1098. break;
  1099. }
  1100. }
  1101. }
  1102. // Pending Order
  1103. for(int j = OrdersTotal()-1; j>=0; j--)
  1104. {
  1105. ulong ticket = OrderGetTicket(j);
  1106. if(OrderSelect(ticket))
  1107. {
  1108. if(ticket==mod1[i].ticket)
  1109. {
  1110. isPresent=true;
  1111. break;
  1112. }
  1113. }
  1114. }
  1115. if(!isPresent)
  1116. {
  1117. Print("Ticket is closed so removed from struct: ",mod1[i].ticket);
  1118. mod1[i].ticket=-1;
  1119. mod1[i].price=-1;
  1120. mod1[i].symbol="";
  1121. mod1[i].ordertype=-1;
  1122. mod1[i].lots=0;
  1123. mod1[i].stoploss=0;
  1124. mod1[i].takeprofit=0;
  1125. currCheck=true;
  1126. //currCheck=clearStructIndex(mod1[i].ticket);
  1127. if(!updationRequired)
  1128. updationRequired=currCheck;
  1129. }
  1130. }
  1131. }
  1132. return updationRequired;
  1133. }
  1134. //+------------------------------------------------------------------+
  1135. //| |
  1136. //+------------------------------------------------------------------+
  1137. bool clearStructIndex(ulong ticket)
  1138. {
  1139. for(int index=0; index<ArraySize(mod1); index++)
  1140. {
  1141. if(mod1[index].ticket == ticket)
  1142. {
  1143. mod1[index].ticket=-1;
  1144. mod1[index].price=-1;
  1145. mod1[index].symbol="";
  1146. mod1[index].ordertype=-1;
  1147. mod1[index].lots=0;
  1148. mod1[index].stoploss=0;
  1149. mod1[index].takeprofit=0;
  1150. Print("Clear Structure Called. ");
  1151. return true;
  1152. }
  1153. }
  1154. return false;
  1155. }
  1156. //+------------------------------------------------------------------+
  1157. //| |
  1158. //+------------------------------------------------------------------+
  1159. bool IsOrderChanged(ulong orderTicket, int index, string calledBy)
  1160. {
  1161. if(mod1[index].ticket!=-1)
  1162. {
  1163. if(calledBy == "Market")
  1164. {
  1165. if(PositionSelectByTicket(orderTicket))
  1166. {
  1167. //Digits
  1168. double digits=getDoubleSymbolInfo(PositionGetString(POSITION_SYMBOL),"digits");
  1169. double tp=NormalizeDouble(PositionGetDouble(POSITION_TP), (int)digits),
  1170. sl=NormalizeDouble(PositionGetDouble(POSITION_SL),(int)digits),
  1171. lot=NormalizeDouble(PositionGetDouble(POSITION_VOLUME),2);
  1172. if(mod1[index].takeprofit!=tp || mod1[index].stoploss != sl || mod1[index].lots!=lot || mod1[index].ordertype!=PositionGetInteger(POSITION_TYPE) || mod1[index].price != PositionGetDouble(POSITION_PRICE_OPEN))
  1173. {
  1174. Print(" Inside IsOrderChanged() ",mod1[index].lots," lot: ",lot," calledBy: ",calledBy," mod1 ticket ",mod1[index].ticket," orderTicket: ",orderTicket);
  1175. // Time
  1176. datetime time = (datetime)(PositionGetInteger(POSITION_TIME) - gmtDifference);
  1177. mod1[index].opentime=time;
  1178. mod1[index].lots=lot;
  1179. mod1[index].stoploss=sl;
  1180. mod1[index].takeprofit=tp;
  1181. mod1[index].comment=PositionGetString(POSITION_COMMENT);
  1182. mod1[index].ordertype=PositionGetInteger(POSITION_TYPE);
  1183. mod1[index].price=PositionGetDouble(POSITION_PRICE_OPEN);
  1184. return true;
  1185. }
  1186. }
  1187. }
  1188. if(calledBy == "Pending")
  1189. {
  1190. if(OrderSelect(orderTicket))
  1191. {
  1192. double digits=getDoubleSymbolInfo(OrderGetString(ORDER_SYMBOL),"digits");
  1193. double tp=NormalizeDouble(OrderGetDouble(ORDER_TP), (int)digits),
  1194. sl=NormalizeDouble(OrderGetDouble(ORDER_SL),(int)digits),
  1195. lot=NormalizeDouble(OrderGetDouble(ORDER_VOLUME_CURRENT),2);
  1196. if(mod1[index].takeprofit!=tp || mod1[index].stoploss != sl || mod1[index].lots!=lot || mod1[index].ordertype!=OrderGetInteger(ORDER_TYPE) || mod1[index].price != OrderGetDouble(ORDER_PRICE_OPEN))
  1197. {
  1198. //time
  1199. datetime time = (datetime)(OrderGetDouble(ORDER_PRICE_OPEN) - gmtDifference);
  1200. mod1[index].opentime=time;
  1201. mod1[index].lots=lot;
  1202. mod1[index].stoploss=sl;
  1203. mod1[index].takeprofit=tp;
  1204. mod1[index].comment=OrderGetString(ORDER_COMMENT);
  1205. mod1[index].ordertype=OrderGetInteger(ORDER_TYPE);
  1206. mod1[index].price=OrderGetDouble(ORDER_PRICE_OPEN);
  1207. return true;
  1208. }
  1209. }
  1210. }
  1211. }
  1212. return false;
  1213. }
  1214. //+------------------------------------------------------------------+
  1215. //| |
  1216. //+------------------------------------------------------------------+
  1217. double getlot(double stop_loss)
  1218. {
  1219. Print("Tick Value: ",SymbolInfoDouble(Symbol(),SYMBOL_TRADE_TICK_VALUE));
  1220. Print("Tick Size: ",SymbolInfoDouble(Symbol(),SYMBOL_TRADE_TICK_SIZE));
  1221. double modeTickV=SymbolInfoDouble(Symbol(),SYMBOL_TRADE_TICK_VALUE)
  1222. ,modeTickS=SymbolInfoDouble(Symbol(),SYMBOL_TRADE_TICK_SIZE);
  1223. // Print("Pip value: ", NormalizeDouble(((SymbolInfoDouble(Symbol(),SYMBOL_TRADE_TICK_VALUE)/(SymbolInfoDouble(Symbol(),SYMBOL_TRADE_TICK_SIZE)/Point))*10),2));
  1224. double pipvalue = NormalizeDouble(((SymbolInfoDouble(Symbol(),SYMBOL_TRADE_TICK_VALUE)/(SymbolInfoDouble(Symbol(),SYMBOL_TRADE_TICK_SIZE)/Point()))*10),2);
  1225. // pipvalue=NormalizeDouble((modeTickV/modeTickS/Point()),)
  1226. // pipvalue=
  1227. pipvalue = pipvalue / 10;
  1228. double lotSize = lot_size;
  1229. if(lot_calculator==rsk) //calculating risk
  1230. {
  1231. double riskamount=(risk/100)*AccountInfoDouble(ACCOUNT_BALANCE);
  1232. double pipvalue_required=riskamount/stop_loss;
  1233. lotSize = pipvalue_required/pipvalue;
  1234. //sl=riskamount/pipValuelot
  1235. int roundDigit=0;
  1236. double step=SymbolInfoDouble(Symbol(),SYMBOL_VOLUME_STEP);
  1237. while(step<1)
  1238. {
  1239. roundDigit++;
  1240. step=step*10;
  1241. }
  1242. Print("Round Digits:",roundDigit);
  1243. lotSize = NormalizeDouble(lotSize,roundDigit);
  1244. //
  1245. }
  1246. Print("Lot Size: ",lotSize);
  1247. if(lotSize > SymbolInfoDouble(Symbol(),SYMBOL_VOLUME_MAX))
  1248. {
  1249. lotSize=SymbolInfoDouble(Symbol(),SYMBOL_VOLUME_MAX);
  1250. }
  1251. else
  1252. if(lotSize<SymbolInfoDouble(Symbol(),SYMBOL_VOLUME_MIN))
  1253. {
  1254. lotSize=SymbolInfoDouble(Symbol(),SYMBOL_VOLUME_MIN);
  1255. }
  1256. //---
  1257. return lotSize;
  1258. }
  1259. //+------------------------------------------------------------------+
  1260. //| |
  1261. //+------------------------------------------------------------------+
  1262. double getDoubleSymbolInfo(string symbol,string info)
  1263. {
  1264. long digits=8;
  1265. //Symbol without the suffix and prefix
  1266. string updatedSymbol=symbol;
  1267. if(suffix!="")
  1268. updatedSymbol = StringSubstr(updatedSymbol,0,StringFind(updatedSymbol,suffix,0));
  1269. if(prefix!="")
  1270. StringReplace(updatedSymbol,prefix,"");
  1271. //Digits calculation could be used in other calculations
  1272. digits = SymbolInfoInteger(symbol,SYMBOL_DIGITS);
  1273. if(digits==0)
  1274. {
  1275. digits=SymbolInfoInteger(updatedSymbol,SYMBOL_DIGITS);
  1276. if(digits==0)
  1277. digits=8;
  1278. }
  1279. if(info=="digits")
  1280. {
  1281. return (double)digits;
  1282. }
  1283. else
  1284. if(info=="point" || info=="points")
  1285. {
  1286. double points=SymbolInfoDouble(symbol, SYMBOL_POINT);
  1287. if(points==0)
  1288. {
  1289. points=SymbolInfoDouble(updatedSymbol,SYMBOL_POINT);
  1290. if(points==0)
  1291. points=0.00001;
  1292. }
  1293. return points;
  1294. }
  1295. else
  1296. if(info=="ask")
  1297. {
  1298. double ask = SymbolInfoDouble(symbol, SYMBOL_ASK);
  1299. if(ask==0)
  1300. {
  1301. ask=SymbolInfoDouble(updatedSymbol,SYMBOL_ASK);
  1302. }
  1303. return NormalizeDouble(ask,(int)digits);
  1304. }
  1305. else
  1306. if(info=="bid")
  1307. {
  1308. double bid=SymbolInfoDouble(symbol, SYMBOL_BID);
  1309. if(bid==0)
  1310. {
  1311. bid=SymbolInfoDouble(updatedSymbol,SYMBOL_BID);
  1312. }
  1313. return NormalizeDouble(bid,(int)digits);
  1314. }
  1315. else
  1316. if(info=="contract"||info=="contractSize")
  1317. {
  1318. double contract=SymbolInfoDouble(symbol,SYMBOL_TRADE_CONTRACT_SIZE);
  1319. if(contract==0)
  1320. {
  1321. contract=SymbolInfoDouble(updatedSymbol,SYMBOL_TRADE_CONTRACT_SIZE);
  1322. }
  1323. return contract;
  1324. }
  1325. return 0;
  1326. }
  1327. //+------------------------------------------------------------------+
  1328. //| |
  1329. //+------------------------------------------------------------------+
  1330. string getSymbol(string symbol)
  1331. {
  1332. if(mappingSymbol!="")
  1333. {
  1334. string symbollist[];
  1335. StringSplit(mappingSymbol,';',symbollist);
  1336. for(int i=0; i<ArraySize(symbollist); i++)
  1337. {
  1338. string symbolPairs[];
  1339. StringSplit(symbollist[i],',',symbolPairs);
  1340. if(ArraySize(symbolPairs)==2)
  1341. {
  1342. if(symbol==symbolPairs[0])
  1343. return symbolPairs[1];
  1344. }
  1345. }
  1346. }
  1347. else
  1348. {
  1349. return prefix+symbol+suffix;
  1350. }
  1351. return prefix+symbol+suffix;
  1352. }
  1353. //+------------------------------------------------------------------+
  1354. //| |
  1355. //+------------------------------------------------------------------+
  1356. void placeBuyTrade()
  1357. {
  1358. double buySL = 0, buyTp=0;
  1359. //openPrice = SymbolInfoDouble(Symbol(),SYMBOL_ASK);
  1360. double Ask = SymbolInfoDouble(Symbol(),SYMBOL_ASK);
  1361. double Bid = SymbolInfoDouble(Symbol(),SYMBOL_BID);
  1362. if(stoplossTrade != 0)
  1363. {
  1364. buySL = Ask - (stoplossTrade * 10 * Point());
  1365. }
  1366. if(takeprofitTrade != 0)
  1367. {
  1368. buyTp = Ask + (takeprofitTrade * 10 * Point());
  1369. }
  1370. double sl_distance = ((Ask - buySL) / Point());
  1371. if(trade.PositionOpen(Symbol(),ORDER_TYPE_BUY,getlot(sl_distance),Ask,buySL,buyTp,"Buy Trade Placed"))
  1372. {
  1373. Print("Buy Trade Placed: ",trade.ResultOrder());
  1374. }
  1375. else
  1376. {
  1377. Print("Error in placing Buy: "+Symbol()+" ",GetLastError());
  1378. }
  1379. }
  1380. //+------------------------------------------------------------------+
  1381. //| |
  1382. //+------------------------------------------------------------------+
  1383. void placeSellTrade()
  1384. {
  1385. double sellSL = 0, sellTp = 0;
  1386. //openPrice = SymbolInfoDouble(Symbol(),SYMBOL_BID);
  1387. double Ask = SymbolInfoDouble(Symbol(),SYMBOL_ASK);
  1388. double Bid = SymbolInfoDouble(Symbol(),SYMBOL_BID);
  1389. if(stoplossTrade != 0)
  1390. {
  1391. sellSL = Bid + (stoplossTrade * 10 * Point());
  1392. }
  1393. if(takeprofitTrade != 0)
  1394. {
  1395. sellTp = Bid - (takeprofitTrade * 10 * Point());
  1396. }
  1397. double sl_distance = ((sellSL - Bid) / Point());
  1398. if(trade.PositionOpen(Symbol(),ORDER_TYPE_SELL,getlot(sl_distance),Bid,sellSL,sellTp,"Sell Trade Placed"))
  1399. {
  1400. Print("Sell Trade PLaced: ",trade.ResultOrder());
  1401. }
  1402. else
  1403. {
  1404. Print("Error in placing Sell: "+Symbol()+" ",GetLastError());
  1405. }
  1406. }
  1407. //+------------------------------------------------------------------+
  1408. //| |
  1409. //+------------------------------------------------------------------+
  1410. void dashboard_data()
  1411. {
  1412. ExtDialog.m_label0.Text(" Master Trades Lots Calc: " + DoubleToString(totalLiveLots(), 2));
  1413. }
  1414. //+------------------------------------------------------------------+
  1415. //| |
  1416. //+------------------------------------------------------------------+
  1417. double totalLiveLots()
  1418. {
  1419. double total_lots = 0.0;
  1420. for(int i = 0; i < PositionsTotal(); i++)
  1421. {
  1422. ulong ticket = PositionGetTicket(i);
  1423. if(PositionSelectByTicket(ticket))
  1424. {
  1425. //if(PositionGetInteger(POSITION_MAGIC) == magic_no)
  1426. {
  1427. //if(PositionGetString(POSITION_SYMBOL) == Symbol())
  1428. {
  1429. int type = (int)PositionGetInteger(POSITION_TYPE);
  1430. if(type == POSITION_TYPE_BUY || type == POSITION_TYPE_SELL)
  1431. {
  1432. total_lots += PositionGetDouble(POSITION_VOLUME);
  1433. }
  1434. }
  1435. }
  1436. }
  1437. }
  1438. return total_lots;
  1439. }
  1440. //+------------------------------------------------------------------+
  1441. //| |
  1442. //+------------------------------------------------------------------+
  1443. void store_live_and_history_tickets()
  1444. {
  1445. // cutoff time = now - N days
  1446. datetime cutoff = (datetime)(TimeCurrent() - (datetime)daysOfTradesToAdd * 86400);
  1447. // --- history orders loop (closed / cancelled / executed orders) ---
  1448. // select history for the required period
  1449. if(HistorySelect(cutoff, LONG_MAX))
  1450. {
  1451. int deals_count = (int)HistoryDealsTotal();
  1452. for(int j = deals_count - 1; j >= 0; --j)
  1453. {
  1454. ulong deal_ticket = HistoryDealGetTicket(j);
  1455. if(deal_ticket == 0)
  1456. continue;
  1457. // deal execution time
  1458. long dealTime = (long)HistoryDealGetInteger(deal_ticket, DEAL_TIME);
  1459. if((datetime)dealTime < cutoff)
  1460. continue; // older than cutoff, skip
  1461. // position id related to this deal (the stored "ticket" you track)
  1462. long position_id = (long)HistoryDealGetInteger(deal_ticket, DEAL_POSITION_ID);
  1463. if(position_id <= 0)
  1464. continue; // no position id to store
  1465. if(HistoryDealGetInteger(deal_ticket, DEAL_ENTRY) != DEAL_ENTRY_IN)
  1466. continue;
  1467. ulong ticket = position_id;
  1468. ulong magic = HistoryDealGetInteger(deal_ticket, DEAL_MAGIC);
  1469. double dealInLot = HistoryDealGetDouble(deal_ticket, DEAL_VOLUME);
  1470. double dealOutLot = dealOutLotsCheck(cutoff, position_id);
  1471. if(dealInLot == dealOutLot)
  1472. if(!history_ticket_present(ticket))
  1473. {
  1474. Print(" Position Id: ", position_id," Deal In Lot: ", dealInLot, " Deal Out Lot: ", dealOutLot);
  1475. add_history_ticket(ticket, magic);
  1476. }
  1477. HistorySelect(cutoff, LONG_MAX);
  1478. }
  1479. }
  1480. else
  1481. {
  1482. // optional: failed to select history — you may handle/log if needed
  1483. // Print("HistorySelect failed. LastError=", GetLastError());
  1484. }
  1485. int ordersTotal=HistoryOrdersTotal();
  1486. ulong orderTicket=0;
  1487. for(int j=0; j<ordersTotal; j++)
  1488. {
  1489. orderTicket=HistoryOrderGetTicket(j);
  1490. long type=HistoryOrderGetInteger(orderTicket,ORDER_TYPE);
  1491. if(type==ORDER_TYPE_BUY_LIMIT || type==ORDER_TYPE_SELL_LIMIT || type==ORDER_TYPE_BUY_STOP
  1492. || type==ORDER_TYPE_SELL_STOP ||type==ORDER_TYPE_BUY_STOP_LIMIT || type==ORDER_TYPE_SELL_STOP_LIMIT)
  1493. {
  1494. long state=HistoryOrderGetInteger(orderTicket,ORDER_STATE);
  1495. if(state==ORDER_STATE_CANCELED || state==ORDER_STATE_REJECTED || state==ORDER_STATE_EXPIRED || state==ORDER_STATE_REQUEST_CANCEL)
  1496. {
  1497. datetime openTime = (datetime)HistoryOrderGetInteger(orderTicket, ORDER_TIME_SETUP);
  1498. if(openTime >= cutoff)
  1499. {
  1500. ulong magic = HistoryOrderGetInteger(orderTicket, ORDER_MAGIC);
  1501. if(!history_ticket_present(orderTicket))
  1502. {
  1503. add_history_ticket(orderTicket, magic);
  1504. }
  1505. }
  1506. }
  1507. }
  1508. }
  1509. }
  1510. //+------------------------------------------------------------------+
  1511. //| |
  1512. //+------------------------------------------------------------------+
  1513. double dealOutLotsCheck(datetime cutOffTimeIs, ulong positionId)
  1514. {
  1515. double sumOfLots = 0.0;
  1516. if(HistorySelect(cutOffTimeIs, LONG_MAX))
  1517. {
  1518. int totalDeals = HistoryDealsTotal();
  1519. for(int i = 0; i < totalDeals; i++)
  1520. {
  1521. ulong dealTicket = HistoryDealGetTicket(i);
  1522. ulong dealPositionID = (ulong)HistoryDealGetInteger(dealTicket, DEAL_POSITION_ID);
  1523. if((HistoryDealGetInteger(dealTicket, DEAL_ENTRY) == DEAL_ENTRY_OUT || HistoryDealGetInteger(dealTicket, DEAL_ENTRY) == DEAL_ENTRY_OUT_BY)
  1524. && dealPositionID == positionId)
  1525. {
  1526. sumOfLots += HistoryDealGetDouble(dealTicket, DEAL_VOLUME);
  1527. }
  1528. }
  1529. }
  1530. // if(HistorySelectByPosition(positionId))
  1531. // {
  1532. // int totalDeals = HistoryDealsTotal();
  1533. // for(int i = 0; i < totalDeals; i++)
  1534. // {
  1535. // ulong dealTicket = HistoryDealGetTicket(i);
  1536. // ulong dealPositionID = (ulong)HistoryDealGetInteger(dealTicket, DEAL_POSITION_ID);
  1537. //
  1538. // //Print(" inside : ",positionId," i: ",i," lot: ",HistoryDealGetDouble(dealTicket, DEAL_VOLUME)," dealPositionID: ",dealPositionID," positionId: ",positionId," DEAL Type: ",HistoryDealGetInteger(dealTicket, DEAL_ENTRY));
  1539. // if((HistoryDealGetInteger(dealTicket, DEAL_ENTRY) == DEAL_ENTRY_OUT || HistoryDealGetInteger(dealTicket, DEAL_ENTRY) == DEAL_ENTRY_OUT_BY)
  1540. // && dealPositionID == positionId)
  1541. // {
  1542. // // Print(" inside 2");
  1543. // sumOfLots += HistoryDealGetDouble(dealTicket, DEAL_VOLUME);
  1544. // }
  1545. // }
  1546. // }
  1547. return sumOfLots;
  1548. }
  1549. //+------------------------------------------------------------------+
  1550. //| |
  1551. //+------------------------------------------------------------------+
  1552. bool history_ticket_present(ulong ticket)
  1553. {
  1554. for(int i = 0 ; i < MaxOrders ; i++)
  1555. {
  1556. if(historyTradeStore[i].ticket == ticket)
  1557. return true;
  1558. }
  1559. return false;
  1560. }
  1561. //+------------------------------------------------------------------+
  1562. //| |
  1563. //+------------------------------------------------------------------+
  1564. void add_history_ticket(ulong ticket, ulong magicIs)
  1565. {
  1566. for(int i = 0; i < MaxOrders; i++)
  1567. {
  1568. if(historyTradeStore[i].ticket == -1)
  1569. {
  1570. historyTradeStore[i].ticket = ticket;
  1571. historyTradeStore[i].magic = magicIs;
  1572. Print("Ticket Added to History Structure. Ticket: ", ticket, " Magic: ", magicIs);
  1573. if(!save_history_store("add_history_ticket()"))
  1574. {
  1575. historyTradeStore[i].ticket = -1;
  1576. historyTradeStore[i].magic = 0;
  1577. Print("Ticket Remove from History Structure because file not opened Ticket: ", ticket, " Magic: ", magicIs);
  1578. }
  1579. return;
  1580. }
  1581. }
  1582. Print("historyTradeStore full, cannot add ticket: ", ticket);
  1583. }
  1584. //+------------------------------------------------------------------+
  1585. //| |
  1586. //+------------------------------------------------------------------+
  1587. void clear_history_store()
  1588. {
  1589. for(int i = 0; i < MaxOrders; i++)
  1590. {
  1591. historyTradeStore[i].ticket = -1;
  1592. historyTradeStore[i].magic = 0;
  1593. }
  1594. Print("History store cleaned");
  1595. }
  1596. //+------------------------------------------------------------------+
  1597. //| |
  1598. //+------------------------------------------------------------------+
  1599. bool save_history_store(string calledBy)
  1600. {
  1601. string file_nameIs = "history_trades.csv";
  1602. int fileHandle = FileOpen(file_nameIs, FILE_WRITE | FILE_CSV | FILE_COMMON);
  1603. if(fileHandle != INVALID_HANDLE)
  1604. {
  1605. for(int i = 0; i < MaxOrders; i++)
  1606. {
  1607. if(historyTradeStore[i].ticket != -1)
  1608. {
  1609. string data_to_store = IntegerToString(historyTradeStore[i].ticket) + "," + IntegerToString(historyTradeStore[i].magic) + "\r\n";
  1610. FileWriteString(fileHandle, data_to_store);
  1611. }
  1612. }
  1613. //Print("save_history_store() called by: ", calledBy, " Time: ", TimeToString(TimeCurrent(), TIME_DATE | TIME_SECONDS));
  1614. FileClose(fileHandle);
  1615. return true;
  1616. }
  1617. else
  1618. {
  1619. Print("Error opening file save_history_store(): ", GetLastError());
  1620. }
  1621. return false;
  1622. }
  1623. //+------------------------------------------------------------------+
  1624. //| |
  1625. //+------------------------------------------------------------------+
  1626. void remove_old_tickets_from_store()
  1627. {
  1628. datetime cutoff = TimeCurrent() - (datetime)daysOfTradesToAdd * 86400;
  1629. // Print("remove_old_tickets_from_store: cutoff = ", TimeToString(cutoff, TIME_DATE|TIME_SECONDS));
  1630. // Prepare history selection ranges once (for deals we limit by cutoff; for orders we select full history)
  1631. for(int i = 0; i < MaxOrders; i++)
  1632. {
  1633. ulong tk = historyTradeStore[i].ticket;
  1634. if(tk == -1) // empty slot
  1635. continue;
  1636. bool found = false;
  1637. ulong pos_ticket = (ulong)tk;
  1638. if(HistorySelect(cutoff, TimeCurrent()))
  1639. {
  1640. int deals_count = (int)HistoryDealsTotal();
  1641. for(int j = deals_count - 1; j >= 0; --j)
  1642. {
  1643. ulong deal_ticket = HistoryDealGetTicket(j);
  1644. if(deal_ticket == 0)
  1645. continue;
  1646. // deal execution time
  1647. long dealTime = (long)HistoryDealGetInteger(deal_ticket, DEAL_TIME);
  1648. if((datetime)dealTime < cutoff)
  1649. continue; // older than cutoff, skip
  1650. if(HistoryDealGetInteger(deal_ticket, DEAL_ENTRY) != DEAL_ENTRY_IN)
  1651. continue;
  1652. // position id related to this deal (the stored "ticket" you track)
  1653. long position_id = (long)HistoryDealGetInteger(deal_ticket, DEAL_POSITION_ID);
  1654. if(position_id <= 0)
  1655. continue; // no position id to store
  1656. double dealInLot = HistoryDealGetDouble(deal_ticket, DEAL_VOLUME);
  1657. double dealOutLot = dealOutLotsCheck(cutoff, position_id);
  1658. if(dealInLot == dealOutLot)
  1659. if(position_id == pos_ticket)
  1660. {
  1661. found = true;
  1662. break;
  1663. }
  1664. }
  1665. HistorySelect(cutoff, TimeCurrent());
  1666. }
  1667. else
  1668. {
  1669. // optional: failed to select history — you may handle/log if needed
  1670. // Print("HistorySelect failed. LastError=", GetLastError());
  1671. }
  1672. if(!found)
  1673. {
  1674. int ordersTotal = HistoryOrdersTotal();
  1675. for(int j = 0; j < ordersTotal; j++)
  1676. {
  1677. ulong orderTicket = HistoryOrderGetTicket(j);
  1678. if(orderTicket == 0)
  1679. continue;
  1680. long type = HistoryOrderGetInteger(orderTicket, ORDER_TYPE);
  1681. if(type != ORDER_TYPE_BUY_LIMIT && type != ORDER_TYPE_SELL_LIMIT &&
  1682. type != ORDER_TYPE_BUY_STOP && type != ORDER_TYPE_SELL_STOP)
  1683. continue;
  1684. datetime openTime = (datetime)HistoryOrderGetInteger(orderTicket, ORDER_TIME_SETUP);
  1685. long state=HistoryOrderGetInteger(orderTicket,ORDER_STATE);
  1686. if(state==ORDER_STATE_CANCELED || state==ORDER_STATE_REJECTED || state==ORDER_STATE_EXPIRED || state==ORDER_STATE_REQUEST_CANCEL)
  1687. {
  1688. if(orderTicket == pos_ticket)
  1689. {
  1690. if(openTime > cutoff)
  1691. {
  1692. found = true;
  1693. break;
  1694. }
  1695. }
  1696. }
  1697. }
  1698. }
  1699. // 3) Final action: remove if not found
  1700. if(!found)
  1701. {
  1702. Print("Ticket not found, removing from store: ", tk, " index=", i);
  1703. historyTradeStore[i].ticket = -1;
  1704. historyTradeStore[i].magic = 0;
  1705. // (optionally clear other fields if your struct has them)
  1706. }
  1707. } // for i
  1708. }
  1709. //+------------------------------------------------------------------+
  1710. //+------------------------------------------------------------------+
  1711. //| |
  1712. //+------------------------------------------------------------------+
  1713. //================================================ Dashboard ====================================
  1714. //+------------------------------------------------------------------+
  1715. //| |
  1716. //+------------------------------------------------------------------+
  1717. class CControlsDialog : public CAppDialog
  1718. {
  1719. public:
  1720. CLabel m_label0;
  1721. CButton m_button;
  1722. CButton m_button1;
  1723. CControlsDialog(void);
  1724. ~CControlsDialog(void);
  1725. //--- create
  1726. virtual bool Create(const long chart,const string name,const int subwin,const int x1,const int y1,const int x2,const int y2);
  1727. virtual bool OnEvent(const int id, const long &lparam,const double &dparam, const string &sparam);
  1728. bool CreateLabel0(void);
  1729. bool CreateButton(void);
  1730. bool CreateButton1(void);
  1731. void OnClickButton(void);
  1732. void OnClickButton1(void);
  1733. bool CreatePanel(void);
  1734. };
  1735. //+------------------------------------------------------------------+
  1736. //| |
  1737. //+------------------------------------------------------------------+
  1738. EVENT_MAP_BEGIN(CControlsDialog)
  1739. //ON_EVENT(ON_CLICK,m_button,OnClickButton)
  1740. //ON_EVENT(ON_CLICK,m_button1,OnClickButton1)
  1741. EVENT_MAP_END(CAppDialog)
  1742. //+------------------------------------------------------------------+
  1743. //| Constructor |
  1744. //+------------------------------------------------------------------+
  1745. CControlsDialog::CControlsDialog(void)
  1746. {
  1747. }
  1748. //+------------------------------------------------------------------+
  1749. //| Destructor |
  1750. //+------------------------------------------------------------------+
  1751. CControlsDialog::~CControlsDialog(void)
  1752. {
  1753. }
  1754. //+------------------------------------------------------------------+
  1755. //| Create |
  1756. //+------------------------------------------------------------------+
  1757. bool CControlsDialog::Create(const long chart,const string name,const int subwin,const int x1,const int y1,const int x2,const int y2)
  1758. {
  1759. if(!CAppDialog::Create(chart,name,subwin,20,20,dashWidth,dashHeight))
  1760. return(false);
  1761. //--- create dependent controls
  1762. if(!CreatePanel())
  1763. return(false);
  1764. if(!CreateLabel0())
  1765. return(false);
  1766. if(!CreateButton())
  1767. return(false);
  1768. if(!CreateButton1())
  1769. return(false);
  1770. //--- succeed
  1771. return(true);
  1772. }
  1773. //+------------------------------------------------------------------+
  1774. //| |
  1775. //+------------------------------------------------------------------+
  1776. bool CControlsDialog::CreateLabel0(void) //Trend Info
  1777. {
  1778. //--- coordinates
  1779. int x1 = (dashWidth/2) - 235;
  1780. int y1 = yAxisGlobal + 15;
  1781. int x2 = 0;
  1782. int y2 = 0;
  1783. //--- create
  1784. if(!m_label0.Create(m_chart_id,m_name+"Label0",m_subwin,x1,y1,x2,y2))
  1785. return(false);
  1786. if(!m_label0.Text(" Master Trades Lots Calc: 0.00"))
  1787. return(false);
  1788. if(!m_label0.Color(clrBlack))
  1789. return(false);
  1790. if(!m_label0.Font("Calibri"))
  1791. return(false);
  1792. if(!m_label0.FontSize(FontSize))
  1793. return(false);
  1794. if(!Add(m_label0))
  1795. return(false);
  1796. //--- succeed
  1797. return(true);
  1798. }
  1799. //+------------------------------------------------------------------+
  1800. //| |
  1801. //+------------------------------------------------------------------+
  1802. bool CControlsDialog::CreateButton(void)
  1803. {
  1804. //--- coordinates
  1805. // Buy
  1806. int x1 = (dashWidth/2) + 14;
  1807. int y1 = yAxisGlobal + 10;
  1808. int x2 = x1 + 70;
  1809. int y2 = y1 + 30;
  1810. //--- create
  1811. if(!m_button.Create(m_chart_id,"button",m_subwin,x1,y1,x2,y2))
  1812. return(false);
  1813. if(!m_button.ColorBackground(clrSlateGray))
  1814. return(false);
  1815. if(!m_button.Text("Sell"))
  1816. return(false);
  1817. if(!m_button.FontSize(FontSize))
  1818. return(false);
  1819. if(!m_button.ColorBackground(clrRed))
  1820. return(false);
  1821. if(!m_button.Font("Calibri Bold"))
  1822. return(false);
  1823. if(!m_button.Color(clrWhiteSmoke))
  1824. return(false);
  1825. if(!m_button.ColorBorder(clrRed))
  1826. return(false);
  1827. if(!Add(m_button))
  1828. return(false);
  1829. m_button.Locking(true);
  1830. m_button.BringToTop();
  1831. //--- succeed
  1832. return(true);
  1833. }
  1834. //+------------------------------------------------------------------+
  1835. //| |
  1836. //+------------------------------------------------------------------+
  1837. bool CControlsDialog::CreateButton1(void)
  1838. {
  1839. //--- coordinates
  1840. // Sell
  1841. int x1 = (dashWidth/2) + 100;
  1842. int y1 = yAxisGlobal + 10;
  1843. int x2 = x1 + 70;
  1844. int y2 = y1 + 30;
  1845. //--- create
  1846. if(!m_button1.Create(m_chart_id,"button1",m_subwin,x1,y1,x2,y2))
  1847. return(false);
  1848. if(!m_button1.ColorBackground(clrBlue))
  1849. return(false);
  1850. if(!m_button1.Text("Buy"))
  1851. return(false);
  1852. if(!m_button1.FontSize(FontSize))
  1853. return(false);
  1854. if(!m_button1.Font("Calibri Bold"))
  1855. return(false);
  1856. if(!m_button1.Color(clrWhiteSmoke))
  1857. return(false);
  1858. if(!m_button1.ColorBorder(clrBlack))
  1859. return(false);
  1860. if(!Add(m_button1))
  1861. return(false);
  1862. m_button1.Locking(true);
  1863. m_button1.BringToTop();
  1864. //--- succeed
  1865. return(true);
  1866. }
  1867. //+------------------------------------------------------------------+
  1868. //| |
  1869. //+------------------------------------------------------------------+
  1870. void CControlsDialog::OnClickButton(void)
  1871. {
  1872. if(m_button.Pressed())
  1873. {
  1874. Print(" Clicked on Button");
  1875. placeSellTrade();
  1876. m_button.Pressed(false);
  1877. }
  1878. }
  1879. //+------------------------------------------------------------------+
  1880. //| |
  1881. //+------------------------------------------------------------------+
  1882. void CControlsDialog::OnClickButton1(void)
  1883. {
  1884. if(m_button1.Pressed())
  1885. {
  1886. Print(" Clicked on Button 1");
  1887. placeBuyTrade();
  1888. m_button1.Pressed(false);
  1889. }
  1890. }
  1891. //+------------------------------------------------------------------+
  1892. //| |
  1893. //+------------------------------------------------------------------+
  1894. bool CControlsDialog::CreatePanel(void)
  1895. {
  1896. //--- coordinates
  1897. int x1=0;
  1898. int y1=0;
  1899. int x2=dashWidth;
  1900. int y2=dashHeight;
  1901. //--- create
  1902. if(!backgroundPanel.Create(0,ExtDialog.Name()+"backPanel",m_subwin,x1,y1,x2,y2))
  1903. return(false);
  1904. if(!backgroundPanel.ColorBackground(clrWhiteSmoke))
  1905. return(false);
  1906. if(!backgroundPanel.ColorBorder(00128))
  1907. return(false);
  1908. if(!ExtDialog.Add(backgroundPanel))
  1909. return(false);
  1910. ExtDialog.Minimized(false);
  1911. backgroundPanel.Alignment(WND_ALIGN_CLIENT,0,0,0,0);
  1912. //--- succeed
  1913. return(true);
  1914. }
  1915. CControlsDialog ExtDialog;
  1916. CPanel backgroundPanel;
  1917. //+------------------------------------------------------------------+
  1918. //| |
  1919. //+------------------------------------------------------------------+
  1920. //+------------------------------------------------------------------+