Bez popisu

vol_hedge_strategy_mt5.mq5 51KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310
  1. //+------------------------------------------------------------------+
  2. //| vol_hedge_strategy_mt5.mq5 |
  3. //| Copyright 2025, MQL Development |
  4. //| https://www.mqldevelopment.com/ |
  5. //+------------------------------------------------------------------+
  6. #property copyright "Copyright 2025, MQL Development"
  7. #property link "https://www.mqldevelopment.com/"
  8. #property version "1.00"
  9. #define MaxOrders 100
  10. #include <Trade\Trade.mqh>
  11. CTrade trade;
  12. //+------------------------------------------------------------------+
  13. //| Expert initialization function |
  14. //+------------------------------------------------------------------+
  15. enum NewsCloseOrder
  16. {
  17. CloseAllRunningOrder=0,
  18. LetTheOrderRun=1,
  19. };
  20. enum selectLine
  21. {
  22. LineOnNewsBar =0,
  23. LineOnNewsStop=1
  24. };
  25. #import "volHedgeNewsFilter.ex5"
  26. //+------------------------------------------------------------------+
  27. //| |
  28. //+------------------------------------------------------------------+
  29. void initiateNews();
  30. int returnNewsStatus(bool High_Impact_News=true
  31. ,int High_Start_Time=60//Stop Trade before high News (min)
  32. ,int High_Stop_Time=15 //Stop Trade after high News (min)
  33. ,bool show_high_line=true//Show verticle Line when high news comes
  34. ,bool Medium_Impact_News=true
  35. ,int Medium_Start_Time=60//Stop Trade before medium News (min)
  36. ,int Medium_Stop_Time=15 //Stop Trade after medium News (min)
  37. ,bool show_medium_line=true//Show verticle Line when medium news comes
  38. ,bool Low_Impact_News=true
  39. ,int Low_Start_Time=60//Stop Trade before low News (min)
  40. ,int Low_Stop_Time=15 //Stop Trade after low News (min)
  41. ,bool show_low_line=true//Show verticle Line when low news comes
  42. ,string symbol=""
  43. ,string expert=""
  44. ,int GMT_Broker_Time=2
  45. ,selectLine sl=0
  46. ,string extraSymbol=""
  47. );
  48. void initiateNews();
  49. bool checkDate(string &lastNewsTitle, string &symbolNews, string &impactNews, string &news1, string &news2, string &news3, datetime &timeRemaining, datetime date,string expertname = "",string symbol = "",string extraSymbol="", int gmt=2,string description_1 = "",int candle = 0);
  50. void PrintStructure();
  51. #import
  52. struct new_trade_store
  53. {
  54. ulong buy_ticket; // Buy Ticket
  55. ulong sell_ticket; // Sell Ticket
  56. string symbol; // Symbol
  57. double price; // Price
  58. double stop_loss; // StopLoss
  59. double take_profit; // TakeProfit
  60. datetime start_time; // Start time
  61. datetime end_time; // End Time
  62. bool buy_hit_virtual_sl; // Buy Hit Virtual StopLoss
  63. bool sell_hit_virtual_sl; // Sell Hit Virtual StopLoss
  64. new_trade_store()
  65. {
  66. buy_ticket = -1;
  67. sell_ticket = -1;
  68. price = 0;
  69. buy_hit_virtual_sl = false;
  70. sell_hit_virtual_sl = false;
  71. }
  72. };
  73. new_trade_store newTradeStore[MaxOrders];
  74. enum lotcalculator
  75. {
  76. fix, //Fixed Lot Size
  77. rsk, //Risk Percentage
  78. dollar, // Risk in Dollars
  79. };
  80. sinput string string_0 = "<><><><><><> General SETTINGS <><><><><><>"; //__
  81. input int magic_no = 333; // Magic no
  82. input bool bothHitsSl = false; // Open after Both Hits StopLoss
  83. input int maxTrades = 2; // Max Concurrent Trades
  84. input int maxSlippage = 5; // Max Slippage
  85. input bool enableSpreadFilter = false; // Enable Spread Filter
  86. input double maximumSpread = 10; // Maximum Spread
  87. input string dataFileName = "vol_hedge_data.csv"; // Data File Name
  88. input string string_1 = "<><><><><><> Lot Management<><><><><><>"; //__
  89. input lotcalculator lot_calculator = fix; // Lot Size Option
  90. input double lot_amount = 0.1; // Lot Size
  91. input double risk = 0.5; // Risk in Percentage %
  92. input double dollars = 10; // Risk in GBP
  93. input string string_2 = "<><><><><><> Time Filter Setting <><><><><><> ";//_
  94. input bool enableTimeSession = false; // Enable Time Session
  95. input string start_time_session = "01:00"; // Start Session
  96. input string end_time_session = "23:59"; // End Session
  97. input string string_0_2 = "<><><><><><> Trailing Setting<><><><><><>"; //__
  98. input bool indivial_trailing = false; // Indiviual Trailing
  99. input double ts_sl = 15; // Trailing Start in Pips
  100. input double ts = 5; // Trailing Stop in Pips
  101. input string strMA14 ="<><><><><><> BreakEven Settings <><><><><><>";//_
  102. input bool UseBreakEven = false; // Use Break Even
  103. input int breakEvenPoints = 15; // BreakEven Trigger Pips
  104. input int breakStopPoint = 5; // BreakEven Above OpenPrice Pips
  105. input string news = "<><><><><><> News Settings <><><><><><>"; // News
  106. input NewsCloseOrder newsClose = CloseAllRunningOrder; // On News Action on Running Orders
  107. input bool High_Impact_News = true; //High Impact News
  108. input int High_Start_Time = 60; //Stop Trade before high News (min)
  109. input int High_Stop_Time = 15; //Stop Trade after high News (min)
  110. input bool show_high_line = true; //Show verticle Line when high news comes
  111. input selectLine Select_News_Line = 0; //News Line
  112. input bool mobileAlert = true; //Mobile Alert
  113. input bool Medium_Impact_News = false; // Medium Impact News
  114. input int Medium_Start_Time = 60; // Stop Trade before medium News (min)
  115. input int Medium_Stop_Time = 15; // Stop Trade after medium News (min)
  116. input bool show_medium_line = false; // Show vertical Line when medium news comes
  117. input bool Low_Impact_News = false; // Low Impact News
  118. input int Low_Start_Time = 60; // Stop Trade before low News (min)
  119. input int Low_Stop_Time = 15; // Stop Trade after low News (min)
  120. input bool show_low_line = false; // Show vertical Line when low news comes
  121. // Global Variables
  122. static double tickCurrentBid = 0;
  123. double tickPreviousBid = 0;
  124. static double tickCurrentAsk = 0;
  125. double tickPreviousAsk = 0;
  126. datetime startSessionTime, endSessionTime;
  127. int GMT_Broker_Time = +2; // GMT_Broker_Time Time of your Broker
  128. int gmt = 0; // GMT_Broker_Time Time of your Broker
  129. string Lname="newsLabel3";
  130. double levelsAre[];
  131. //+------------------------------------------------------------------+
  132. //| |
  133. //+------------------------------------------------------------------+
  134. int OnInit()
  135. {
  136. //---
  137. Print(" OnInIt. ");
  138. trade.SetExpertMagicNumber(magic_no);
  139. trade.SetDeviationInPoints(maxSlippage);
  140. trade.SetTypeFilling(ORDER_FILLING_IOC);
  141. trade.LogLevel(LOG_LEVEL_ALL);
  142. trade.SetAsyncMode(false);
  143. if(!MQLInfoInteger(MQL_TESTER))
  144. {
  145. loadNewTradeStoreFile();
  146. }
  147. int filehandle = FileOpen(dataFileName, FILE_READ | FILE_CSV | FILE_COMMON | FILE_ANSI);
  148. if(filehandle != INVALID_HANDLE)
  149. {
  150. Print(" Valid Handler. ");
  151. while(!FileIsEnding(filehandle))
  152. {
  153. string orderToRead = FileReadString(filehandle);
  154. string orderData[];
  155. //Print("Data: ", OrderToRead);
  156. StringSplit(orderToRead, StringGetCharacter(",",0), orderData);
  157. Print("Array Size: ", ArraySize(orderData));
  158. Print(" Order is: ", orderToRead);
  159. for(int i = 0 ; i < ArraySize(orderData) ; i++)
  160. {
  161. Print(" Order Data: ", orderData[i], " i: ", i);
  162. }
  163. if(ArraySize(orderData) >= 6)
  164. {
  165. if(orderData[0] == Symbol())
  166. {
  167. // store into local variables first (trim if needed)
  168. ulong buy_ticket_local = (ulong)-1; // keep -1 as per your convention
  169. ulong sell_ticket_local = (ulong)-1;
  170. string symbol_local = orderData[0];
  171. double price_local = StringToDouble(orderData[1]);
  172. double sl_local = StringToDouble(orderData[2]);
  173. double tp_local = StringToDouble(orderData[3]);
  174. // if your CSV has extra fields (tp2,tp3, etc.) parse here as needed
  175. datetime start_local = StringToTime(orderData[4]);
  176. datetime end_local = StringToTime(orderData[5]);
  177. ArrayResize(levelsAre,ArraySize(levelsAre)+1);
  178. levelsAre[ArraySize(levelsAre) - 1] = price_local;
  179. // OPTIONAL: only add when price == 0:
  180. // if(MathAbs(price_local) > 1e-9) { Print("Skipped: price != 0"); continue; }
  181. bool buy_virtual_tp_hit = true;
  182. bool sell_virtual_tp_hit = true;
  183. if(bothHitsSl)
  184. {
  185. buy_virtual_tp_hit = false;
  186. sell_virtual_tp_hit = false;
  187. }
  188. // call the single-responsibility function that writes into struct array
  189. if(!level_present(price_local))
  190. {
  191. addToNewTradeStore(buy_ticket_local, sell_ticket_local,
  192. symbol_local, price_local,
  193. sl_local, tp_local,
  194. start_local, end_local,
  195. buy_virtual_tp_hit, sell_virtual_tp_hit);
  196. }
  197. else
  198. {
  199. Print("Level is already Present. Level: ", price_local);
  200. }
  201. }
  202. }
  203. }
  204. FileClose(filehandle);
  205. }
  206. else
  207. {
  208. Print(" InValid Handler. Error: ", GetLastError());
  209. }
  210. struct_level_check();
  211. timeFilter(true,start_time_session, end_time_session, startSessionTime, endSessionTime);
  212. Print(" Session Start = ", startSessionTime, " Asian Session End = ", endSessionTime);
  213. int timeDifference = (int)TimeCurrent() - (int)TimeGMT();
  214. Print("Time Difference is: ", timeDifference);
  215. if(timeDifference > 0)
  216. {
  217. GMT_Broker_Time = (int)MathRound((double)timeDifference / 3600.0);
  218. }
  219. else
  220. if(timeDifference < 0)
  221. {
  222. GMT_Broker_Time = (int)MathRound((double)timeDifference / 3600.0);
  223. }
  224. else // timeDifference == 0
  225. {
  226. GMT_Broker_Time = 0;
  227. }
  228. Print("Gmt Time: ", TimeGMT(), " Broker Gmt Time: ", GMT_Broker_Time);
  229. gmt = GMT_Broker_Time;
  230. if(!MQLInfoInteger(MQL_TESTER))
  231. {
  232. initiateNews(); // change here
  233. }
  234. //---
  235. return(INIT_SUCCEEDED);
  236. }
  237. //+------------------------------------------------------------------+
  238. //| Expert deinitialization function |
  239. //+------------------------------------------------------------------+
  240. void OnDeinit(const int reason)
  241. {
  242. //---
  243. if(!MQLInfoInteger(MQL_TESTER))
  244. {
  245. saveNewTradeStoreFile();
  246. }
  247. }
  248. //+------------------------------------------------------------------+
  249. //| Expert tick function |
  250. //+------------------------------------------------------------------+
  251. void OnTick()
  252. {
  253. static int status=-1,preStatus=-1;
  254. if(!MQLInfoInteger(MQL_TESTER))
  255. {
  256. status=returnNewsStatus(High_Impact_News
  257. ,High_Start_Time
  258. ,High_Stop_Time
  259. ,show_high_line
  260. ,Medium_Impact_News
  261. ,Medium_Start_Time
  262. ,Medium_Stop_Time
  263. ,show_medium_line
  264. ,Low_Impact_News
  265. ,Low_Start_Time
  266. ,Low_Stop_Time
  267. ,show_low_line
  268. ,Symbol()
  269. ,MQLInfoString(MQL_PROGRAM_NAME)
  270. ,GMT_Broker_Time
  271. ,Select_News_Line
  272. ,""
  273. );
  274. }
  275. else
  276. status=0;
  277. if(status==0)
  278. {
  279. mainActivity();
  280. }
  281. if(status==1 || status==2 || status==3)
  282. {
  283. if(newsClose==0)
  284. {
  285. if(orderCount_1(POSITION_TYPE_BUY,magic_no)>0)
  286. closeTrades(POSITION_TYPE_BUY,magic_no);
  287. if(orderCount_1(POSITION_TYPE_SELL,magic_no)>0)
  288. closeTrades(POSITION_TYPE_SELL,magic_no);
  289. }
  290. else
  291. if(newsClose==1)
  292. {
  293. if((orderCount_1(POSITION_TYPE_BUY,magic_no)>0) || (orderCount_1(POSITION_TYPE_SELL,magic_no)>0))
  294. {
  295. mainActivity();
  296. }
  297. }
  298. }
  299. if(status!=preStatus)
  300. {
  301. if(status==0 && preStatus!=-1)
  302. {
  303. // if(ObjectFind(0,Lname))
  304. {
  305. // ObjectSetInteger(0,Lname,OBJPROP_COLOR,clrRed);
  306. ObjectSetString(0,Lname,OBJPROP_TEXT,"");
  307. }
  308. Alert("Trading is start");
  309. if(mobileAlert)
  310. SendNotification("Trading is start");
  311. preStatus=status;
  312. }
  313. else
  314. if(status==1)
  315. {
  316. ObjectSetInteger(0,Lname,OBJPROP_COLOR,clrRed);
  317. ObjectSetString(0,Lname,OBJPROP_TEXT,"High Impact News");
  318. Alert("Trading Stop due to high impact news");
  319. if(mobileAlert)
  320. SendNotification("Trading Stop due to high impact news");
  321. preStatus=status;
  322. }
  323. else
  324. if(status==2)
  325. {
  326. ObjectSetInteger(0,Lname,OBJPROP_COLOR,clrBlue);
  327. ObjectSetString(0,Lname,OBJPROP_TEXT,"Medium Impact News");
  328. Alert("Trading Stop due to medium impact news");
  329. if(mobileAlert)
  330. SendNotification("Trading Stop due to medium impact news");
  331. preStatus=status;
  332. }
  333. else
  334. if(status==3)
  335. {
  336. ObjectSetInteger(0,Lname,OBJPROP_COLOR,clrGreen);
  337. ObjectSetString(0,Lname,OBJPROP_TEXT,"Low Impact News");
  338. Alert("Trading Stop due to low impact news");
  339. if(mobileAlert)
  340. SendNotification("Trading Stop due to low impact news");
  341. preStatus=status;
  342. }
  343. }
  344. else
  345. {
  346. mainActivity();
  347. }
  348. }
  349. //+------------------------------------------------------------------+
  350. //| |
  351. //+------------------------------------------------------------------+
  352. void mainActivity()
  353. {
  354. //---
  355. if(indivial_trailing)
  356. {
  357. Individual_Trailing();
  358. }
  359. if(UseBreakEven)
  360. {
  361. breakEven();
  362. }
  363. double Bid = SymbolInfoDouble(Symbol(), SYMBOL_BID);
  364. double Ask = SymbolInfoDouble(Symbol(), SYMBOL_ASK);
  365. if(tickPreviousBid == 0 && tickCurrentBid == 0)
  366. {
  367. tickPreviousBid = Bid;
  368. tickCurrentBid = Bid;
  369. }
  370. else
  371. {
  372. tickPreviousBid = tickCurrentBid;
  373. tickCurrentBid = Bid;
  374. }
  375. if(tickPreviousAsk == 0 && tickCurrentAsk == 0)
  376. {
  377. tickPreviousAsk = Ask;
  378. tickCurrentAsk = Ask;
  379. }
  380. else
  381. {
  382. tickPreviousAsk = tickCurrentAsk;
  383. tickCurrentAsk = Ask;
  384. }
  385. // Print(" Time is: ", TimeCurrent());
  386. timeFilter(false,start_time_session, end_time_session, startSessionTime, endSessionTime);
  387. // Comment(" Session Start = ", startSessionTime, " Asian Session End = ", endSessionTime);
  388. if((!enableTimeSession) || (enableTimeSession && TimeCurrent() >= startSessionTime && TimeCurrent() <= endSessionTime))
  389. {
  390. removeFromStructure();
  391. if(bothHitsSl)
  392. {
  393. virtualSLHitCheck();
  394. }
  395. tradePlacingCheck();
  396. }
  397. }
  398. //+------------------------------------------------------------------+
  399. //+------------------------------------------------------------------+
  400. //| |
  401. //+------------------------------------------------------------------+
  402. void closeTrades(int type,int magicno)
  403. {
  404. Print("Total order: ",OrdersTotal());
  405. for(int i= PositionsTotal()-1; i>=0; i--)
  406. {
  407. // Print(" Selection: ",OrderSelect(i,SELECT_BY_POS)," i: ",i," OrdersTotal(): ", OrdersTotal());
  408. ulong ticket = PositionGetTicket(i);
  409. if(PositionSelectByTicket(ticket))
  410. {
  411. if(PositionGetInteger(POSITION_TYPE) == type)
  412. {
  413. if(PositionGetInteger(POSITION_MAGIC) == magicno && PositionGetString(POSITION_SYMBOL) == Symbol())
  414. {
  415. //trade.PositionClose(PositionGetInteger(POSITION_TICKET))
  416. if(!trade.PositionClose(PositionGetInteger(POSITION_TICKET)))
  417. {Print("Problem in closing order order ",PositionGetInteger(POSITION_TICKET)); }
  418. else
  419. {
  420. Print("Order Closed by closeTrades() new filter",PositionGetInteger(POSITION_TICKET));
  421. }
  422. }
  423. }
  424. }
  425. }
  426. }
  427. //+------------------------------------------------------------------+
  428. //| |
  429. //+------------------------------------------------------------------+
  430. int orderCount_1(int type,int magic)
  431. {
  432. int count1=0;
  433. for(int i= PositionsTotal()-1; i>=0; i--)
  434. {
  435. // Print(" Selection: ",OrderSelect(i,SELECT_BY_POS)," i: ",i," OrdersTotal(): ", OrdersTotal());
  436. ulong ticket = PositionGetTicket(i);
  437. if(PositionSelectByTicket(ticket))
  438. {
  439. // if(PositionGetInteger(POSITION_TYPE) == POSITION_TYPE_BUY || PositionGetInteger(POSITION_TYPE) == POSITION_TYPE_SELL)
  440. if(PositionGetInteger(POSITION_MAGIC) == magic && PositionGetString(POSITION_SYMBOL) == Symbol())
  441. {
  442. //trade.PositionClose(PositionGetInteger(POSITION_TICKET))
  443. if(PositionGetInteger(POSITION_TYPE) == type)
  444. {
  445. count1++;
  446. }
  447. }
  448. }
  449. }
  450. return count1;
  451. }
  452. //+------------------------------------------------------------------+
  453. //| |
  454. //+------------------------------------------------------------------+
  455. int orderCount(int type)
  456. {
  457. int count = 0;
  458. for(int i= PositionsTotal()-1; i>=0; i--)
  459. {
  460. ulong ticket = PositionGetTicket(i);
  461. if(PositionSelectByTicket(ticket))
  462. {
  463. if(PositionGetInteger(POSITION_MAGIC) == magic_no && PositionGetString(POSITION_SYMBOL) == Symbol())
  464. {
  465. if(PositionGetInteger(POSITION_TYPE) == type)
  466. {
  467. count++;
  468. }
  469. }
  470. }
  471. }
  472. return count;
  473. }
  474. //+------------------------------------------------------------------+
  475. //| |
  476. //+------------------------------------------------------------------+
  477. bool level_present(double priceIs)
  478. {
  479. for(int i = 0 ; i < MaxOrders ; i++)
  480. {
  481. if(newTradeStore[i].price > 0)
  482. {
  483. if(priceIs == newTradeStore[i].price)
  484. {
  485. return true;
  486. }
  487. }
  488. }
  489. return false;
  490. }
  491. //+------------------------------------------------------------------+
  492. //| |
  493. //+------------------------------------------------------------------+
  494. void struct_level_check()
  495. {
  496. for(int i = 0; i < MaxOrders; i++)
  497. {
  498. if(newTradeStore[i].price > 0)
  499. {
  500. bool found = false;
  501. for(int j = 0; j < ArraySize(levelsAre); j++)
  502. {
  503. if(newTradeStore[i].price == levelsAre[j])
  504. {
  505. found = true;
  506. break;
  507. }
  508. }
  509. if(!found)
  510. {
  511. Print("Price not found in levelsAre[] -> index:", i, " | price:", newTradeStore[i].price);
  512. newTradeStore[i].buy_ticket = (ulong)-1;
  513. newTradeStore[i].sell_ticket = (ulong)-1;
  514. bool buy_virtual_tp_hit = true;
  515. bool sell_virtual_tp_hit = true;
  516. if(bothHitsSl)
  517. {
  518. buy_virtual_tp_hit = false;
  519. sell_virtual_tp_hit = false;
  520. }
  521. newTradeStore[i].buy_hit_virtual_sl = buy_virtual_tp_hit;
  522. newTradeStore[i].sell_hit_virtual_sl = sell_virtual_tp_hit;
  523. newTradeStore[i].symbol = "";
  524. newTradeStore[i].price = 0.0;
  525. newTradeStore[i].stop_loss = 0.0;
  526. newTradeStore[i].take_profit = 0.0;
  527. newTradeStore[i].start_time = 0;
  528. newTradeStore[i].end_time = 0;
  529. return;
  530. }
  531. }
  532. }
  533. return;
  534. }
  535. //+------------------------------------------------------------------+
  536. //| |
  537. //+------------------------------------------------------------------+
  538. void addToNewTradeStore(ulong r_buy_ticket, ulong r_sell_ticket,
  539. string r_symbol, double r_price,
  540. double r_stop_loss, double r_take_profit,
  541. datetime r_start_time, datetime r_end_time, bool r_buy_hit_sl, bool r_sell_hit_sl)
  542. {
  543. Print(" Tier 1. ");
  544. for(int i = 0; i < MaxOrders; i++)
  545. {
  546. // treat slot as empty when both tickets are -1 (same convention as constructor)
  547. if(newTradeStore[i].buy_ticket == -1 && newTradeStore[i].sell_ticket == -1)
  548. {
  549. if(newTradeStore[i].price == 0)
  550. {
  551. newTradeStore[i].buy_ticket = r_buy_ticket;
  552. newTradeStore[i].sell_ticket = r_sell_ticket;
  553. newTradeStore[i].symbol = r_symbol;
  554. newTradeStore[i].price = r_price;
  555. newTradeStore[i].stop_loss = r_stop_loss;
  556. newTradeStore[i].take_profit = r_take_profit;
  557. newTradeStore[i].start_time = r_start_time;
  558. newTradeStore[i].end_time = r_end_time;
  559. newTradeStore[i].buy_hit_virtual_sl = r_buy_hit_sl;
  560. newTradeStore[i].sell_hit_virtual_sl = r_sell_hit_sl;
  561. Print("Stored -> idx: ", i,
  562. " | Symbol: ", newTradeStore[i].symbol,
  563. " | price: ", DoubleToString(newTradeStore[i].price, Digits()),
  564. " | sl: ", DoubleToString(newTradeStore[i].stop_loss, Digits()),
  565. " | tp: ", DoubleToString(newTradeStore[i].take_profit, Digits()),
  566. " | start: ", TimeToString(newTradeStore[i].start_time, TIME_DATE|TIME_SECONDS),
  567. " | end: ", TimeToString(newTradeStore[i].end_time, TIME_DATE|TIME_SECONDS),
  568. " | Buy Virtal Sl Hit: ", newTradeStore[i].buy_hit_virtual_sl,
  569. " | Sell Virtual Sl Hit: ", newTradeStore[i].sell_hit_virtual_sl);
  570. break;
  571. }
  572. }
  573. }
  574. }
  575. //+------------------------------------------------------------------+
  576. //| |
  577. //+------------------------------------------------------------------+
  578. void tradePlacingCheck()
  579. {
  580. for(int i = 0; i < MaxOrders; i++)
  581. {
  582. if(newTradeStore[i].buy_ticket == -1 && newTradeStore[i].sell_ticket == -1)
  583. {
  584. if(newTradeStore[i].price > 0)
  585. {
  586. if(TimeCurrent() > newTradeStore[i].start_time && TimeCurrent() < newTradeStore[i].end_time)
  587. {
  588. if(newTradeStore[i].buy_hit_virtual_sl == true && newTradeStore[i].sell_hit_virtual_sl == true)
  589. {
  590. double levelPriceIs = newTradeStore[i].price;
  591. if((tickPreviousBid > levelPriceIs && tickCurrentBid < levelPriceIs) ||
  592. (tickPreviousBid < levelPriceIs && tickCurrentBid > levelPriceIs))
  593. {
  594. if(countLiveTrades() < maxTrades)
  595. {
  596. if((enableSpreadFilter && spreadFilter()) || !enableSpreadFilter)
  597. {
  598. ulong buyTicket = placeBuyTrade(newTradeStore[i].stop_loss, newTradeStore[i].take_profit);
  599. ulong sellTicket = placeSellTrade(newTradeStore[i].stop_loss, newTradeStore[i].take_profit);
  600. newTradeStore[i].buy_ticket = buyTicket;
  601. newTradeStore[i].sell_ticket = sellTicket;
  602. }
  603. }
  604. }
  605. }
  606. }
  607. }
  608. }
  609. }
  610. }
  611. //+------------------------------------------------------------------+
  612. //| |
  613. //+------------------------------------------------------------------+
  614. ulong placeBuyTrade(double stoploss, double takeprofit)
  615. {
  616. double buySL = 0, buyTp=0;
  617. //openPrice = SymbolInfoDouble(Symbol(),SYMBOL_ASK);
  618. double Ask = SymbolInfoDouble(Symbol(),SYMBOL_ASK);
  619. double Bid = SymbolInfoDouble(Symbol(),SYMBOL_BID);
  620. if(stoploss != 0)
  621. {
  622. buySL = Ask - (stoploss * Point());
  623. }
  624. if(takeprofit != 0)
  625. {
  626. buyTp = Ask + (takeprofit * Point());
  627. }
  628. double distance = MathAbs((Ask - buySL) / Point());
  629. if(trade.PositionOpen(Symbol(),ORDER_TYPE_BUY,getLot(distance),Ask,buySL,buyTp,"Buy Trade Placed"))
  630. {
  631. Print("Buy Trade Placed: ",trade.ResultOrder());
  632. return trade.ResultOrder();
  633. }
  634. else
  635. {
  636. Print("Error in placing Buy: "+Symbol()+" ",GetLastError());
  637. return -1;
  638. }
  639. return -1;
  640. }
  641. //+------------------------------------------------------------------+
  642. //| |
  643. //+------------------------------------------------------------------+
  644. ulong placeSellTrade(double stoploss, double takeprofit)
  645. {
  646. double sellSL = 0, sellTp = 0;
  647. double Ask = SymbolInfoDouble(Symbol(),SYMBOL_ASK);
  648. double Bid = SymbolInfoDouble(Symbol(),SYMBOL_BID);
  649. if(stoploss != 0)
  650. {
  651. sellSL = Bid + (stoploss * Point());
  652. }
  653. if(takeprofit != 0)
  654. {
  655. sellTp = Bid - (takeprofit * Point());
  656. }
  657. double distance = MathAbs((Bid - sellSL) / Point());
  658. if(trade.PositionOpen(Symbol(),ORDER_TYPE_SELL,getLot(distance),Bid,sellSL,sellTp,"Sell Trade Placed"))
  659. {
  660. Print("Sell Trade PLaced: ",trade.ResultOrder());
  661. return trade.ResultOrder();
  662. }
  663. else
  664. {
  665. Print("Error in placing Sell: "+Symbol()+" ",GetLastError());
  666. return -1;
  667. }
  668. return -1;
  669. }
  670. //+------------------------------------------------------------------+
  671. //| |
  672. //+------------------------------------------------------------------+
  673. double getLot(double stop_loss)
  674. {
  675. Print("Tick Value: ",SymbolInfoDouble(Symbol(),SYMBOL_TRADE_TICK_VALUE));
  676. Print("Tick Size: ",SymbolInfoDouble(Symbol(),SYMBOL_TRADE_TICK_SIZE));
  677. double modeTickV=SymbolInfoDouble(Symbol(),SYMBOL_TRADE_TICK_VALUE)
  678. ,modeTickS=SymbolInfoDouble(Symbol(),SYMBOL_TRADE_TICK_SIZE);
  679. // Print("Pip value: ", NormalizeDouble(((SymbolInfoDouble(Symbol(),SYMBOL_TRADE_TICK_VALUE)/(SymbolInfoDouble(Symbol(),SYMBOL_TRADE_TICK_SIZE)/Point))*10),2));
  680. double pipvalue = NormalizeDouble(((SymbolInfoDouble(Symbol(),SYMBOL_TRADE_TICK_VALUE)/(SymbolInfoDouble(Symbol(),SYMBOL_TRADE_TICK_SIZE)/Point()))*10),2);
  681. // pipvalue=NormalizeDouble((modeTickV/modeTickS/Point()),)
  682. // pipvalue=
  683. pipvalue = pipvalue / 10;
  684. double lotSize = lot_amount;
  685. if(lot_calculator == rsk || lot_calculator == dollar) //calculating risk
  686. {
  687. double riskamount = 0;
  688. if(lot_calculator == rsk)
  689. {
  690. riskamount = (risk/100)*AccountInfoDouble(ACCOUNT_BALANCE);
  691. }
  692. if(lot_calculator == dollar)
  693. {
  694. riskamount = dollars;
  695. }
  696. double pipvalue_required=riskamount/stop_loss;
  697. lotSize = pipvalue_required/pipvalue;
  698. //sl=riskamount/pipValuelot
  699. int roundDigit=0;
  700. double step=SymbolInfoDouble(Symbol(),SYMBOL_VOLUME_STEP);
  701. while(step<1)
  702. {
  703. roundDigit++;
  704. step=step*10;
  705. }
  706. Print("Round Digits:",roundDigit);
  707. lotSize = NormalizeDouble(lotSize,roundDigit);
  708. //
  709. }
  710. Print("Lot Size: ",lotSize);
  711. if(lotSize > SymbolInfoDouble(Symbol(),SYMBOL_VOLUME_MAX))
  712. {
  713. lotSize=SymbolInfoDouble(Symbol(),SYMBOL_VOLUME_MAX);
  714. }
  715. else
  716. if(lotSize<SymbolInfoDouble(Symbol(),SYMBOL_VOLUME_MIN))
  717. {
  718. lotSize=SymbolInfoDouble(Symbol(),SYMBOL_VOLUME_MIN);
  719. }
  720. //---
  721. return lotSize;
  722. }
  723. //+------------------------------------------------------------------+
  724. //| |
  725. //+------------------------------------------------------------------+
  726. void timeFilter(bool onInit,string startTime,string endTime,datetime & sessionStart,datetime & sessionEnd)
  727. {
  728. int newYorkStartHour = 0, newYorkStartMin = 0, newYorkEndHour = 0, newYorkEndMin = 0;
  729. datetime newYorkStartTrading,newYorkEndTrading;
  730. string time[];
  731. StringSplit(startTime,':',time);
  732. newYorkStartHour = (int)StringToInteger(time[0]);
  733. newYorkStartMin = (int)StringToInteger(time[1]);
  734. EventSetMillisecondTimer(500);
  735. time[0] = "";
  736. time[1] = "";
  737. StringSplit(endTime,':',time);
  738. newYorkEndHour = (int)StringToInteger(time[0]);
  739. newYorkEndMin = (int)StringToInteger(time[1]);
  740. // Print(" Start Time Hour: ",newYorkStartHour," Start Time Min: ",newYorkStartMin);
  741. // Print(" End Time Hour: ",newYorkEndHour," End Time Min: ",newYorkEndMin);
  742. datetime startDateTime;
  743. MqlDateTime st;
  744. TimeCurrent(st); // get current date
  745. st.hour = newYorkStartHour;
  746. st.min = newYorkStartMin;
  747. st.sec = 0;
  748. startDateTime = StructToTime(st);
  749. datetime endDateTime;
  750. MqlDateTime et;
  751. TimeCurrent(et); // get current date
  752. et.hour = newYorkEndHour;
  753. et.min = newYorkEndMin;
  754. et.sec = 0;
  755. endDateTime = StructToTime(et);
  756. MqlDateTime sdate,edate;
  757. datetime start_Time = 0, end_Time = 0;
  758. if(startDateTime > endDateTime)
  759. {
  760. if(onInit)
  761. {
  762. start_Time = iTime(Symbol(),PERIOD_D1,1);
  763. end_Time = iTime(Symbol(),PERIOD_D1,0);
  764. }
  765. else
  766. {
  767. start_Time = sessionStart;
  768. end_Time = sessionEnd;
  769. if(TimeCurrent() >= sessionEnd && sessionEnd != 0)
  770. {
  771. start_Time = iTime(Symbol(),PERIOD_D1,0);
  772. end_Time = start_Time + 86400;
  773. }
  774. }
  775. }
  776. else
  777. {
  778. start_Time = iTime(Symbol(),PERIOD_D1,0);
  779. end_Time = iTime(Symbol(),PERIOD_D1,0);
  780. }
  781. if(TimeToStruct(end_Time,edate))
  782. {
  783. edate.hour = newYorkEndHour;
  784. edate.min = newYorkEndMin;
  785. edate.sec = 0;
  786. }
  787. else
  788. Print("Error in Converting Time: ",GetLastError());
  789. newYorkEndTrading = StructToTime(edate);
  790. if(TimeToStruct(start_Time,sdate))
  791. {
  792. sdate.hour = newYorkStartHour;
  793. sdate.min = newYorkStartMin;
  794. sdate.sec = 0;
  795. }
  796. else
  797. Print("Error in Converting Time: ",GetLastError());
  798. newYorkStartTrading = StructToTime(sdate);
  799. sessionStart = newYorkStartTrading;
  800. sessionEnd = newYorkEndTrading;
  801. }
  802. //+------------------------------------------------------------------+
  803. //| |
  804. //+------------------------------------------------------------------+
  805. void removeFromStructure()
  806. {
  807. for(int i = 0 ; i < MaxOrders ; i++)
  808. {
  809. bool isBuyPresent=false, isSellPresent=false;
  810. if(newTradeStore[i].buy_ticket != -1 && newTradeStore[i].sell_ticket != -1)
  811. {
  812. for(int j = PositionsTotal()-1; j>=0; j--)
  813. {
  814. ulong ticket = PositionGetTicket(j);
  815. if(PositionSelectByTicket(ticket))
  816. {
  817. if(ticket == newTradeStore[i].buy_ticket)
  818. {
  819. isBuyPresent=true;
  820. }
  821. }
  822. }
  823. for(int j = PositionsTotal()-1; j>=0; j--)
  824. {
  825. ulong ticket = PositionGetTicket(j);
  826. if(PositionSelectByTicket(ticket))
  827. {
  828. if(ticket == newTradeStore[i].sell_ticket)
  829. {
  830. isSellPresent = true;
  831. }
  832. }
  833. }
  834. if(!isBuyPresent && !isSellPresent)
  835. {
  836. Print("Buy/Sell Ticket is closed so removed from struct. Buy Ticket: ", newTradeStore[i].buy_ticket, " Sell Ticket: ", newTradeStore[i].sell_ticket);
  837. newTradeStore[i].buy_ticket = (ulong)-1;
  838. newTradeStore[i].sell_ticket = (ulong)-1;
  839. bool buy_virtual_tp_hit = true;
  840. bool sell_virtual_tp_hit = true;
  841. if(bothHitsSl)
  842. {
  843. buy_virtual_tp_hit = false;
  844. sell_virtual_tp_hit = false;
  845. }
  846. newTradeStore[i].buy_hit_virtual_sl = buy_virtual_tp_hit;
  847. newTradeStore[i].sell_hit_virtual_sl = sell_virtual_tp_hit;
  848. //newTradeStore[i].symbol = "";
  849. //newTradeStore[i].price = 0.0;
  850. //newTradeStore[i].stop_loss = 0.0;
  851. //newTradeStore[i].take_profit = 0.0;
  852. //newTradeStore[i].start_time = 0;
  853. //newTradeStore[i].end_time = 0;
  854. }
  855. }
  856. }
  857. }
  858. //+------------------------------------------------------------------+
  859. //| |
  860. //+------------------------------------------------------------------+
  861. void virtualSLHitCheck()
  862. {
  863. for(int i = 0 ; i < MaxOrders ; i++)
  864. {
  865. if(newTradeStore[i].buy_ticket == -1 && newTradeStore[i].sell_ticket == -1)
  866. {
  867. if(TimeCurrent() > newTradeStore[i].start_time && TimeCurrent() < newTradeStore[i].end_time)
  868. {
  869. double buy_sl = newTradeStore[i].price - (newTradeStore[i].stop_loss * Point());
  870. double sell_sl = newTradeStore[i].price + (newTradeStore[i].stop_loss * Point());
  871. if(newTradeStore[i].buy_hit_virtual_sl == false)
  872. {
  873. if((tickPreviousBid < buy_sl && tickCurrentBid > buy_sl))
  874. {
  875. newTradeStore[i].buy_hit_virtual_sl = true;
  876. Print(" Buy Virtual Sl Hit. newTradeStore[i].buy_hit_virtual_sl: ", newTradeStore[i].buy_hit_virtual_sl, " Order Price is: ", newTradeStore[i].price, " Stop Loss Price is: ", buy_sl, " Time Virtual Sl Hit is: ", TimeCurrent());
  877. }
  878. }
  879. if(newTradeStore[i].sell_hit_virtual_sl == false)
  880. {
  881. if((tickPreviousAsk > sell_sl && tickCurrentAsk < sell_sl))
  882. {
  883. newTradeStore[i].sell_hit_virtual_sl = true;
  884. Print(" Sell Virtual Sl Hit. newTradeStore[i].sell_hit_virtual_sl: ", newTradeStore[i].sell_hit_virtual_sl, " Order Price is: ", newTradeStore[i].price, " Stop Loss Price is: ", sell_sl, " Time Virtual Sl Hit is: ", TimeCurrent());
  885. }
  886. }
  887. }
  888. }
  889. }
  890. }
  891. //+------------------------------------------------------------------+
  892. //| |
  893. //+------------------------------------------------------------------+
  894. int countLiveTrades()
  895. {
  896. int count = 0;
  897. for(int i = 0; i < PositionsTotal(); i++)
  898. {
  899. ulong ticket = PositionGetTicket(i);
  900. if(PositionSelectByTicket(ticket))
  901. {
  902. if(PositionGetInteger(POSITION_MAGIC) == magic_no)
  903. {
  904. if(PositionGetString(POSITION_SYMBOL) == Symbol())
  905. {
  906. if(PositionGetInteger(POSITION_TYPE) == POSITION_TYPE_BUY || PositionGetInteger(POSITION_TYPE) == POSITION_TYPE_SELL)
  907. {
  908. count++;
  909. }
  910. }
  911. }
  912. }
  913. }
  914. return count;
  915. }
  916. //+------------------------------------------------------------------+
  917. //| |
  918. //+------------------------------------------------------------------+
  919. bool spreadFilter()
  920. {
  921. long spreadIs = SymbolInfoInteger(Symbol(), SYMBOL_SPREAD);
  922. if(spreadIs > maximumSpread)
  923. {
  924. return false;
  925. }
  926. return true;
  927. }
  928. //+------------------------------------------------------------------+
  929. //| |
  930. //+------------------------------------------------------------------+
  931. void breakEven()
  932. {
  933. for(int i = PositionsTotal()-1; i>=0; i--)
  934. {
  935. ulong ticket = PositionGetTicket(i);
  936. string symbol=PositionGetSymbol(i);
  937. double mySL = 0,newSL = 0;
  938. double SymbolTickSize = SymbolInfoDouble(symbol, SYMBOL_TRADE_TICK_SIZE);
  939. ////Print("ticket ",ticket," Symbol : ",symbol);
  940. if(PositionSelectByTicket(ticket))
  941. {
  942. if(PositionGetString(POSITION_SYMBOL)==Symbol() && PositionGetInteger(POSITION_MAGIC) == magic_no)
  943. {
  944. //========================================================Buy Condition=========================================================================
  945. if(PositionGetInteger(POSITION_TYPE) == POSITION_TYPE_BUY)
  946. {
  947. mySL = PositionGetDouble(POSITION_PRICE_OPEN) + (breakEvenPoints* 10 * SymbolTickSize);
  948. if(SymbolInfoDouble(Symbol(),SYMBOL_BID) >= mySL && PositionGetDouble(POSITION_PRICE_OPEN) > PositionGetDouble(POSITION_SL))
  949. {
  950. newSL= PositionGetDouble(POSITION_PRICE_OPEN) + (breakStopPoint* 10 * SymbolTickSize);
  951. if(trade.PositionModify(ticket,newSL,PositionGetDouble(POSITION_TP)))
  952. {
  953. Print("Buy Order BreakEven Successfully ");
  954. }
  955. else
  956. {
  957. Print("Error in BreakEven Buy Position ",GetLastError());
  958. }
  959. }
  960. }
  961. //=======================================================Sell condition ===============================================================
  962. if(PositionGetInteger(POSITION_TYPE) == POSITION_TYPE_SELL)
  963. {
  964. mySL = PositionGetDouble(POSITION_PRICE_OPEN) - (breakEvenPoints* 10 * SymbolTickSize);
  965. if(SymbolInfoDouble(Symbol(),SYMBOL_ASK) <= mySL && PositionGetDouble(POSITION_SL) > PositionGetDouble(POSITION_PRICE_OPEN))
  966. {
  967. newSL = PositionGetDouble(POSITION_PRICE_OPEN) - (breakStopPoint* 10 * SymbolTickSize);
  968. if(trade.PositionModify(ticket,newSL,PositionGetDouble(POSITION_TP)))
  969. {
  970. Print("Order Sell BreakEven Successfully ");
  971. }
  972. else
  973. {
  974. Print("Error in BreakEven Sell Position ",GetLastError());
  975. }
  976. }
  977. }
  978. }
  979. }
  980. }
  981. }
  982. //+------------------------------------------------------------------+
  983. //| |
  984. //+------------------------------------------------------------------+
  985. void Individual_Trailing()
  986. {
  987. int openedpositions;
  988. double mySL,myResult;
  989. openedpositions=PositionsTotal();
  990. if((openedpositions>0))
  991. {
  992. int totalorders=PositionsTotal();
  993. for(int i=0; i<totalorders; i++) // scan all orders and positions. ..
  994. {
  995. ulong ticket = PositionGetTicket(i);
  996. if(PositionSelectByTicket(ticket))
  997. {
  998. if(PositionGetString(POSITION_SYMBOL)==Symbol() && PositionGetInteger(POSITION_MAGIC) ==magic_no) // only look if mygrid and symbol. ..
  999. {
  1000. double SymbolAsk = SymbolInfoDouble(PositionGetString(POSITION_SYMBOL), SYMBOL_ASK);
  1001. double SymbolBid = SymbolInfoDouble(PositionGetString(POSITION_SYMBOL), SYMBOL_BID);
  1002. int SymbolDigits = (int)SymbolInfoInteger(PositionGetString(POSITION_SYMBOL), SYMBOL_DIGITS);
  1003. double SymbolTickSize = SymbolInfoDouble(PositionGetString(POSITION_SYMBOL), SYMBOL_TRADE_TICK_SIZE);
  1004. int type= (int)PositionGetInteger(POSITION_TYPE);
  1005. if(type==POSITION_TYPE_BUY) // its a long position
  1006. {
  1007. mySL=NormalizeDouble(SymbolAsk-(ts*SymbolTickSize*10),Digits()); // new SL
  1008. double startSl=PositionGetDouble(POSITION_PRICE_OPEN)+(ts_sl*SymbolTickSize*10);
  1009. if(PositionGetDouble(POSITION_SL) != mySL)
  1010. if(mySL>PositionGetDouble(POSITION_SL) && SymbolAsk>=startSl)
  1011. {
  1012. myResult=trade.PositionModify(ticket,mySL,PositionGetDouble(POSITION_TP)); //OrderModify(OrderTicket(),OrderOpenPrice(),mySL,OrderTakeProfit(),0,clrGreen);
  1013. if(!myResult)
  1014. {
  1015. Print(" Buy Trade Trailing Error: ",GetLastError());
  1016. }
  1017. }
  1018. }
  1019. if(type==POSITION_TYPE_SELL)
  1020. {
  1021. mySL=NormalizeDouble(SymbolBid+(ts*SymbolTickSize*10),Digits()); // new SL
  1022. double startSlSell=PositionGetDouble(POSITION_PRICE_OPEN)-(ts_sl*SymbolTickSize*10);
  1023. if(PositionGetDouble(POSITION_SL) != mySL)
  1024. if(((mySL<PositionGetDouble(POSITION_SL)) || (PositionGetDouble(POSITION_SL)<SymbolTickSize)) && SymbolBid<=startSlSell)
  1025. {
  1026. myResult=trade.PositionModify(ticket,mySL,PositionGetDouble(POSITION_TP)); //OrderModify(OrderTicket(),OrderOpenPrice(),mySL,OrderTakeProfit(),0,clrRed);
  1027. if(!myResult)
  1028. {
  1029. Print(" Sell Trade Trailing Error: ",GetLastError());
  1030. }
  1031. }
  1032. }
  1033. }
  1034. }
  1035. }
  1036. }
  1037. }
  1038. //+------------------------------------------------------------------+
  1039. //| |
  1040. //+------------------------------------------------------------------+
  1041. void saveNewTradeStoreFile()
  1042. {
  1043. // don't run in strategy tester
  1044. if(MQLInfoInteger(MQL_TESTER))
  1045. return;
  1046. string file_name = "new_trade_store.csv";
  1047. int fileHandle = FileOpen(file_name,
  1048. FILE_WRITE | FILE_CSV | FILE_COMMON |
  1049. FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_READ);
  1050. if(fileHandle == INVALID_HANDLE)
  1051. {
  1052. PrintFormat("saveNewTradeStoreFile() -> Cannot open file '%s'. Error: %d", file_name, GetLastError());
  1053. return;
  1054. }
  1055. // header (optional) - comment out if you don't want header
  1056. //string header = "buy_ticket,sell_ticket,symbol,price,stop_loss,take_profit,start_time,end_time,buy_hit_virtual_sl,sell_hit_virtual_sl\r\n";
  1057. //FileWriteString(fileHandle, header);
  1058. for(int i = 0; i < MaxOrders; i++)
  1059. {
  1060. // decide whether this slot has useful data:
  1061. // you can tweak this condition as you prefer (symbol != "" is simple)
  1062. bool slotPopulated = (StringLen(newTradeStore[i].symbol) > 0)
  1063. || (newTradeStore[i].price != 0.0)
  1064. || (newTradeStore[i].start_time != 0);
  1065. if(!slotPopulated)
  1066. continue;
  1067. // convert values to strings
  1068. string buyTicketStr = IntegerToString((long)newTradeStore[i].buy_ticket);
  1069. string sellTicketStr = IntegerToString((long)newTradeStore[i].sell_ticket);
  1070. string priceStr = DoubleToString(newTradeStore[i].price, _Digits);
  1071. string slStr = DoubleToString(newTradeStore[i].stop_loss, _Digits);
  1072. string tpStr = DoubleToString(newTradeStore[i].take_profit, _Digits);
  1073. string startTimeStr = (newTradeStore[i].start_time != 0) ? TimeToString(newTradeStore[i].start_time, TIME_DATE|TIME_SECONDS) : "";
  1074. string endTimeStr = (newTradeStore[i].end_time != 0) ? TimeToString(newTradeStore[i].end_time, TIME_DATE|TIME_SECONDS) : "";
  1075. string buyHitStr = ""; // IntegerToString(newTradeStore[i].buy_hit_virtual_sl ? 1 : 0);
  1076. string sellHitStr = ""; // IntegerToString(newTradeStore[i].sell_hit_virtual_sl ? 1 : 0);
  1077. if(newTradeStore[i].buy_hit_virtual_sl == true)
  1078. {
  1079. buyHitStr = "true";
  1080. }
  1081. else
  1082. {
  1083. buyHitStr = "false";
  1084. }
  1085. if(newTradeStore[i].sell_hit_virtual_sl == true)
  1086. {
  1087. sellHitStr = "true";
  1088. }
  1089. else
  1090. {
  1091. sellHitStr = "false";
  1092. }
  1093. // build CSV line and write
  1094. string line = buyTicketStr + "," + sellTicketStr + "," +
  1095. newTradeStore[i].symbol + "," +
  1096. priceStr + "," + slStr + "," + tpStr + "," +
  1097. startTimeStr + "," + endTimeStr + "," +
  1098. buyHitStr + "," + sellHitStr + "\r\n";
  1099. FileWriteString(fileHandle, line);
  1100. }
  1101. FileClose(fileHandle);
  1102. PrintFormat("saveNewTradeStoreFile() -> saved to '%s'.", file_name);
  1103. }
  1104. //+------------------------------------------------------------------+
  1105. //| |
  1106. //+------------------------------------------------------------------+
  1107. void loadNewTradeStoreFile()
  1108. {
  1109. if(MQLInfoInteger(MQL_TESTER))
  1110. return;
  1111. string file_name = "new_trade_store.csv";
  1112. int fileHandle = FileOpen(file_name,
  1113. FILE_READ | FILE_CSV | FILE_COMMON |
  1114. FILE_SHARE_READ | FILE_SHARE_WRITE);
  1115. if(fileHandle == INVALID_HANDLE)
  1116. {
  1117. Print("loadNewTradeStoreFile() -> Cannot open file '", file_name, "'. Error: ", GetLastError());
  1118. return;
  1119. }
  1120. // reset defaults
  1121. for(int j = 0; j < MaxOrders; j++)
  1122. {
  1123. newTradeStore[j].buy_ticket = (ulong)-1;
  1124. newTradeStore[j].sell_ticket = (ulong)-1;
  1125. newTradeStore[j].symbol = "";
  1126. newTradeStore[j].price = 0.0;
  1127. newTradeStore[j].stop_loss = 0.0;
  1128. newTradeStore[j].take_profit = 0.0;
  1129. newTradeStore[j].start_time = 0;
  1130. newTradeStore[j].end_time = 0;
  1131. newTradeStore[j].buy_hit_virtual_sl = false;
  1132. newTradeStore[j].sell_hit_virtual_sl = false;
  1133. }
  1134. int idx = 0;
  1135. while(!FileIsEnding(fileHandle) && idx < MaxOrders)
  1136. {
  1137. string line = FileReadString(fileHandle);
  1138. if(StringLen(line) == 0)
  1139. continue;
  1140. string tokens[];
  1141. int total = StringSplit(line, ',', tokens);
  1142. if(total >= 10)
  1143. {
  1144. newTradeStore[idx].buy_ticket = (ulong)tokens[0];
  1145. newTradeStore[idx].sell_ticket = (ulong)tokens[1];
  1146. newTradeStore[idx].symbol = tokens[2];
  1147. newTradeStore[idx].price = StringToDouble(tokens[3]);
  1148. newTradeStore[idx].stop_loss = StringToDouble(tokens[4]);
  1149. newTradeStore[idx].take_profit = StringToDouble(tokens[5]);
  1150. string sStart = tokens[6];
  1151. string sEnd = tokens[7];
  1152. newTradeStore[idx].start_time = (StringLen(sStart) > 0) ? StringToTime(sStart) : 0;
  1153. newTradeStore[idx].end_time = (StringLen(sEnd) > 0) ? StringToTime(sEnd) : 0;
  1154. bool bHit = false;
  1155. bool sHit = false;
  1156. if(tokens[8] == "true")
  1157. {
  1158. bHit = true;
  1159. }
  1160. else
  1161. {
  1162. bHit = false;
  1163. }
  1164. if(tokens[9] == "true")
  1165. {
  1166. sHit = true;
  1167. }
  1168. else
  1169. {
  1170. sHit = false;
  1171. }
  1172. newTradeStore[idx].buy_hit_virtual_sl = bHit;
  1173. newTradeStore[idx].sell_hit_virtual_sl = sHit;
  1174. // --- simple Print instead of PrintFormat ---
  1175. Print(
  1176. "Loaded newTradeStore[", idx, "]:",
  1177. " buy_ticket=", newTradeStore[idx].buy_ticket,
  1178. " sell_ticket=", newTradeStore[idx].sell_ticket,
  1179. " symbol=", newTradeStore[idx].symbol,
  1180. " price=", DoubleToString(newTradeStore[idx].price, _Digits),
  1181. " \n sl=", DoubleToString(newTradeStore[idx].stop_loss, _Digits),
  1182. " tp=", DoubleToString(newTradeStore[idx].take_profit, _Digits),
  1183. " start=", (newTradeStore[idx].start_time != 0 ? TimeToString(newTradeStore[idx].start_time, TIME_DATE|TIME_SECONDS) : ""),
  1184. " end=", (newTradeStore[idx].end_time != 0 ? TimeToString(newTradeStore[idx].end_time, TIME_DATE|TIME_SECONDS) : ""),
  1185. " buyHit=", newTradeStore[idx].buy_hit_virtual_sl,
  1186. " sellHit=", newTradeStore[idx].sell_hit_virtual_sl
  1187. );
  1188. idx++;
  1189. }
  1190. else
  1191. {
  1192. Print("loadNewTradeStoreFile(): skipping malformed line (tokens=", total, "): ", line);
  1193. }
  1194. }
  1195. FileClose(fileHandle);
  1196. Print("loadNewTradeStoreFile() -> loaded ", idx, " entries from '", file_name, "'.");
  1197. }
  1198. //+------------------------------------------------------------------+
  1199. //| |
  1200. //+------------------------------------------------------------------+
  1201. //+------------------------------------------------------------------+