Няма описание

localHedgingMasterCopierMt5.mq5 170KB

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