Brak opisu

localHedgingClientCopierMt5.mq5 73KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776
  1. //+------------------------------------------------------------------+
  2. //| localHedgingClientCopierMt5.mq5 |
  3. //| Copyright 2025, MetaQuotes Ltd. |
  4. //| https://www.mqldevelopment.com/ |
  5. //+------------------------------------------------------------------+
  6. #property copyright "Copyright 2025, MetaQuotes Ltd."
  7. #property link "https://www.mqldevelopment.com/"
  8. #property version "1.00"
  9. #define orderCount 2000
  10. #define count1 50
  11. #define testCounter 50
  12. #define MaxOrders 20000
  13. #define daysOfTradesToAdd 20
  14. #include <Trade\Trade.mqh>
  15. CTrade trade;
  16. //+------------------------------------------------------------------+
  17. //| Expert initialization function |
  18. //+------------------------------------------------------------------+
  19. struct historyTradesClientSide
  20. {
  21. ulong ticket;
  22. ulong magic;
  23. historyTradesClientSide()
  24. {
  25. ticket = -1;
  26. magic = 0;
  27. }
  28. };
  29. historyTradesClientSide historyTradeStore[MaxOrders];
  30. struct order
  31. {
  32. ulong ticket;
  33. double price;
  34. datetime opentime;
  35. string symbol;
  36. int ordertype;
  37. double lots;
  38. double stoploss;
  39. double takeprofit;
  40. double accountBalance;
  41. int contractSize;
  42. string comments;
  43. int magicNo;
  44. double closedPercentageOfTrade;
  45. order()
  46. {
  47. ticket =-1;
  48. closedPercentageOfTrade = 0;
  49. }
  50. };
  51. struct clientOrder
  52. {
  53. ulong ticket;
  54. double price;
  55. datetime opentime;
  56. string symbol;
  57. int ordertype;
  58. double lots;
  59. double stoploss;
  60. double takeprofit;
  61. ulong magic;
  62. string comments;
  63. double masterLot;
  64. clientOrder()
  65. {
  66. ticket=-1;
  67. price=-1;
  68. symbol=Symbol();
  69. ordertype=-1;
  70. lots=0;
  71. masterLot=0;
  72. stoploss=0;
  73. takeprofit=0;
  74. magic=0;
  75. comments="";
  76. }
  77. };
  78. clientOrder cod[orderCount];
  79. struct masterOrder
  80. {
  81. datetime opentime;
  82. string symbol;
  83. ulong ordertype;
  84. double price;
  85. double lots;
  86. double stoploss;
  87. double takeprofit;
  88. ulong ticket;
  89. int magic;
  90. double accountBalance;
  91. int contractSize;
  92. string comment;
  93. masterOrder()
  94. {
  95. ticket=-1;
  96. price=-1;
  97. symbol=Symbol();
  98. ordertype=-1;
  99. lots=0;
  100. stoploss=0;
  101. takeprofit=0;
  102. }
  103. };
  104. masterOrder mod1[orderCount];
  105. enum lot_option
  106. {
  107. fix, //Fixed Lot
  108. mul, //Multiplied Lot
  109. Balance, // Balance Base Multiplier
  110. slaveLotCal,
  111. };
  112. enum tradeCopy_type
  113. {
  114. buy,//Buy Only
  115. sell,//Sell Only
  116. buySell,//Buy and Sell
  117. };
  118. enum operation_code
  119. {
  120. Master, //Master
  121. Client, //Client
  122. };
  123. sinput string string_0 = "<><><><><><> General SETTINGS <><><><><><>"; //__
  124. input int slip = 5; // Master Order Variation in Pips
  125. input int sec = 10; // Master Order Expired After Seconds
  126. input tradeCopy_type tradeType = buySell; // Trades To Copy
  127. input lot_option lotoption = slaveLotCal; // Lot Option
  128. input double mult = 1.0; // Multiplier (for Client)
  129. input double fixed = 0.1; // Fixed Lot (for Client)
  130. input double Bmult = 1; // Balance Multiplier (for Client)
  131. input double recoveryAmount = 3000; // Recovery Amount (for Client Lot)
  132. input double maxDd = 8000; // Max DrawDown (for Client Lot)
  133. input string suffix = ""; // Suffix
  134. input string symbolExclude = ""; // Symbol to Exclude
  135. input string prefix = ""; // Prefix
  136. input string mappingSymbol = "GOLD,XAUUSD;bitcoin,BTCUSD"; // Mapping Pairs Inp,Out;Inp,Out
  137. // Heart Beat
  138. sinput string string_1 = "<><><><><><> HeartBeat Setting <><><><><><>"; //__
  139. input string clientServer = ""; // Master Server
  140. input string localApiKey = "U2FsdGVkX18vBY4H1uzQiZwuh8B++8VBtCGJ3yGr2XPII0qCodmfuhjssKu5oug1J4e97bkwPtDQLi4py1OODQ=="; // Local API Key
  141. input string localHB_req_link = "http://localhost/api/slastConnected"; // Request Link For LastConnected
  142. //+------------------------------------------------------------------+
  143. //| |
  144. //+------------------------------------------------------------------+
  145. //Global Variable
  146. int gmtDifference = 0;
  147. int filehandle;
  148. // Heart Beat
  149. long lastFileSize=0;
  150. datetime lastModified=0;
  151. bool contractChk = true;//Contract Checking
  152. bool doReversal = true; // Reverse Trades
  153. bool fileLastEmpty=false;
  154. long accountNumber=AccountInfoInteger(ACCOUNT_LOGIN);
  155. int counter=0,testCounterVar=0;
  156. order order_array[];
  157. datetime lastModified1=0;
  158. long lastFileSize1=0;
  159. bool fileHandlerIssue=false;
  160. operation_code mode1=Client; //Working code
  161. int OnInit()
  162. {
  163. //---
  164. accountNumber=AccountInfoInteger(ACCOUNT_LOGIN);
  165. EventSetMillisecondTimer(20);
  166. if(!ObjectFind(0,"mode") || ObjectGetString(0,"mode",OBJPROP_TEXT,0)!=EnumToString(mode1)+" Account")
  167. {
  168. ObjectDelete(0,"mode");
  169. ObjectCreate(0,"mode",OBJ_LABEL,0,0,0);
  170. ObjectSetInteger(0,"mode",OBJPROP_XDISTANCE,10);
  171. ObjectSetInteger(0,"mode",OBJPROP_YDISTANCE,25);
  172. ObjectSetInteger(0,"mode",OBJPROP_CORNER,CORNER_RIGHT_UPPER);
  173. ObjectSetInteger(0,"mode",OBJPROP_ANCHOR,ANCHOR_RIGHT_UPPER);
  174. ObjectSetInteger(0,"mode",OBJPROP_COLOR,clrLightBlue);
  175. ObjectSetString(0,"mode",OBJPROP_TEXT,EnumToString(mode1)+" Account");
  176. ObjectSetInteger(0,"mode",OBJPROP_FONTSIZE,14);
  177. }
  178. gmtDifference = (int)TimeCurrent() - (int)TimeGMT();
  179. Print("GMT Difference(sec): ",gmtDifference);
  180. mapHistory();
  181. //---
  182. return(INIT_SUCCEEDED);
  183. }
  184. //+------------------------------------------------------------------+
  185. //| Expert deinitialization function |
  186. //+------------------------------------------------------------------+
  187. void OnDeinit(const int reason)
  188. {
  189. //---
  190. EventKillTimer();
  191. ObjectsDeleteAll(0,0,-1);
  192. }
  193. //+------------------------------------------------------------------+
  194. //| Expert tick function |
  195. //+------------------------------------------------------------------+
  196. void OnTick()
  197. {
  198. //---
  199. }
  200. //+------------------------------------------------------------------+
  201. void OnTimer()
  202. {
  203. gmtDifference = (int)TimeCurrent() - (int)TimeGMT();
  204. read_history_file();
  205. readData();
  206. writeDataClientCof();
  207. }
  208. //+------------------------------------------------------------------+
  209. //| |
  210. //+------------------------------------------------------------------+
  211. void writeDataClientCof()
  212. {
  213. int fileHandleClientCof;
  214. if(PositionsTotal()==0 && OrdersTotal()==0 && !fileLastEmpty && TerminalInfoInteger(TERMINAL_CONNECTED))
  215. {
  216. fileHandleClientCof = FileOpen("COF_client.csv", FILE_WRITE|FILE_CSV|FILE_COMMON);
  217. if(fileHandleClientCof != INVALID_HANDLE)
  218. {
  219. Print("Writing file to empty");
  220. FileWrite(fileHandleClientCof, "");
  221. FileClose(fileHandleClientCof);
  222. fileLastEmpty = true;
  223. emptyStruct();
  224. }
  225. else
  226. {
  227. Print(" Client Cof File handler issue:", GetLastError());
  228. }
  229. }
  230. else
  231. {
  232. bool updationReq = checkOrderUpdate();
  233. if(updationReq || fileHandlerIssue)
  234. {
  235. Print(" ------------------------------- Client Cof Start ------------------------------------------ ");
  236. fileHandleClientCof = FileOpen("COF_client.csv", FILE_WRITE|FILE_CSV|FILE_COMMON);
  237. if(fileHandleClientCof != INVALID_HANDLE)
  238. {
  239. fileHandlerIssue = false;
  240. for(int i = PositionsTotal()-1; i >= 0; i--)
  241. {
  242. ulong ticket = PositionGetTicket(i);
  243. if(PositionSelectByTicket(ticket))
  244. {
  245. string time = TimeToString(PositionGetInteger(POSITION_TIME)-gmtDifference,TIME_DATE|TIME_SECONDS);
  246. string symbol = PositionGetString(POSITION_SYMBOL);
  247. double digits=getDoubleSymbolInfo(symbol,"digits");
  248. int symbolContractSize=(int)getDoubleSymbolInfo(symbol,"contract");
  249. ulong tempTicket = PositionGetInteger(POSITION_TICKET);
  250. if(suffix != "")
  251. symbol = StringSubstr(symbol, 0, StringFind(symbol, suffix, 0));
  252. if(prefix != "")
  253. StringReplace(symbol, prefix, "");
  254. long orderType = PositionGetInteger(POSITION_TYPE);
  255. double takeProfit = PositionGetDouble(POSITION_TP), stopLoss = PositionGetDouble(POSITION_SL);
  256. if(doReversal)
  257. {
  258. if(orderType == POSITION_TYPE_BUY)
  259. orderType = POSITION_TYPE_SELL;
  260. else
  261. if(orderType == POSITION_TYPE_SELL)
  262. orderType = POSITION_TYPE_BUY;
  263. takeProfit = PositionGetDouble(POSITION_SL);
  264. stopLoss = PositionGetDouble(POSITION_TP);
  265. }
  266. double sumOfClosed = dealOutLotsCheck(0, PositionGetInteger(POSITION_TICKET));
  267. double currentLot = PositionGetDouble(POSITION_VOLUME);
  268. double totalLot = sumOfClosed + currentLot;
  269. double closedPercentage = 0.0;
  270. if(totalLot > 0.0)
  271. closedPercentage = (sumOfClosed / totalLot) * 100.0;
  272. Print(" Client Closed % = ", closedPercentage);
  273. 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";
  274. FileWrite(filehandle,OrderToWrite);
  275. }
  276. }
  277. for(int i = OrdersTotal()-1; i >= 0; i--)
  278. {
  279. ulong ticket = OrderGetTicket(i);
  280. if(OrderSelect(ticket))
  281. {
  282. string time = TimeToString(OrderGetInteger(ORDER_TIME_SETUP)-gmtDifference, TIME_DATE|TIME_SECONDS);
  283. string symbol = OrderGetString(ORDER_SYMBOL);
  284. double digits = getDoubleSymbolInfo(symbol,"digits");
  285. if(suffix != "")
  286. symbol = StringSubstr(symbol, 0, StringFind(symbol, suffix, 0));
  287. if(prefix != "")
  288. StringReplace(symbol, prefix, "");
  289. long orderType = OrderGetInteger(ORDER_TYPE);
  290. double takeProfit = OrderGetDouble(ORDER_TP);
  291. double stopLoss = OrderGetDouble(ORDER_SL);
  292. if(doReversal)
  293. {
  294. if(orderType == ORDER_TYPE_BUY_STOP)
  295. orderType = ORDER_TYPE_SELL_LIMIT;
  296. else
  297. if(orderType == ORDER_TYPE_SELL_STOP)
  298. orderType = ORDER_TYPE_BUY_LIMIT;
  299. else
  300. if(orderType == ORDER_TYPE_BUY_LIMIT)
  301. orderType = ORDER_TYPE_SELL_STOP;
  302. else
  303. if(orderType == ORDER_TYPE_SELL_LIMIT)
  304. orderType = ORDER_TYPE_BUY_STOP;
  305. takeProfit = OrderGetDouble(ORDER_SL);
  306. stopLoss = OrderGetDouble(ORDER_TP);
  307. }
  308. double closedPercentage = 0;
  309. string OrderToWrite =
  310. time + "," +
  311. symbol + "," +
  312. IntegerToString(orderType) + "," +
  313. DoubleToString(OrderGetDouble(ORDER_PRICE_OPEN),(int)digits) + "," +
  314. DoubleToString(OrderGetDouble(ORDER_VOLUME_CURRENT),2) + "," +
  315. DoubleToString(stopLoss,(int)digits) + "," +
  316. DoubleToString(takeProfit,(int)digits) + "," +
  317. IntegerToString(OrderGetInteger(ORDER_TICKET)) + "," +
  318. IntegerToString(OrderGetInteger(ORDER_MAGIC)) + "," +
  319. (string)AccountInfoDouble(ACCOUNT_BALANCE) + "," +
  320. DoubleToString(closedPercentage) +","+
  321. (string)SymbolInfoDouble(OrderGetString(ORDER_SYMBOL), SYMBOL_TRADE_CONTRACT_SIZE) +
  322. OrderGetString(ORDER_COMMENT) + "\r\n";
  323. Print("Client Cof Writing Pending Order Block.");
  324. FileWrite(fileHandleClientCof, OrderToWrite);
  325. }
  326. }
  327. FileClose(fileHandleClientCof);
  328. fileLastEmpty = false;
  329. Print("Client Cof File Updated:", TimeCurrent());
  330. }
  331. else
  332. {
  333. Print("Client Cof File Handle Issue:", GetLastError());
  334. }
  335. Print(" ------------------------------- Client Cof End ------------------------------------------ ");
  336. }
  337. }
  338. }
  339. //+------------------------------------------------------------------+
  340. //| |
  341. //+------------------------------------------------------------------+
  342. bool checkOrderUpdate()
  343. {
  344. bool updationRequired=false,currCheck=false;
  345. for(int i = PositionsTotal()-1 ; i >= 0 ; i--)
  346. {
  347. ulong ticket = PositionGetTicket(i);
  348. if(PositionSelectByTicket(ticket))
  349. {
  350. int orderIndex=-1;
  351. bool alreadyAdded=isOrderThere(ticket, orderIndex);
  352. if(!alreadyAdded)
  353. {
  354. currCheck=false;
  355. currCheck=addOrderMaster(ticket, "Market");
  356. if(!updationRequired)
  357. updationRequired=currCheck;
  358. }
  359. else
  360. {
  361. if(orderIndex!=-1)
  362. {
  363. currCheck=false;
  364. currCheck=IsOrderChanged(PositionGetInteger(POSITION_TICKET),orderIndex, "Market");
  365. if(!updationRequired)
  366. {
  367. updationRequired=currCheck;
  368. }
  369. }
  370. }
  371. }
  372. }
  373. for(int i = OrdersTotal()-1 ; i >= 0 ; i--)
  374. {
  375. ulong ticket = OrderGetTicket(i);
  376. if(OrderSelect(ticket))
  377. {
  378. if(OrderGetInteger(ORDER_TYPE) != ORDER_TYPE_BUY && OrderGetInteger(ORDER_TYPE) != ORDER_TYPE_SELL && OrderGetInteger(ORDER_TYPE) != ORDER_TYPE_CLOSE_BY)
  379. {
  380. int orderIndex=-1;
  381. bool alreadyAdded=isOrderThere(ticket, orderIndex);
  382. if(!alreadyAdded)
  383. {
  384. Print("Inside pending Adding to master order: ",ticket," type: ",OrderGetInteger(ORDER_TYPE)," ",OrdersTotal()," ",ORDER_TYPE_CLOSE_BY);
  385. currCheck=false;
  386. currCheck=addOrderMaster(ticket, "Pending");
  387. if(!updationRequired)
  388. updationRequired=currCheck;
  389. }
  390. else
  391. {
  392. if(orderIndex!=-1)
  393. {
  394. currCheck=false;
  395. currCheck=IsOrderChanged(OrderGetInteger(ORDER_TICKET), orderIndex, "Pending");
  396. if(!updationRequired)
  397. {
  398. updationRequired=currCheck;
  399. }
  400. }
  401. }
  402. }
  403. }
  404. }
  405. for(int i=0; i<ArraySize(mod1); i++)
  406. {
  407. bool isPresent=false;
  408. if(mod1[i].ticket !=-1)
  409. {
  410. for(int j = PositionsTotal()-1; j>=0; j--)
  411. {
  412. ulong ticket = PositionGetTicket(j);
  413. if(PositionSelectByTicket(ticket))
  414. {
  415. if(ticket==mod1[i].ticket)
  416. {
  417. isPresent=true;
  418. break;
  419. }
  420. }
  421. }
  422. // Pending Order
  423. for(int j = OrdersTotal()-1; j>=0; j--)
  424. {
  425. ulong ticket = OrderGetTicket(j);
  426. if(OrderSelect(ticket))
  427. {
  428. if(ticket==mod1[i].ticket)
  429. {
  430. isPresent=true;
  431. break;
  432. }
  433. }
  434. }
  435. if(!isPresent)
  436. {
  437. Print("Ticket is closed so removed from struct: ",mod1[i].ticket);
  438. mod1[i].ticket=-1;
  439. mod1[i].price=-1;
  440. mod1[i].symbol="";
  441. mod1[i].ordertype=-1;
  442. mod1[i].lots=0;
  443. mod1[i].stoploss=0;
  444. mod1[i].takeprofit=0;
  445. currCheck=true;
  446. //currCheck=clearStructIndex(mod1[i].ticket);
  447. if(!updationRequired)
  448. updationRequired=currCheck;
  449. }
  450. }
  451. }
  452. return updationRequired;
  453. }
  454. //+------------------------------------------------------------------+
  455. //| |
  456. //+------------------------------------------------------------------+
  457. bool IsOrderChanged(ulong orderTicket, int index, string calledBy)
  458. {
  459. if(mod1[index].ticket!=-1)
  460. {
  461. if(calledBy == "Market")
  462. {
  463. if(PositionSelectByTicket(orderTicket))
  464. {
  465. //Digits
  466. double digits=getDoubleSymbolInfo(PositionGetString(POSITION_SYMBOL),"digits");
  467. double tp=NormalizeDouble(PositionGetDouble(POSITION_TP), (int)digits),
  468. sl=NormalizeDouble(PositionGetDouble(POSITION_SL),(int)digits),
  469. lot=NormalizeDouble(PositionGetDouble(POSITION_VOLUME),2);
  470. 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))
  471. {
  472. Print(" Inside IsOrderChanged() ",mod1[index].lots," lot: ",lot," calledBy: ",calledBy," mod1 ticket ",mod1[index].ticket," orderTicket: ",orderTicket);
  473. // Time
  474. datetime time = (datetime)(PositionGetInteger(POSITION_TIME) - gmtDifference);
  475. mod1[index].opentime=time;
  476. mod1[index].lots=lot;
  477. mod1[index].stoploss=sl;
  478. mod1[index].takeprofit=tp;
  479. mod1[index].comment=PositionGetString(POSITION_COMMENT);
  480. mod1[index].ordertype=PositionGetInteger(POSITION_TYPE);
  481. mod1[index].price=PositionGetDouble(POSITION_PRICE_OPEN);
  482. return true;
  483. }
  484. }
  485. }
  486. if(calledBy == "Pending")
  487. {
  488. if(OrderSelect(orderTicket))
  489. {
  490. double digits=getDoubleSymbolInfo(OrderGetString(ORDER_SYMBOL),"digits");
  491. double tp=NormalizeDouble(OrderGetDouble(ORDER_TP), (int)digits),
  492. sl=NormalizeDouble(OrderGetDouble(ORDER_SL),(int)digits),
  493. lot=NormalizeDouble(OrderGetDouble(ORDER_VOLUME_CURRENT),2);
  494. 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))
  495. {
  496. //time
  497. datetime time = (datetime)(OrderGetDouble(ORDER_PRICE_OPEN) - gmtDifference);
  498. mod1[index].opentime=time;
  499. mod1[index].lots=lot;
  500. mod1[index].stoploss=sl;
  501. mod1[index].takeprofit=tp;
  502. mod1[index].comment=OrderGetString(ORDER_COMMENT);
  503. mod1[index].ordertype=OrderGetInteger(ORDER_TYPE);
  504. mod1[index].price=OrderGetDouble(ORDER_PRICE_OPEN);
  505. return true;
  506. }
  507. }
  508. }
  509. }
  510. return false;
  511. }
  512. //+------------------------------------------------------------------+
  513. //| |
  514. //+------------------------------------------------------------------+
  515. bool addOrderMaster(ulong ticket, string calledBy)
  516. {
  517. for(int i=0; i<ArraySize(mod1); i++)
  518. {
  519. if(mod1[i].ticket==-1)
  520. {
  521. if(calledBy == "Market")
  522. {
  523. //ulong ticket = PositionGetTicket(orderTicket);
  524. if(PositionSelectByTicket(ticket))
  525. {
  526. //Symbol Updation
  527. string symbol=PositionGetString(POSITION_SYMBOL);
  528. if(suffix!="")
  529. symbol = StringSubstr(symbol,0,StringFind(PositionGetString(POSITION_SYMBOL),suffix,0));
  530. if(prefix!="")
  531. StringReplace(symbol,prefix,"");
  532. //Digits
  533. double digits=getDoubleSymbolInfo(PositionGetString(POSITION_SYMBOL),"digits");
  534. //time
  535. datetime time = (datetime)(PositionGetInteger(POSITION_TIME)-gmtDifference);
  536. mod1[i].opentime=time;
  537. mod1[i].symbol=symbol;
  538. mod1[i].ordertype=PositionGetInteger(POSITION_TYPE);
  539. mod1[i].price=NormalizeDouble(PositionGetDouble(POSITION_PRICE_OPEN),(int)digits);
  540. mod1[i].lots=NormalizeDouble(PositionGetDouble(POSITION_VOLUME),2);
  541. mod1[i].stoploss=NormalizeDouble(PositionGetDouble(POSITION_SL),(int)digits);
  542. mod1[i].takeprofit=NormalizeDouble(PositionGetDouble(POSITION_TP),(int)digits);
  543. mod1[i].ticket=PositionGetInteger(POSITION_TICKET);
  544. mod1[i].magic=(int)PositionGetInteger(POSITION_MAGIC);
  545. mod1[i].comment=PositionGetString(POSITION_COMMENT);
  546. Print("Ticket:",PositionGetInteger(POSITION_TICKET)," stored in index:",i);
  547. return true;
  548. }
  549. }
  550. if(calledBy == "Pending")
  551. {
  552. if(OrderSelect(ticket))
  553. {
  554. string symbol = OrderGetString(ORDER_SYMBOL);
  555. if(suffix!="")
  556. symbol = StringSubstr(symbol,0,StringFind(OrderGetString(ORDER_SYMBOL),suffix,0));
  557. if(prefix!="")
  558. StringReplace(symbol,prefix,"");
  559. //Digits
  560. double digits=getDoubleSymbolInfo(OrderGetString(ORDER_SYMBOL),"digits");
  561. //time
  562. datetime time = (datetime)(OrderGetInteger(ORDER_TIME_SETUP) - gmtDifference);
  563. mod1[i].opentime=time;
  564. mod1[i].symbol=symbol;
  565. mod1[i].ordertype=OrderGetInteger(ORDER_TYPE);
  566. mod1[i].price=NormalizeDouble(OrderGetDouble(ORDER_PRICE_OPEN),(int)digits);
  567. mod1[i].lots=NormalizeDouble(OrderGetDouble(ORDER_VOLUME_CURRENT),2);
  568. mod1[i].stoploss=NormalizeDouble(OrderGetDouble(ORDER_SL),(int)digits);
  569. mod1[i].takeprofit=NormalizeDouble(OrderGetDouble(ORDER_TP),(int)digits);
  570. mod1[i].ticket=OrderGetInteger(ORDER_TICKET);
  571. mod1[i].magic=(int)OrderGetInteger(ORDER_MAGIC);
  572. mod1[i].comment=OrderGetString(ORDER_COMMENT);
  573. Print("Ticket: ",OrderGetInteger(ORDER_TICKET)," stored in index by pending order:",i);
  574. return true;
  575. }
  576. }
  577. }
  578. }
  579. return false;
  580. }
  581. //+------------------------------------------------------------------+
  582. //| |
  583. //+------------------------------------------------------------------+
  584. void readData()
  585. {
  586. if(EnumToString(mode1)=="Client")
  587. {
  588. filehandle=FileOpen("COF.csv",FILE_SHARE_READ|FILE_CSV|FILE_COMMON|FILE_READ|FILE_ANSI|FILE_TXT|FILE_COMMON);
  589. if(filehandle!=INVALID_HANDLE)
  590. {
  591. datetime lastFileModified=(datetime)FileGetInteger(filehandle,FILE_MODIFY_DATE);
  592. long fileSize=FileGetInteger(filehandle,FILE_SIZE);
  593. int a= 0;
  594. if(lastModified==lastFileModified && fileSize==lastFileSize) // lastModified==lastFileModified && fileSize==lastFileSize
  595. {
  596. FileClose(filehandle);
  597. if(counter>=count1 && TerminalInfoInteger(TERMINAL_CONNECTED))
  598. {
  599. if(testCounterVar==testCounter)
  600. {
  601. testCounterVar=0;
  602. }
  603. adminHeartBeat();
  604. counter=0;
  605. }
  606. counter++;
  607. testCounterVar++;
  608. }
  609. else
  610. {
  611. clearOrderArray();
  612. while(!FileIsEnding(filehandle))
  613. {
  614. string OrderToRead = FileReadString(filehandle);
  615. string Order_specs [];
  616. StringSplit(OrderToRead,StringGetCharacter(",",0),Order_specs);
  617. Print("Array Size: ", ArraySize(Order_specs));
  618. if(ArraySize(Order_specs) == 12 || ArraySize(Order_specs) == 13)
  619. {
  620. string symbol = getSymbol(Order_specs[1]);//prefix+Order_specs[1]+suffix;
  621. int orderType=StringToInteger(Order_specs[2]);
  622. if(StringFind(symbol,symbolExclude,0) < 0 &&
  623. (((orderType==POSITION_TYPE_BUY||orderType==ORDER_TYPE_BUY_STOP ||orderType==ORDER_TYPE_SELL_STOP)&& (tradeType==0||tradeType==2)) ||
  624. ((orderType==POSITION_TYPE_SELL||orderType==ORDER_TYPE_BUY_LIMIT ||orderType==ORDER_TYPE_SELL_LIMIT)&& (tradeType==1||tradeType==2)))
  625. )
  626. {
  627. order_array[ArraySize(order_array)-1].symbol = symbol;
  628. order_array[ArraySize(order_array)-1].opentime = StringToTime(Order_specs[0]);
  629. order_array[ArraySize(order_array)-1].price = StringToDouble(Order_specs[3]);
  630. order_array[ArraySize(order_array)-1].ordertype = StringToInteger(Order_specs[2]);
  631. order_array[ArraySize(order_array)-1].lots = StringToDouble(Order_specs[4]);
  632. order_array[ArraySize(order_array)-1].stoploss = StringToDouble(Order_specs[5]);
  633. order_array[ArraySize(order_array)-1].takeprofit = StringToDouble(Order_specs[6]);
  634. order_array[ArraySize(order_array)-1].ticket = StringToInteger(Order_specs[7]);
  635. //Saving master order ticket to order magic number
  636. order_array[ArraySize(order_array)-1].magicNo = StringToInteger(Order_specs[7]);
  637. order_array[ArraySize(order_array)-1].accountBalance=StringToDouble(Order_specs[9]);
  638. order_array[ArraySize(order_array)-1].closedPercentageOfTrade = StringToDouble(Order_specs[10]);
  639. order_array[ArraySize(order_array)-1].contractSize=StringToInteger(Order_specs[11]);
  640. if(ArraySize(Order_specs) == 13)
  641. order_array[ArraySize(order_array)-1].comments=Order_specs[12];
  642. else
  643. order_array[ArraySize(order_array)-1].comments="";
  644. if(ArraySize(Order_specs) == 13)
  645. {
  646. StringReplace(Order_specs[12],"from #","");
  647. StringReplace(Order_specs[12]," ","");
  648. Print(" Order_specs[12] ",Order_specs[12]," order_array[ArraySize(order_array)-1].ticket ",order_array[ArraySize(order_array)-1].ticket);
  649. for(int l=0; l<orderCount; l++)
  650. {
  651. if(cod[l].magic == int(Order_specs[12]))
  652. {
  653. cod[l].magic = order_array[ArraySize(order_array)-1].ticket;
  654. }
  655. }
  656. }
  657. Print(" Symbol: ", order_array[ArraySize(order_array)-1].symbol,
  658. " Open Price: ", order_array[ArraySize(order_array)-1].price,
  659. " Lot: ", order_array[ArraySize(order_array)-1].lots,
  660. " Open time: ", order_array[ArraySize(order_array)-1].opentime,
  661. " Closed %: ", order_array[ArraySize(order_array)-1].closedPercentageOfTrade);
  662. ArrayResize(order_array,ArraySize(order_array)+1);
  663. addToMarketWatch(symbol);
  664. }
  665. }
  666. }
  667. lastModified=lastFileModified;
  668. lastFileSize=fileSize;
  669. FileClose(filehandle);
  670. }
  671. int arraySize=ArraySize(order_array);
  672. if(ArraySize(order_array) == 1) //
  673. {
  674. if(PositionsTotal() > 0)
  675. {
  676. for(int i=PositionsTotal()-1; i>=0; i--)
  677. {
  678. ulong ticket = PositionGetTicket(i);
  679. if(PositionSelectByTicket(ticket))
  680. {
  681. if(history_ticket_present(PositionGetInteger(POSITION_MAGIC)))
  682. if(!trade.PositionClose(ticket))
  683. {
  684. Print(" Order Close Error on No Master Trade: "+IntegerToString(GetLastError()));
  685. }
  686. else
  687. Print(" ------------- Order Close by empty array ------------------ ");
  688. }
  689. }
  690. }
  691. if(OrdersTotal() > 0)
  692. {
  693. for(int i=OrdersTotal()-1; i>=0; i--)
  694. {
  695. ulong ticket = OrderGetTicket(i);
  696. if(OrderSelect(ticket))
  697. {
  698. if(history_ticket_present(OrderGetInteger(ORDER_MAGIC)))
  699. if(!trade.OrderDelete(ticket))
  700. {
  701. Print(" Error in Deleting Pending Order (Empty Array) : "+IntegerToString(GetLastError()));
  702. }
  703. else
  704. Print("Order Close by empty array (Empty Array)");
  705. }
  706. }
  707. }
  708. deleteAllArray();
  709. }
  710. else
  711. {
  712. for(int i=0; i<ArraySize(order_array); i++)
  713. {
  714. //Print(" ------------------------------------------ Ticket: ", order_array[ArraySize(order_array)-1].ticket, " Magic Number: ", order_array[ArraySize(order_array)-1].magicNo, " Array Size: ", ArraySize(order_array), " Index: ", i);
  715. int trade_taken = 2;
  716. int partialCloseOrderPosition=-1;
  717. double percentageToClose = 0;
  718. double closedPercentage = 0.0;
  719. double currentLot = 0.0;
  720. double totalLot = 0;
  721. for(int j=0; j<orderCount; j++)
  722. {
  723. //if(OrderSelect(cod[j].ticket,SELECT_BY_POS))
  724. if(cod[j].ticket!=-1)
  725. {
  726. if(cod[j].magic==order_array[i].ticket)
  727. {
  728. trade_taken = 0;
  729. }
  730. if(PositionSelectByTicket(cod[j].ticket))
  731. {
  732. double sumOfClosed = dealOutLotsCheck(0, PositionGetInteger(POSITION_TICKET));
  733. currentLot = PositionGetDouble(POSITION_VOLUME);
  734. totalLot = sumOfClosed + currentLot;
  735. if(totalLot > 0.0)
  736. closedPercentage = NormalizeDouble((sumOfClosed / totalLot) * 100.0, 1);
  737. }
  738. //Print(" Magic: ", cod[j].magic, " Ticket: ", order_array[i].ticket, " Master Lot: ", cod[j].masterLot, " Client Lot: ", order_array[i].lots);
  739. if(cod[j].magic==order_array[i].ticket)
  740. {
  741. if(closedPercentage < order_array[i].closedPercentageOfTrade)
  742. {
  743. percentageToClose = MathAbs(order_array[i].closedPercentageOfTrade - closedPercentage);
  744. trade_taken=1;
  745. partialCloseOrderPosition=j;
  746. }
  747. }
  748. }
  749. }
  750. if(order_array[i].ticket != -1)
  751. {
  752. if(trade_taken==1)
  753. {
  754. //current order need to close partially
  755. if(partialCloseOrderPosition!=-1)
  756. {
  757. bool isOrderClose=false;
  758. int roundDigit=0;
  759. double step=SymbolInfoDouble(cod[partialCloseOrderPosition].symbol,SYMBOL_VOLUME_STEP);
  760. while(step<1)
  761. {
  762. roundDigit++;
  763. step=step*10;
  764. }
  765. double lotClosePer = NormalizeDouble((totalLot * percentageToClose) / 100, roundDigit);
  766. if(percentageToClose > 0 && lotClosePer > SymbolInfoDouble(cod[partialCloseOrderPosition].symbol,SYMBOL_VOLUME_MIN))
  767. {
  768. if(!trade.PositionClosePartial(cod[partialCloseOrderPosition].ticket, lotClosePer))
  769. {
  770. Print("Partial order did not close:",cod[partialCloseOrderPosition].ticket, " Lot To Close is: ", lotClosePer);
  771. }
  772. else
  773. {
  774. isOrderClose=true;
  775. Print("Order Partial Close. currentLot Was =", currentLot,
  776. " Percentage to close = ", percentageToClose,
  777. " Lot I am Going To close = ", lotClosePer);
  778. }
  779. }
  780. }
  781. }
  782. else
  783. if(trade_taken == 2)
  784. {
  785. int diff1=((int)TimeCurrent()-(int)order_array[i].opentime)-gmtDifference;// ,diff2=TimeSeconds(TimeCurrent()-order_array[i].opentime);
  786. if(diff1 <= sec)
  787. {
  788. Print("Symbol: ",order_array[i].opentime," ",diff1," <= ",sec);
  789. trade.SetExpertMagicNumber(IntegerToString(order_array[i].ticket));
  790. trade.SetDeviationInPoints(10);
  791. trade.SetTypeFilling(ORDER_FILLING_IOC);
  792. trade.LogLevel(LOG_LEVEL_ALL);
  793. trade.SetAsyncMode(false);
  794. if(order_array[i].ordertype == ORDER_TYPE_BUY)
  795. {
  796. double tempSlip=MathAbs(order_array[i].price- SymbolInfoDouble(order_array[i].symbol,SYMBOL_ASK))/SymbolInfoDouble(order_array[i].symbol,SYMBOL_POINT);
  797. if((MathAbs(order_array[i].price-SymbolInfoDouble(order_array[i].symbol,SYMBOL_ASK))/SymbolInfoDouble(order_array[i].symbol,SYMBOL_POINT)) <= slip*10)
  798. {
  799. double lotsize = getLotSize(order_array[i].symbol, order_array[i].accountBalance, order_array[i].lots, order_array[i].contractSize);
  800. double Stoploss=0.0;
  801. double ask=NormalizeDouble(SymbolInfoDouble(order_array[i].symbol,SYMBOL_ASK),(int)SymbolInfoInteger(order_array[i].symbol,SYMBOL_DIGITS));
  802. if(trade.PositionOpen(order_array[i].symbol,ORDER_TYPE_BUY,lotsize,ask,order_array[i].stoploss,order_array[i].takeprofit,""))
  803. {
  804. if(addOrderMaster(trade.ResultOrder(),order_array[i].ticket,order_array[i].lots, "Market"))
  805. {
  806. Print(" Buy Order Ticket:",trade.ResultOrder()," Stored!!!");
  807. }
  808. else
  809. {
  810. //Print("Order Ticket is not stotred: ",trade.ResultOrder()," Error is: ", GetLastError());
  811. }
  812. }
  813. else
  814. {
  815. Print("Copy Buy Order Send Error: "+IntegerToString(GetLastError()));
  816. }
  817. }
  818. }
  819. if(order_array[i].ordertype == ORDER_TYPE_SELL)
  820. {
  821. if((MathAbs(order_array[i].price-SymbolInfoDouble(order_array[i].symbol,SYMBOL_BID))/SymbolInfoDouble(order_array[i].symbol,SYMBOL_POINT)) <= slip*10)
  822. {
  823. double lotsize = getLotSize(order_array[i].symbol, order_array[i].accountBalance, order_array[i].lots, order_array[i].contractSize);
  824. double Stoploss=0.0;
  825. double bid=NormalizeDouble(SymbolInfoDouble(order_array[i].symbol,SYMBOL_BID),(int)SymbolInfoInteger(order_array[i].symbol,SYMBOL_DIGITS));
  826. if(trade.PositionOpen(order_array[i].symbol,ORDER_TYPE_SELL,lotsize,bid,order_array[i].stoploss,order_array[i].takeprofit,""))
  827. {
  828. if(addOrderMaster(trade.ResultOrder(),order_array[i].ticket,order_array[i].lots, "Market"))
  829. {
  830. Print(" Sell Order Ticket:",trade.ResultOrder()," Stored!!!");
  831. }
  832. }
  833. else
  834. {
  835. Print("Copy Buy Order Send Error: "+IntegerToString(GetLastError()));
  836. }
  837. }
  838. }
  839. if(order_array[i].ordertype == ORDER_TYPE_BUY_STOP)
  840. {
  841. // Not Checking Slippage
  842. double lotsize = getLotSize(order_array[i].symbol, order_array[i].accountBalance, order_array[i].lots, order_array[i].contractSize);
  843. if(trade.BuyStop(lotsize, order_array[i].price, order_array[i].symbol, order_array[i].stoploss, order_array[i].takeprofit, 0, 0, ""))
  844. {
  845. if(addOrderMaster(trade.ResultOrder(),order_array[i].ticket,order_array[i].lots, "Pending"))
  846. {
  847. Print("Order Ticket Buy Stop:",trade.ResultOrder()," Stored!!!");
  848. }
  849. }
  850. else
  851. {
  852. Print("Error in Order Buy Stop Order: "+Symbol()+" ",GetLastError());
  853. }
  854. }
  855. if(order_array[i].ordertype == ORDER_TYPE_SELL_STOP)
  856. {
  857. double lotsize = getLotSize(order_array[i].symbol, order_array[i].accountBalance, order_array[i].lots, order_array[i].contractSize);
  858. if(trade.SellStop(lotsize, order_array[i].price, order_array[i].symbol, order_array[i].stoploss, order_array[i].takeprofit, 0, 0, ""))
  859. {
  860. if(addOrderMaster(trade.ResultOrder(),order_array[i].ticket,order_array[i].lots, "Pending"))
  861. {
  862. Print("Order Ticket Sell Stop:",trade.ResultOrder()," Stored!!!");
  863. }
  864. }
  865. else
  866. {
  867. Print("Error in Order Sell Stop Order: "+Symbol()+" ",GetLastError());
  868. }
  869. }
  870. if(order_array[i].ordertype == ORDER_TYPE_BUY_LIMIT)
  871. {
  872. double lotsize = getLotSize(order_array[i].symbol, order_array[i].accountBalance, order_array[i].lots, order_array[i].contractSize);
  873. if(trade.BuyLimit(lotsize, order_array[i].price, order_array[i].symbol, order_array[i].stoploss, order_array[i].takeprofit, 0, 0, ""))
  874. {
  875. if(addOrderMaster(trade.ResultOrder(),order_array[i].ticket,order_array[i].lots, "Pending"))
  876. {
  877. Print("Order Ticket Buy Limit:",trade.ResultOrder()," Stored!!!");
  878. }
  879. }
  880. else
  881. {
  882. Print("Error in Order Buy Limit: "+Symbol()+" ",GetLastError());
  883. }
  884. }
  885. if(order_array[i].ordertype == ORDER_TYPE_SELL_LIMIT)
  886. {
  887. double lotsize = getLotSize(order_array[i].symbol, order_array[i].accountBalance, order_array[i].lots, order_array[i].contractSize);
  888. if(trade.SellLimit(lotsize, order_array[i].price, order_array[i].symbol, order_array[i].stoploss, order_array[i].takeprofit, 0, 0, ""))
  889. {
  890. if(addOrderMaster(trade.ResultOrder(),order_array[i].ticket,order_array[i].lots, "Pending"))
  891. {
  892. Print("Order Ticket Sell Limit: ",trade.ResultOrder()," Stored!!! ", " Tp: ", order_array[i].takeprofit, " Sl: ", order_array[i].stoploss);
  893. }
  894. }
  895. else
  896. {
  897. Print("Error in Order Sell Limit: "+Symbol()+" ",GetLastError());
  898. }
  899. }
  900. }
  901. }
  902. }
  903. }
  904. for(int i=0; i<orderCount; i++)
  905. {
  906. bool trade_close = true;
  907. if(PositionSelectByTicket(cod[i].ticket))
  908. {
  909. for(int j=0; j<ArraySize(order_array); j++)
  910. {
  911. if(cod[i].magic == (order_array[j].ticket))
  912. {
  913. int digitss = getDoubleSymbolInfo(PositionGetString(POSITION_SYMBOL), "digits");
  914. trade_close = false;
  915. //Print("TP/SL | norm cod TP=",NormalizeDouble(cod[i].takeprofit,digitss),
  916. // " norm order TP=",NormalizeDouble(order_array[j].takeprofit,digitss),
  917. // " | norm cod SL=",NormalizeDouble(cod[i].stoploss,digitss),
  918. // " norm order SL=",NormalizeDouble(order_array[j].stoploss,digitss));
  919. if(NormalizeDouble(cod[i].takeprofit, digitss) != NormalizeDouble(order_array[j].takeprofit, digitss))
  920. {
  921. if(NormalizeDouble(order_array[j].takeprofit, digitss) == NormalizeDouble(PositionGetDouble(POSITION_TP), digitss))
  922. {
  923. Print(" Client Position Tp Was Manually Modified. ");
  924. cod[i].takeprofit=NormalizeDouble(order_array[j].takeprofit, digitss);
  925. }
  926. }
  927. if(NormalizeDouble(cod[i].stoploss, digitss) != NormalizeDouble(order_array[j].stoploss, digitss))
  928. {
  929. if(NormalizeDouble(order_array[j].stoploss, digitss) == NormalizeDouble(PositionGetDouble(POSITION_SL), digitss))
  930. {
  931. Print(" Client Position SL Was Manually Modified. ");
  932. cod[i].stoploss = NormalizeDouble(order_array[j].stoploss, digitss);
  933. }
  934. }
  935. if(NormalizeDouble(cod[i].takeprofit, digitss) != NormalizeDouble(order_array[j].takeprofit, digitss) || NormalizeDouble(cod[i].stoploss, digitss) != NormalizeDouble(order_array[j].stoploss, digitss))
  936. {
  937. if(trade.PositionModify(PositionGetInteger(POSITION_TICKET),order_array[j].stoploss,order_array[j].takeprofit))
  938. {
  939. Print("Order modified ticket:",PositionGetInteger(POSITION_TICKET));
  940. cod[i].takeprofit=NormalizeDouble(order_array[j].takeprofit, digitss);
  941. cod[i].stoploss=NormalizeDouble(order_array[j].stoploss, digitss);
  942. }
  943. else
  944. {
  945. //ExpertRemove();
  946. Print("Order not modified error:",GetLastError());
  947. }
  948. }
  949. }
  950. }
  951. if(trade_close == true)
  952. {
  953. if(PositionGetInteger(POSITION_TYPE)== ORDER_TYPE_BUY)
  954. {
  955. if(!trade.PositionClose(PositionGetInteger(POSITION_TICKET)))
  956. {
  957. Print("Buy Order Close Error on Master Trade Close: "+IntegerToString(GetLastError()));
  958. }
  959. else
  960. {
  961. Print("Order close by no master copy of trade");
  962. cod[i].ticket=-1;
  963. }
  964. }
  965. if(PositionGetInteger(POSITION_TYPE)== ORDER_TYPE_SELL)
  966. {
  967. if(!trade.PositionClose(PositionGetInteger(POSITION_TICKET)))
  968. {
  969. Print("Sell Order Close Error on Master Trade Close: "+IntegerToString(GetLastError()));
  970. }
  971. else
  972. {
  973. Print("Order close by no master copy of trade");
  974. cod[i].ticket=-1;
  975. }
  976. }
  977. }
  978. }
  979. if(OrderSelect(cod[i].ticket))
  980. {
  981. for(int j=0; j<ArraySize(order_array); j++)
  982. {
  983. if(cod[i].magic == (order_array[j].ticket))
  984. {
  985. trade_close = false;
  986. int digitss = (int)getDoubleSymbolInfo(PositionGetString(POSITION_SYMBOL), "digits");
  987. if(NormalizeDouble(cod[i].takeprofit, digitss) != NormalizeDouble(order_array[j].takeprofit, digitss))
  988. {
  989. if(NormalizeDouble(order_array[j].takeprofit, digitss) == NormalizeDouble(OrderGetDouble(ORDER_TP), digitss))
  990. {
  991. Print(" Pending Master Position Tp Was Manually Modified. ");
  992. cod[i].takeprofit=NormalizeDouble(order_array[j].takeprofit, digitss);
  993. }
  994. }
  995. if(NormalizeDouble(cod[i].stoploss, digitss) != NormalizeDouble(order_array[j].stoploss, digitss))
  996. {
  997. if(NormalizeDouble(order_array[j].stoploss, digitss) == NormalizeDouble(OrderGetDouble(ORDER_SL), digitss))
  998. {
  999. Print(" Pending Master Position SL Was Manually Modified. ");
  1000. cod[i].stoploss = NormalizeDouble(order_array[j].stoploss, digitss);
  1001. }
  1002. }
  1003. if(NormalizeDouble(cod[i].price, digitss) != NormalizeDouble(order_array[j].price, digitss))
  1004. {
  1005. if(NormalizeDouble(order_array[j].price, digitss) == NormalizeDouble(OrderGetDouble(ORDER_PRICE_OPEN), digitss))
  1006. {
  1007. Print(" Pending Master Position Price Was Manually Modified. ");
  1008. cod[i].price = NormalizeDouble(order_array[j].price, digitss);
  1009. }
  1010. }
  1011. // if(OrderGetDouble(ORDER_TP)!=order_array[j].takeprofit || OrderGetDouble(ORDER_SL)!=order_array[j].stoploss || OrderGetDouble(ORDER_PRICE_OPEN)!=order_array[j].price)
  1012. 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))
  1013. {
  1014. if(trade.OrderModify(OrderGetInteger(ORDER_TICKET),order_array[j].price,order_array[j].stoploss,order_array[j].takeprofit, 0, 0, 0))
  1015. {
  1016. Print("Pending Order modified ticket:",PositionGetInteger(POSITION_TICKET));
  1017. cod[i].takeprofit=order_array[j].takeprofit;
  1018. cod[i].stoploss=order_array[j].stoploss;
  1019. cod[i].price = order_array[j].price;
  1020. }
  1021. else
  1022. {
  1023. Print("Order not modified error:",GetLastError());
  1024. }
  1025. }
  1026. }
  1027. }
  1028. if(trade_close == true)
  1029. {
  1030. 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)
  1031. {
  1032. if(!trade.OrderDelete(OrderGetInteger(ORDER_TICKET)))
  1033. {
  1034. Print("Error in Deleting Pending Order: "+IntegerToString(GetLastError()));
  1035. }
  1036. else
  1037. {
  1038. Print("Pending Order Deleted. Ticket is: ", cod[i].ticket);
  1039. cod[i].ticket=-1;
  1040. }
  1041. }
  1042. }
  1043. }
  1044. }
  1045. }
  1046. }
  1047. }
  1048. }
  1049. //+------------------------------------------------------------------+
  1050. //| |
  1051. //+------------------------------------------------------------------+
  1052. void print()
  1053. {
  1054. for(int i=0; i<orderCount; i++)
  1055. {
  1056. if(cod[i].ticket!=-1)
  1057. {
  1058. Print("Ticket : ",cod[i].ticket," OPen price: ",cod[i].price, " Type: ",cod[i].ordertype);
  1059. }
  1060. }
  1061. }
  1062. //+------------------------------------------------------------------+
  1063. //| |
  1064. //+------------------------------------------------------------------+
  1065. bool isOrderThere(ulong ticket,int &index)
  1066. {
  1067. for(int i=0; i<ArraySize(mod1); i++)
  1068. {
  1069. if(ticket != -1)
  1070. {
  1071. if(mod1[i].ticket==ticket)
  1072. {
  1073. index=i;
  1074. return true;
  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].magic=0;
  1091. mod1[i].price=-1;
  1092. mod1[i].symbol="";
  1093. mod1[i].ordertype=-1;
  1094. mod1[i].lots=0;
  1095. mod1[i].stoploss=0;
  1096. mod1[i].takeprofit=0;
  1097. }
  1098. }
  1099. }
  1100. //+------------------------------------------------------------------+
  1101. //| |
  1102. //+------------------------------------------------------------------+
  1103. void deleteAllArray()
  1104. {
  1105. for(int i=0; i<orderCount; i++)
  1106. {
  1107. if(cod[i].ticket!=-1)
  1108. {
  1109. cod[i].ticket=-1;
  1110. }
  1111. }
  1112. }
  1113. //+------------------------------------------------------------------+
  1114. //| |
  1115. //+------------------------------------------------------------------+
  1116. double dealOutLotsCheck(datetime cutOffTimeIs, ulong positionId)
  1117. {
  1118. double sumOfLots = 0.0;
  1119. if(HistorySelect(cutOffTimeIs,LONG_MAX))
  1120. {
  1121. int totalDeals = HistoryDealsTotal();
  1122. for(int i = 0; i < totalDeals; i++)
  1123. {
  1124. ulong dealTicket = HistoryDealGetTicket(i);
  1125. ulong dealPositionID = (ulong)HistoryDealGetInteger(dealTicket, DEAL_POSITION_ID);
  1126. if(HistoryDealGetInteger(dealTicket, DEAL_ENTRY) == DEAL_ENTRY_OUT
  1127. && dealPositionID == positionId)
  1128. {
  1129. sumOfLots += HistoryDealGetDouble(dealTicket, DEAL_VOLUME);
  1130. }
  1131. }
  1132. }
  1133. return sumOfLots;
  1134. }
  1135. //+------------------------------------------------------------------+
  1136. //| |
  1137. //+------------------------------------------------------------------+
  1138. bool addOrderMaster(ulong ticket,ulong magic,double lot, string calledBy)
  1139. {
  1140. Print("in addOrderMaster: ", ticket);
  1141. bool notFoundPosition=false;//Use to look in to the order loop in case order isn't converted
  1142. if(OrderSelect(ticket))
  1143. {
  1144. Print("Inside order selection:");
  1145. Print("Order State:",(ENUM_ORDER_STATE)OrderGetInteger(ORDER_STATE));
  1146. Print("Order Time done:",(datetime)OrderGetInteger(ORDER_TIME_DONE));
  1147. Print("Order Type:",(ENUM_ORDER_TYPE)OrderGetInteger(ORDER_TYPE));
  1148. }
  1149. else
  1150. if(HistoryOrderSelect(ticket))
  1151. {
  1152. Print("Inside history order selection:");
  1153. Print("Order State:",(ENUM_ORDER_STATE)HistoryOrderGetInteger(ticket,ORDER_STATE));
  1154. Print("Order Time done:",(datetime)HistoryOrderGetInteger(ticket,ORDER_TIME_DONE));
  1155. Print("Order Type:",(ENUM_ORDER_TYPE)HistoryOrderGetInteger(ticket,ORDER_TYPE));
  1156. }
  1157. else
  1158. {
  1159. PrintFormat("OrderSelect(%I64u) failed. Error %d", ticket, GetLastError());
  1160. }
  1161. for(int i=0; i<orderCount; i++)
  1162. {
  1163. if(cod[i].ticket==-1)
  1164. {
  1165. if(calledBy == "Market")
  1166. {
  1167. if(PositionSelectByTicket(ticket))
  1168. {
  1169. cod[i].ticket=PositionGetInteger(POSITION_TICKET);
  1170. cod[i].price=PositionGetDouble(POSITION_PRICE_OPEN);
  1171. cod[i].symbol=PositionGetString(POSITION_SYMBOL);
  1172. cod[i].ordertype=PositionGetInteger(POSITION_TYPE);
  1173. cod[i].lots=PositionGetDouble(POSITION_VOLUME);
  1174. cod[i].stoploss=PositionGetDouble(POSITION_SL);
  1175. cod[i].takeprofit=PositionGetDouble(POSITION_TP);
  1176. cod[i].magic=PositionGetInteger(POSITION_MAGIC);
  1177. cod[i].comments=PositionGetString(POSITION_COMMENT);
  1178. cod[i].masterLot = lot;
  1179. Print("Ticket stored in master:",PositionGetInteger(POSITION_TICKET)," stored in index:",i);
  1180. Print("========== CLIENT ORDER STORED ==========");
  1181. Print(" index=", i,
  1182. " | master_magic=", cod[i].magic,
  1183. " | client_ticket=", cod[i].ticket,
  1184. " | symbol=", cod[i].symbol,
  1185. " | order_type=", cod[i].ordertype,
  1186. " | open_price=", DoubleToString(cod[i].price, _Digits),
  1187. " | lots=", DoubleToString(cod[i].lots, 2),
  1188. " | master_lot=", DoubleToString(cod[i].masterLot, 2),
  1189. " | sl=", DoubleToString(cod[i].stoploss, _Digits),
  1190. " | tp=", DoubleToString(cod[i].takeprofit, _Digits),
  1191. " | comment=", cod[i].comments);
  1192. Print("========================================");
  1193. return true;
  1194. }
  1195. else
  1196. {
  1197. Print("Ticket:",ticket," not found in the position list");
  1198. notFoundPosition=true;
  1199. }
  1200. }
  1201. if(calledBy == "Pending" || notFoundPosition)
  1202. {
  1203. if(OrderSelect(ticket))
  1204. {
  1205. cod[i].ticket=OrderGetInteger(ORDER_TICKET);
  1206. cod[i].price=OrderGetDouble(ORDER_PRICE_OPEN);
  1207. cod[i].symbol=OrderGetString(ORDER_SYMBOL);
  1208. cod[i].ordertype=OrderGetInteger(ORDER_TYPE);
  1209. cod[i].lots=OrderGetDouble(ORDER_VOLUME_CURRENT);
  1210. cod[i].stoploss=OrderGetDouble(ORDER_SL);
  1211. cod[i].takeprofit=OrderGetDouble(ORDER_TP);
  1212. cod[i].magic=OrderGetInteger(ORDER_MAGIC);
  1213. cod[i].comments=OrderGetString(ORDER_COMMENT);
  1214. cod[i].masterLot = lot;
  1215. Print("Pending Order Ticket in master:",OrderGetInteger(ORDER_TICKET)," stored in index:",i);
  1216. return true;
  1217. }
  1218. else
  1219. {
  1220. Print("Ticket:",ticket," not found in the order list");
  1221. }
  1222. }
  1223. }
  1224. }
  1225. return false;
  1226. }
  1227. //+------------------------------------------------------------------+
  1228. //+------------------------------------------------------------------+
  1229. //| |
  1230. //+------------------------------------------------------------------+
  1231. double getDoubleSymbolInfo(string symbol,string info)
  1232. {
  1233. long digits=8;
  1234. //Symbol without the suffix and prefix
  1235. string updatedSymbol=symbol;
  1236. if(suffix!="")
  1237. updatedSymbol = StringSubstr(updatedSymbol,0,StringFind(updatedSymbol,suffix,0));
  1238. if(prefix!="")
  1239. StringReplace(updatedSymbol,prefix,"");
  1240. //Digits calculation could be used in other calculations
  1241. digits = SymbolInfoInteger(symbol,SYMBOL_DIGITS);
  1242. if(digits==0)
  1243. {
  1244. digits=SymbolInfoInteger(updatedSymbol,SYMBOL_DIGITS);
  1245. if(digits==0)
  1246. digits=8;
  1247. }
  1248. if(info=="digits")
  1249. {
  1250. return (double)digits;
  1251. }
  1252. else
  1253. if(info=="point" || info=="points")
  1254. {
  1255. double points=SymbolInfoDouble(symbol, SYMBOL_POINT);
  1256. if(points==0)
  1257. {
  1258. points=SymbolInfoDouble(updatedSymbol,SYMBOL_POINT);
  1259. if(points==0)
  1260. points=0.00001;
  1261. }
  1262. return points;
  1263. }
  1264. else
  1265. if(info=="ask")
  1266. {
  1267. double ask = SymbolInfoDouble(symbol, SYMBOL_ASK);
  1268. if(ask==0)
  1269. {
  1270. ask=SymbolInfoDouble(updatedSymbol,SYMBOL_ASK);
  1271. if(ask==0)
  1272. ask=0.00001;
  1273. }
  1274. return NormalizeDouble(ask,(int)digits);
  1275. }
  1276. else
  1277. if(info=="bid")
  1278. {
  1279. double bid=SymbolInfoDouble(symbol, SYMBOL_BID);
  1280. if(bid==0)
  1281. {
  1282. bid=SymbolInfoDouble(updatedSymbol,SYMBOL_BID);
  1283. if(bid==0)
  1284. bid=0.00001;
  1285. }
  1286. return NormalizeDouble(bid,(int)digits);
  1287. }
  1288. else
  1289. if(info=="contract"||info=="contractSize")
  1290. {
  1291. double contract=SymbolInfoDouble(symbol,SYMBOL_TRADE_CONTRACT_SIZE);
  1292. if(contract==0)
  1293. {
  1294. contract=SymbolInfoDouble(updatedSymbol,SYMBOL_TRADE_CONTRACT_SIZE);
  1295. }
  1296. return contract;
  1297. }
  1298. else
  1299. if(info=="lotStep")
  1300. {
  1301. double step=SymbolInfoDouble(symbol, SYMBOL_VOLUME_STEP);
  1302. if(step==0)
  1303. {
  1304. step=SymbolInfoDouble(updatedSymbol,SYMBOL_VOLUME_STEP);
  1305. }
  1306. return step;
  1307. }
  1308. else
  1309. if(info=="minLot")
  1310. {
  1311. double minLot=SymbolInfoDouble(symbol, SYMBOL_VOLUME_MIN);
  1312. if(minLot==0)
  1313. {
  1314. minLot = SymbolInfoDouble(updatedSymbol, SYMBOL_VOLUME_MIN);
  1315. }
  1316. return minLot;
  1317. }
  1318. else
  1319. if(info=="maxLot")
  1320. {
  1321. double maxLot=SymbolInfoDouble(symbol,SYMBOL_VOLUME_MAX);
  1322. if(maxLot==0)
  1323. {
  1324. maxLot=SymbolInfoDouble(updatedSymbol,SYMBOL_VOLUME_MAX);
  1325. }
  1326. return maxLot;
  1327. }
  1328. return 0;
  1329. }
  1330. //+------------------------------------------------------------------+
  1331. //| |
  1332. //+------------------------------------------------------------------+
  1333. string getSymbol(string symbol)
  1334. {
  1335. if(mappingSymbol!="")
  1336. {
  1337. string symbollist[];
  1338. StringSplit(mappingSymbol,';',symbollist);
  1339. for(int i=0; i<ArraySize(symbollist); i++)
  1340. {
  1341. string symbolPairs[];
  1342. StringSplit(symbollist[i],',',symbolPairs);
  1343. if(ArraySize(symbolPairs)==2)
  1344. {
  1345. if(symbol==symbolPairs[0])
  1346. return symbolPairs[1];
  1347. }
  1348. }
  1349. }
  1350. else
  1351. {
  1352. return prefix+symbol+suffix;
  1353. }
  1354. return prefix+symbol+suffix;
  1355. }
  1356. //+------------------------------------------------------------------+
  1357. //| |
  1358. //+------------------------------------------------------------------+
  1359. double getLotSize(string symbol,double masterAccountBalance,double masterLot,int masterContractSize)
  1360. {
  1361. double lotsize = fixed;
  1362. Print("------> Symbol:",symbol," master Account balance:",masterAccountBalance," master lot:",masterLot," master Contract:",masterContractSize);
  1363. if(lotoption == mul)
  1364. {
  1365. lotsize = NormalizeDouble(masterLot*mult,2);
  1366. }
  1367. else
  1368. if(lotoption == Balance)
  1369. {
  1370. lotsize=((AccountInfoDouble(ACCOUNT_BALANCE)/masterAccountBalance)*masterLot)*Bmult;
  1371. }
  1372. else
  1373. if(lotoption == slaveLotCal)
  1374. {
  1375. lotsize = masterLot * (maxDd / recoveryAmount);
  1376. }
  1377. Print("Before Lot Size: ",lotsize);
  1378. if(contractChk)
  1379. {
  1380. int clientContractSize=getDoubleSymbolInfo(symbol,"contract");
  1381. Print("Client Contract size:",clientContractSize);
  1382. if(masterContractSize!=0 && clientContractSize!=0)
  1383. {
  1384. lotsize=((masterContractSize*1.0)/clientContractSize)*lotsize;
  1385. }
  1386. }
  1387. int roundDigit=0;
  1388. double step=getDoubleSymbolInfo(symbol, "lotStep");
  1389. while(step<1)
  1390. {
  1391. roundDigit++;
  1392. step=step*10;
  1393. }
  1394. Print("Round Digits:",roundDigit);
  1395. lotsize = NormalizeDouble(lotsize,roundDigit);
  1396. if(lotsize<getDoubleSymbolInfo(symbol,"minLot"))
  1397. lotsize=getDoubleSymbolInfo(symbol,"minLot");
  1398. else
  1399. if(lotsize>getDoubleSymbolInfo(symbol,"maxLot"))
  1400. lotsize=getDoubleSymbolInfo(symbol,"maxLot");
  1401. Print("Lot Size: ",lotsize);
  1402. return lotsize;
  1403. }
  1404. //+------------------------------------------------------------------+
  1405. //| |
  1406. //+------------------------------------------------------------------+
  1407. void adminHeartBeat()
  1408. {
  1409. string headers = "apikey:"+localApiKey+"\r\naccept: */* \r\nContent-Type: application/json\r\nUser-Agent: MetaTraderApi";
  1410. string url =localHB_req_link;// Request_link+(string)accountNumber;
  1411. bool isPost;
  1412. int timeout = 100000;
  1413. string lastConnected=TimeToString(TimeCurrent());
  1414. StringReplace(lastConnected,".","-");
  1415. StringReplace(lastConnected," ","T");
  1416. string gmtTime=TimeToString(TimeGMT());
  1417. string jsonData="{\"sLogin\":\""+(string)accountNumber+"\",\"sServer\":\""+clientServer+"\",\"sVersion\":\"5\" ,\"sLastConnected\":\""+gmtTime+"\"}";//\",\"url\":"+"\""+url+"\""+headers+"}";
  1418. uchar data[];
  1419. StringToCharArray(jsonData, data, 0, StringLen(jsonData));
  1420. // Print("Making the heart beat request to the local host");
  1421. POST_function(url,headers,timeout,data,isPost);
  1422. }
  1423. //+------------------------------------------------------------------+
  1424. //| |
  1425. //+------------------------------------------------------------------+
  1426. bool POST_function(string url, string headers, int timeout, uchar &data[], bool &IsPost)
  1427. {
  1428. ResetLastError(); // clear previous error
  1429. static int lastErrorPrinted = 0;
  1430. uchar result[]; // use uchar for WebRequest result
  1431. string resultHeaders;
  1432. int res = WebRequest("POST", url, headers, timeout, data, result, resultHeaders);
  1433. if(res == 200 || res == 201)
  1434. {
  1435. Print("***Request success. HTTP response code POST: ", res);
  1436. string result_string = CharArrayToString(result);
  1437. Print("content POST: ", result_string);
  1438. lastErrorPrinted = 0; // reset remembered error on success
  1439. IsPost = true;
  1440. return true;
  1441. }
  1442. else
  1443. {
  1444. int err = GetLastError(); // read the error once
  1445. // only print when there's a real error and it's different from last time
  1446. if(err != 0 && err != lastErrorPrinted)
  1447. {
  1448. Print("Get last error: ", err);
  1449. Print("***Request failed. HTTP response code: ", res);
  1450. string result_string = CharArrayToString(result);
  1451. Print("content: ", result_string);
  1452. lastErrorPrinted = err; // remember this error so we don't spam it
  1453. }
  1454. IsPost = false;
  1455. return false;
  1456. }
  1457. }
  1458. //+------------------------------------------------------------------+
  1459. //| |
  1460. //+------------------------------------------------------------------+
  1461. void clearOrderArray()
  1462. {
  1463. //Resize to one
  1464. ArrayResize(order_array,1);
  1465. //Clear all data
  1466. order_array[0].symbol = "";
  1467. order_array[0].opentime = 0;
  1468. order_array[0].price = 0;
  1469. order_array[0].ordertype = 0;
  1470. order_array[0].lots = 0;
  1471. order_array[0].stoploss = 0;
  1472. order_array[0].takeprofit = 0;
  1473. order_array[0].ticket = -1;
  1474. order_array[0].magicNo = 0;
  1475. order_array[0].accountBalance=0;
  1476. order_array[0].contractSize=0;
  1477. order_array[0].comments="";
  1478. order_array[0].closedPercentageOfTrade = 0;
  1479. }
  1480. //+------------------------------------------------------------------+
  1481. //| |
  1482. //+------------------------------------------------------------------+
  1483. void mapHistory()
  1484. {
  1485. for(int i=0; i<PositionsTotal(); i++)
  1486. {
  1487. ulong ticket = PositionGetTicket(i);
  1488. if(PositionSelectByTicket(ticket))
  1489. {
  1490. if(PositionGetInteger(POSITION_MAGIC) > 999)
  1491. {
  1492. addOrderMaster(PositionGetInteger(POSITION_TICKET), PositionGetInteger(POSITION_MAGIC), PositionGetDouble(POSITION_VOLUME), "Market");
  1493. }
  1494. }
  1495. }
  1496. for(int i=0; i<OrdersTotal(); i++)
  1497. {
  1498. ulong ticket = OrderGetTicket(i);
  1499. if(OrderSelect(ticket))
  1500. {
  1501. if(OrderGetInteger(ORDER_MAGIC) > 999)
  1502. {
  1503. addOrderMaster(OrderGetInteger(ORDER_TICKET), OrderGetInteger(ORDER_MAGIC), OrderGetDouble(ORDER_VOLUME_CURRENT), "Pending");
  1504. }
  1505. }
  1506. }
  1507. }
  1508. //+------------------------------------------------------------------+
  1509. //| |
  1510. //+------------------------------------------------------------------+
  1511. bool addToMarketWatch(string symbol)
  1512. {
  1513. Print("Symbol:",symbol);
  1514. bool result=SymbolSelect(symbol,true);
  1515. if(result)
  1516. {
  1517. Print("Successfully added the symbol or already there:", symbol);
  1518. return true;
  1519. }
  1520. else
  1521. {
  1522. Print("Error in adding symbol:",symbol);
  1523. }
  1524. return false;
  1525. }
  1526. //+------------------------------------------------------------------+
  1527. //| |
  1528. //+------------------------------------------------------------------+
  1529. void read_history_file()
  1530. {
  1531. string file_name = "history_trades.csv";
  1532. if(!FileIsExist(file_name, FILE_COMMON))
  1533. {
  1534. Print("File not found: ", file_name);
  1535. return;
  1536. }
  1537. int h = FileOpen(file_name, FILE_SHARE_READ|FILE_CSV|FILE_COMMON|FILE_READ|FILE_ANSI|FILE_TXT|FILE_COMMON);
  1538. if(h == INVALID_HANDLE)
  1539. {
  1540. Print("Error opening file: ", file_name, " Err:", GetLastError());
  1541. return;
  1542. }
  1543. datetime lastFileModified=(datetime)FileGetInteger(h,FILE_MODIFY_DATE);
  1544. long fileSize=FileGetInteger(h,FILE_SIZE);
  1545. if(lastModified1==lastFileModified && fileSize==lastFileSize1)
  1546. {
  1547. FileClose(h);
  1548. return;
  1549. }
  1550. else
  1551. {
  1552. ulong fileTickets[];
  1553. ArrayResize(fileTickets, 0);
  1554. while(!FileIsEnding(h))
  1555. {
  1556. string line = FileReadString(h);
  1557. // split by comma
  1558. string parts[];
  1559. int count = StringSplit(line,',', parts);
  1560. if(count >= 2)
  1561. {
  1562. // convert to integers
  1563. ulong ticket = StringToInteger(parts[0]);
  1564. ulong magic = StringToInteger(parts[1]);
  1565. int newSize = ArraySize(fileTickets) + 1;
  1566. ArrayResize(fileTickets, newSize);
  1567. fileTickets[newSize - 1] = ticket;
  1568. if(!history_ticket_present(ticket))
  1569. add_history_ticket(ticket, magic);
  1570. }
  1571. else
  1572. {
  1573. // Print("Skipped malformed line while reading ", file_name, " : ", line);
  1574. }
  1575. }
  1576. FileClose(h);
  1577. lastModified1=lastFileModified;
  1578. lastFileSize1=fileSize;
  1579. for(int i = 0; i < MaxOrders; i++)
  1580. {
  1581. ulong tk = historyTradeStore[i].ticket;
  1582. if(tk == -1)
  1583. continue;
  1584. bool found = false;
  1585. for(int j = 0; j < ArraySize(fileTickets); j++)
  1586. {
  1587. if(fileTickets[j] == tk)
  1588. {
  1589. found = true;
  1590. break;
  1591. }
  1592. }
  1593. if(!found)
  1594. {
  1595. Print("Removing ticket not found in file: ", tk, " index=", i);
  1596. historyTradeStore[i].ticket = -1;
  1597. historyTradeStore[i].magic = 0;
  1598. }
  1599. }
  1600. }
  1601. }
  1602. //+------------------------------------------------------------------+
  1603. //| |
  1604. //+------------------------------------------------------------------+
  1605. void add_history_ticket(ulong ticket, ulong magicIs)
  1606. {
  1607. for(int i = 0; i < MaxOrders; i++)
  1608. {
  1609. if(historyTradeStore[i].ticket == -1)
  1610. {
  1611. historyTradeStore[i].ticket = ticket;
  1612. historyTradeStore[i].magic = magicIs;
  1613. Print(" -------- add_history_ticket() Added ticket: ", ticket, " Magic: ", magicIs, " ---------------------------- ");
  1614. return;
  1615. }
  1616. }
  1617. Print("historyTradeStore full, cannot add ticket: ", ticket);
  1618. }
  1619. //+------------------------------------------------------------------+
  1620. //| |
  1621. //+------------------------------------------------------------------+
  1622. bool history_ticket_present(ulong ticket)
  1623. {
  1624. for(int i = 0 ; i < MaxOrders ; i++)
  1625. {
  1626. if(historyTradeStore[i].ticket == ticket)
  1627. return true;
  1628. }
  1629. return false;
  1630. }
  1631. //+------------------------------------------------------------------+
  1632. //+------------------------------------------------------------------+
  1633. //| |
  1634. //+------------------------------------------------------------------+