Ingen beskrivning

localHedgingClientCopierMt5.mq5 67KB

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