Geen omschrijving

vol_hedge_strategy_mt5.mq5 141KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773
  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.20"
  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. enum selectDay
  26. {
  27. prev, // Previous Day
  28. curr, // Current Day
  29. };
  30. #import "volHedgeNewsFilter.ex5"
  31. //+------------------------------------------------------------------+
  32. //| |
  33. //+------------------------------------------------------------------+
  34. void initiateNews(bool master = false);
  35. int returnNewsStatus(bool High_Impact_News=true
  36. ,int High_Start_Time=60//Stop Trade before high News (min)
  37. ,int High_Stop_Time=15 //Stop Trade after high News (min)
  38. ,bool show_high_line=true//Show verticle Line when high news comes
  39. ,bool Medium_Impact_News=true
  40. ,int Medium_Start_Time=60//Stop Trade before medium News (min)
  41. ,int Medium_Stop_Time=15 //Stop Trade after medium News (min)
  42. ,bool show_medium_line=true//Show verticle Line when medium news comes
  43. ,bool Low_Impact_News=true
  44. ,int Low_Start_Time=60//Stop Trade before low News (min)
  45. ,int Low_Stop_Time=15 //Stop Trade after low News (min)
  46. ,bool show_low_line=true//Show verticle Line when low news comes
  47. ,string symbol=""
  48. ,string expert=""
  49. ,int GMT_Broker_Time=2
  50. ,selectLine sl=0
  51. ,string extraSymbol=""
  52. ,bool isMaster = false
  53. );
  54. 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);
  55. void PrintStructure();
  56. #import
  57. struct new_trade_store
  58. {
  59. ulong buy_ticket; // Buy Ticket
  60. ulong sell_ticket; // Sell Ticket
  61. string symbol; // Symbol
  62. double price; // Price
  63. double stop_loss_buy; // StopLoss Buy
  64. double take_profit_buy; // TakeProfit Buy
  65. double stop_loss_sell; // StopLoss Sell
  66. double take_profit_sell; // TakeProfit Sell
  67. datetime start_time; // Start time
  68. datetime end_time; // End Time
  69. bool demand_level_hit; // Demand Level Hit
  70. bool buy_hit_virtual_sl; // Buy Hit Virtual StopLoss
  71. bool sell_hit_virtual_sl; // Sell Hit Virtual StopLoss
  72. new_trade_store()
  73. {
  74. buy_ticket = -1;
  75. sell_ticket = -1;
  76. price = 0;
  77. demand_level_hit = false;
  78. buy_hit_virtual_sl = false;
  79. sell_hit_virtual_sl = false;
  80. }
  81. };
  82. new_trade_store newTradeStore[MaxOrders];
  83. enum lotcalculator
  84. {
  85. fix, //Fixed Lot Size
  86. rsk, //Risk in Percentage
  87. dollar, // Risk in Dollars
  88. };
  89. enum optionsEaTyp
  90. {
  91. client, // Slave EA
  92. master, // Master EA
  93. };
  94. sinput string string_0 = "<><><><><><> General SETTINGS <><><><><><>"; //__
  95. input string tempString = "Enter your text"; // Preset Name
  96. input int magic_no = 333; // Magic no
  97. input bool useTpSlPips = false; // Use Relative Tp/Sl in Points
  98. input double stopLoss = 1000; // Fixed Stop Loss in Points
  99. input double takeProfit = 1000; // Fixed Take Profit in Points
  100. input bool bothHitsSl = false; // Enable Topped & Tailed Pre-Demand Level
  101. input int maxTrades = 2; // Max Concurrent Trades
  102. input int maxSlippage = 5; // Max Slippage (Points)
  103. input bool enableSpreadFilter = false; // Enable Spread Filter
  104. input double maximumSpread = 10; // Maximum Spread (Points)
  105. input string tradeComment = "Trade Placed"; // Trade Comment Prefix
  106. input string dataFileName = "vol_hedge_data.csv"; // CSV File Name
  107. input bool enableDrawLevels = false; // Draw Levels
  108. input string string_0_2 = "<><><><><><> Trailing Setting<><><><><><>"; //__
  109. input bool indivial_trailing = false; // Indiviual Trailing
  110. input double ts_sl = 150; // Trailing Start in Points
  111. input double ts = 50; // Trailing Stop in Points
  112. input string strMA14 ="<><><><><><> BreakEven Settings <><><><><><>";//_
  113. input bool UseBreakEven = false; // Use Break Even
  114. input int breakEvenPoints = 150; // BreakEven Trigger Points
  115. input int breakStopPoint = 50; // BreakEven Above OpenPrice Points
  116. input string string_1 = "<><><><><><> Lot Management<><><><><><>"; //__
  117. input lotcalculator lot_calculator = fix; // Lot Size Option
  118. input double lot_amount = 0.1; // Lot Size
  119. input double risk = 0.5; // Risk in Percentage %
  120. input double dollars = 10; // Risk in GBP
  121. input string time_setting = "<><><><><> Time Filter Settings <><><><><>"; //_
  122. input bool enableTimeFilter = false; // Enable Time Filter
  123. input string startTime = "03:00"; // Start Time Session
  124. input string endTime = "09:00"; // End Time Session
  125. input string weekFilterSettings = "<><><><><> Week Filter Settings <><><><><>"; //_
  126. input bool enableWeekFilter = false; // Enable Week Filter (true/false)
  127. input int filterMonthNumber = 9; // Month number to apply week filter (1..12)
  128. input int filterWeekNumber = 2; // Week number of month to block (1..5)
  129. input string monthFilterSettings = "<><><><><> Month Filter Settings <><><><><>"; //_
  130. input bool allowJanuary = true; // Allow Trading in January
  131. input bool allowFebruary = true; // Allow Trading in February
  132. input bool allowMarch = true; // Allow Trading in March
  133. input bool allowApril = true; // Allow Trading in April
  134. input bool allowMay = true; // Allow Trading in May
  135. input bool allowJune = true; // Allow Trading in June
  136. input bool allowJuly = true; // Allow Trading in July
  137. input bool allowAugust = true; // Allow Trading in August
  138. input bool allowSeptember = true; // Allow Trading in September
  139. input bool allowOctober = true; // Allow Trading in October
  140. input bool allowNovember = true; // Allow Trading in November
  141. input bool allowDecember = true; // Allow Trading in December
  142. input string news = "<><><><><><> News Settings <><><><><><>"; // News
  143. input NewsCloseOrder newsClose = CloseAllRunningOrder; // On News Action on Running Orders
  144. input optionsEaTyp selectEaType = master; // Select EA Side
  145. input bool High_Impact_News = true; //High Impact News
  146. input int High_Start_Time = 60; //Stop Trade before high News (min)
  147. input int High_Stop_Time = 15; //Stop Trade after high News (min)
  148. input bool show_high_line = true; //Show verticle Line when high news comes
  149. input selectLine Select_News_Line = 0; //News Line
  150. input bool mobileAlert = true; //Mobile Alert
  151. input bool Medium_Impact_News = true; // Medium Impact News
  152. input int Medium_Start_Time = 60; // Stop Trade before medium News (min)
  153. input int Medium_Stop_Time = 15; // Stop Trade after medium News (min)
  154. input bool show_medium_line = true; // Show vertical Line when medium news comes
  155. input bool Low_Impact_News = true; // Low Impact News
  156. input int Low_Start_Time = 60; // Stop Trade before low News (min)
  157. input int Low_Stop_Time = 15; // Stop Trade after low News (min)
  158. input bool show_low_line = true; // Show vertical Line when low news comes
  159. // Global Variables
  160. static double tickCurrentBid = 0;
  161. double tickPreviousBid = 0;
  162. static double tickCurrentAsk = 0;
  163. double tickPreviousAsk = 0;
  164. int newYorkStartTime = 0, newYorkStartMin = 0, newYorkEndHour = 0, newYorkEndMin = 0;
  165. datetime newYorkStartTrading = 0, newYorkEndTrading = 0;
  166. int GMT_Broker_Time = +2; // GMT_Broker_Time Time of your Broker
  167. int gmt = 0; // GMT_Broker_Time Time of your Broker
  168. string Lname="newsLabel3";
  169. double levelsAre[];
  170. selectDay newYorkSessionDay = curr; // Select Day for Start Time
  171. //+------------------------------------------------------------------+
  172. //| |
  173. //+------------------------------------------------------------------+
  174. int OnInit()
  175. {
  176. //---
  177. Print(" OnInIt. ");
  178. trade.SetExpertMagicNumber(magic_no);
  179. trade.SetDeviationInPoints(maxSlippage);
  180. trade.SetTypeFilling(ORDER_FILLING_IOC);
  181. trade.LogLevel(LOG_LEVEL_ALL);
  182. trade.SetAsyncMode(false);
  183. if(!MQLInfoInteger(MQL_TESTER))
  184. {
  185. loadNewTradeStoreFile();
  186. }
  187. int filehandle = FileOpen(dataFileName, FILE_READ | FILE_CSV | FILE_COMMON | FILE_ANSI);
  188. if(filehandle != INVALID_HANDLE)
  189. {
  190. Print(" Valid Handler. ");
  191. while(!FileIsEnding(filehandle))
  192. {
  193. string orderToRead = FileReadString(filehandle);
  194. string orderData[];
  195. //Print("Data: ", OrderToRead);
  196. StringSplit(orderToRead, StringGetCharacter(",",0), orderData);
  197. Print("Array Size: ", ArraySize(orderData));
  198. Print(" Order is: ", orderToRead);
  199. for(int i = 0 ; i < ArraySize(orderData) ; i++)
  200. {
  201. Print(" Order Data: ", orderData[i], " i: ", i);
  202. }
  203. if(ArraySize(orderData) >= 8)
  204. {
  205. if(orderData[0] == Symbol())
  206. {
  207. // store into local variables first (trim if needed)
  208. ulong buy_ticket_local = (ulong)-1; // keep -1 as per your convention
  209. ulong sell_ticket_local = (ulong)-1;
  210. string symbol_local = orderData[0];
  211. double price_local = StringToDouble(orderData[1]);
  212. double sl_buy_local = StringToDouble(orderData[2]);
  213. double tp_buy_local = StringToDouble(orderData[3]);
  214. double sl_sell_local = StringToDouble(orderData[4]);
  215. double tp_sell_local = StringToDouble(orderData[5]);
  216. // if your CSV has extra fields (tp2,tp3, etc.) parse here as needed
  217. datetime start_local = StringToTime(orderData[6]);
  218. datetime end_local = StringToTime(orderData[7]);
  219. if(orderData[6] == "0" || orderData[6] == NULL)
  220. {
  221. start_local = 0;
  222. }
  223. if(orderData[7] == "0" || orderData[7] == NULL)
  224. {
  225. end_local = 0;
  226. }
  227. ArrayResize(levelsAre,ArraySize(levelsAre)+1);
  228. levelsAre[ArraySize(levelsAre) - 1] = price_local;
  229. // OPTIONAL: only add when price == 0:
  230. // if(MathAbs(price_local) > 1e-9) { Print("Skipped: price != 0"); continue; }
  231. bool buy_virtual_tp_hit = true;
  232. bool sell_virtual_tp_hit = true;
  233. bool demand_level_hit_first = true;
  234. if(bothHitsSl)
  235. {
  236. buy_virtual_tp_hit = false;
  237. sell_virtual_tp_hit = false;
  238. demand_level_hit_first = false;
  239. }
  240. // call the single-responsibility function that writes into struct array
  241. if(!level_present(price_local))
  242. {
  243. Print(" --------------- Price: ", price_local, " Start Time: ", start_local, " End Time: ", end_local, " --------------------");
  244. addToNewTradeStore(buy_ticket_local, sell_ticket_local,
  245. symbol_local, price_local,
  246. sl_buy_local, tp_buy_local,
  247. sl_sell_local, tp_sell_local,
  248. start_local, end_local,
  249. demand_level_hit_first, buy_virtual_tp_hit, sell_virtual_tp_hit);
  250. }
  251. else
  252. {
  253. Print("Level is already Present. Level: ", price_local);
  254. }
  255. }
  256. }
  257. }
  258. FileClose(filehandle);
  259. }
  260. else
  261. {
  262. Print(" InValid Handler. Error: ", GetLastError());
  263. }
  264. struct_level_check();
  265. print_newTradeStore();
  266. string time[];
  267. StringSplit(startTime,':',time);
  268. newYorkStartTime = (int)StringToInteger(time[0]);
  269. newYorkStartMin = (int)StringToInteger(time[1]);
  270. Print("NewYork Start Time Hour: ",newYorkStartTime," Start Time Min: ",newYorkStartMin);
  271. time[0] = "";
  272. time[1] = "";
  273. StringSplit(endTime,':',time);
  274. newYorkEndHour = (int)StringToInteger(time[0]);
  275. newYorkEndMin = (int)StringToInteger(time[1]);
  276. Print("NewYork End Time Hour: ",newYorkEndHour," End Time Min: ",newYorkEndMin);
  277. StringSplit(startTime,':',time);
  278. int newYorkStartHour = (int)StringToInteger(time[0]);
  279. newYorkStartMin = (int)StringToInteger(time[1]);
  280. EventSetMillisecondTimer(500);
  281. time[0] = "";
  282. time[1] = "";
  283. StringSplit(endTime,':',time);
  284. newYorkEndHour = (int)StringToInteger(time[0]);
  285. newYorkEndMin = (int)StringToInteger(time[1]);
  286. datetime startDateTime;
  287. MqlDateTime st;
  288. TimeCurrent(st); // get current date
  289. st.hour = newYorkStartHour;
  290. st.min = newYorkStartMin;
  291. st.sec = 0;
  292. startDateTime = StructToTime(st);
  293. datetime endDateTime;
  294. MqlDateTime et;
  295. TimeCurrent(et); // get current date
  296. et.hour = newYorkEndHour;
  297. et.min = newYorkEndMin;
  298. et.sec = 0;
  299. endDateTime = StructToTime(et);
  300. datetime start_Time = 0, end_Time = 0;
  301. if(startDateTime > endDateTime)
  302. {
  303. Print(" --------------------------- Previous -------------------------------------- ");
  304. newYorkSessionDay = prev;
  305. }
  306. else
  307. {
  308. Print(" --------------------------- Current -------------------------------------- ");
  309. newYorkSessionDay = curr;
  310. }
  311. timeFilter(true);
  312. int timeDifference = (int)TimeCurrent() - (int)TimeGMT();
  313. Print("Time Difference is: ", timeDifference);
  314. if(timeDifference > 0)
  315. {
  316. GMT_Broker_Time = (int)MathRound((double)timeDifference / 3600.0);
  317. }
  318. else
  319. if(timeDifference < 0)
  320. {
  321. GMT_Broker_Time = (int)MathRound((double)timeDifference / 3600.0);
  322. }
  323. else // timeDifference == 0
  324. {
  325. GMT_Broker_Time = 0;
  326. }
  327. Print("Gmt Time: ", TimeGMT(), " Broker Gmt Time: ", GMT_Broker_Time);
  328. gmt = GMT_Broker_Time;
  329. if(!MQLInfoInteger(MQL_TESTER))
  330. {
  331. if(selectEaType == master)
  332. {
  333. initiateNews(true); // change here
  334. }
  335. else
  336. {
  337. initiateNews(false);
  338. }
  339. }
  340. if(enableDrawLevels)
  341. {
  342. drawLevels();
  343. }
  344. //---
  345. return(INIT_SUCCEEDED);
  346. }
  347. //+------------------------------------------------------------------+
  348. //| Expert deinitialization function |
  349. //+------------------------------------------------------------------+
  350. void OnDeinit(const int reason)
  351. {
  352. //---
  353. ObjectsDeleteAll(0, 0, OBJ_HLINE);
  354. if(!MQLInfoInteger(MQL_TESTER))
  355. {
  356. saveNewTradeStoreFile();
  357. }
  358. }
  359. //+------------------------------------------------------------------+
  360. //| Expert tick function |
  361. //+------------------------------------------------------------------+
  362. void OnTick()
  363. {
  364. bool masterSide = false;
  365. if(selectEaType == master)
  366. {
  367. masterSide = true;
  368. }
  369. else
  370. {
  371. masterSide = false;
  372. }
  373. static int status=-1,preStatus=-1;
  374. if(!MQLInfoInteger(MQL_TESTER))
  375. {
  376. status=returnNewsStatus(High_Impact_News
  377. ,High_Start_Time
  378. ,High_Stop_Time
  379. ,show_high_line
  380. ,Medium_Impact_News
  381. ,Medium_Start_Time
  382. ,Medium_Stop_Time
  383. ,show_medium_line
  384. ,Low_Impact_News
  385. ,Low_Start_Time
  386. ,Low_Stop_Time
  387. ,show_low_line
  388. ,Symbol()
  389. ,MQLInfoString(MQL_PROGRAM_NAME)
  390. ,GMT_Broker_Time
  391. ,Select_News_Line
  392. ,"", masterSide
  393. );
  394. if(status==0)
  395. {
  396. mainActivity();
  397. }
  398. if(status==1 || status==2 || status==3)
  399. {
  400. if(newsClose==0)
  401. {
  402. if(orderCount_1(POSITION_TYPE_BUY,magic_no)>0)
  403. closeTrades(POSITION_TYPE_BUY,magic_no);
  404. if(orderCount_1(POSITION_TYPE_SELL,magic_no)>0)
  405. closeTrades(POSITION_TYPE_SELL,magic_no);
  406. }
  407. else
  408. if(newsClose==1)
  409. {
  410. mainActivity();
  411. }
  412. }
  413. if(status!=preStatus)
  414. {
  415. if(status == 0 && preStatus !=- 1)
  416. {
  417. // if(ObjectFind(0,Lname))
  418. {
  419. // ObjectSetInteger(0,Lname,OBJPROP_COLOR,clrRed);
  420. ObjectSetString(0,Lname,OBJPROP_TEXT,"");
  421. }
  422. Alert("Trading is start");
  423. if(mobileAlert)
  424. SendNotification("Trading is start");
  425. preStatus=status;
  426. }
  427. else
  428. if(status==1)
  429. {
  430. ObjectSetInteger(0,Lname,OBJPROP_COLOR,clrRed);
  431. ObjectSetString(0,Lname,OBJPROP_TEXT,"High Impact News");
  432. Alert("Trading Stop due to high impact news");
  433. if(mobileAlert)
  434. SendNotification("Trading Stop due to high impact news");
  435. preStatus=status;
  436. }
  437. else
  438. if(status==2)
  439. {
  440. ObjectSetInteger(0,Lname,OBJPROP_COLOR,clrBlue);
  441. ObjectSetString(0,Lname,OBJPROP_TEXT,"Medium Impact News");
  442. Alert("Trading Stop due to medium impact news");
  443. if(mobileAlert)
  444. SendNotification("Trading Stop due to medium impact news");
  445. preStatus=status;
  446. }
  447. else
  448. if(status==3)
  449. {
  450. ObjectSetInteger(0,Lname,OBJPROP_COLOR,clrGreen);
  451. ObjectSetString(0,Lname,OBJPROP_TEXT,"Low Impact News");
  452. Alert("Trading Stop due to low impact news");
  453. if(mobileAlert)
  454. SendNotification("Trading Stop due to low impact news");
  455. preStatus=status;
  456. }
  457. }
  458. }
  459. else
  460. {
  461. mainActivity();
  462. }
  463. }
  464. //+------------------------------------------------------------------+
  465. //| |
  466. //+------------------------------------------------------------------+
  467. void mainActivity()
  468. {
  469. //---
  470. if(enableDrawLevels)
  471. {
  472. drawLevels();
  473. }
  474. newBar();
  475. if(indivial_trailing)
  476. {
  477. Individual_Trailing();
  478. }
  479. if(UseBreakEven)
  480. {
  481. breakEven();
  482. }
  483. double Bid = SymbolInfoDouble(Symbol(), SYMBOL_BID);
  484. double Ask = SymbolInfoDouble(Symbol(), SYMBOL_ASK);
  485. if(tickPreviousBid == 0 && tickCurrentBid == 0)
  486. {
  487. tickPreviousBid = Bid;
  488. tickCurrentBid = Bid;
  489. }
  490. else
  491. {
  492. tickPreviousBid = tickCurrentBid;
  493. tickCurrentBid = Bid;
  494. }
  495. if(tickPreviousAsk == 0 && tickCurrentAsk == 0)
  496. {
  497. tickPreviousAsk = Ask;
  498. tickCurrentAsk = Ask;
  499. }
  500. else
  501. {
  502. tickPreviousAsk = tickCurrentAsk;
  503. tickCurrentAsk = Ask;
  504. }
  505. timeFilter(false);
  506. // Comment(" Session Start = ", newYorkStartTrading, " Asian Session End = ", newYorkEndTrading);
  507. if((enableTimeFilter && TimeCurrent() >= newYorkStartTrading && TimeCurrent() <= newYorkEndTrading) || !enableTimeFilter)
  508. {
  509. removeFromStructure();
  510. if(bothHitsSl)
  511. {
  512. virtualSLHitCheck();
  513. }
  514. tradePlacingCheck();
  515. }
  516. }
  517. //+------------------------------------------------------------------+
  518. //+------------------------------------------------------------------+
  519. //| |
  520. //+------------------------------------------------------------------+
  521. bool isTradingAllowedByWeek()
  522. {
  523. if(!enableWeekFilter) // filter disabled -> allow trading
  524. return true;
  525. // validate inputs quickly
  526. if(filterMonthNumber < 1 || filterMonthNumber > 12)
  527. {
  528. PrintFormat("⚠️ filterMonthNumber out of range (%d). Week filter disabled.", filterMonthNumber);
  529. return true;
  530. }
  531. if(filterWeekNumber < 1 || filterWeekNumber > 5)
  532. {
  533. PrintFormat("⚠️ filterWeekNumber out of range (%d). Week filter disabled.", filterWeekNumber);
  534. return true;
  535. }
  536. MqlDateTime t;
  537. TimeToStruct(TimeCurrent(), t); // t.mon (1..12), t.day (1..31)
  538. // if the months don't match, week filter doesn't apply -> allow
  539. if(t.mon != filterMonthNumber)
  540. return true;
  541. // compute week of month: days 1-7 -> week 1, 8-14 -> week 2, etc.
  542. int weekOfMonth = ((t.day - 1) / 7) + 1; // yields 1..5
  543. // if current week equals the filtered week -> block trading (return false)
  544. if(weekOfMonth == filterWeekNumber)
  545. {
  546. return false; // trading NOT allowed this week of the specified month
  547. }
  548. return true; // otherwise allow trading
  549. }
  550. //+------------------------------------------------------------------+
  551. //| |
  552. //+------------------------------------------------------------------+
  553. bool isTradingAllowedByMonth()
  554. {
  555. MqlDateTime t;
  556. TimeToStruct(TimeCurrent(), t);
  557. switch(t.mon)
  558. {
  559. case 1:
  560. return allowJanuary;
  561. case 2:
  562. return allowFebruary;
  563. case 3:
  564. return allowMarch;
  565. case 4:
  566. return allowApril;
  567. case 5:
  568. return allowMay;
  569. case 6:
  570. return allowJune;
  571. case 7:
  572. return allowJuly;
  573. case 8:
  574. return allowAugust;
  575. case 9:
  576. return allowSeptember;
  577. case 10:
  578. return allowOctober;
  579. case 11:
  580. return allowNovember;
  581. case 12:
  582. return allowDecember;
  583. default:
  584. return true; // Safe fallback: allow trading if month invalid
  585. }
  586. }
  587. //+------------------------------------------------------------------+
  588. //| |
  589. //+------------------------------------------------------------------+
  590. bool newBar()
  591. {
  592. static datetime lastbar;
  593. datetime curbar = iTime(Symbol(), PERIOD_CURRENT, 0);
  594. if(lastbar != curbar)
  595. {
  596. lastbar = curbar;
  597. Print(" ---------------------- New Bar :: ---------------------- ",lastbar);
  598. return (true);
  599. }
  600. else
  601. {
  602. return (false);
  603. }
  604. }
  605. //+------------------------------------------------------------------+
  606. //| |
  607. //+------------------------------------------------------------------+
  608. void closeTrades(int type,int magicno)
  609. {
  610. Print("Total order: ",OrdersTotal());
  611. for(int i= PositionsTotal()-1; i>=0; i--)
  612. {
  613. // Print(" Selection: ",OrderSelect(i,SELECT_BY_POS)," i: ",i," OrdersTotal(): ", OrdersTotal());
  614. ulong ticket = PositionGetTicket(i);
  615. if(PositionSelectByTicket(ticket))
  616. {
  617. if(PositionGetInteger(POSITION_TYPE) == type)
  618. {
  619. if(PositionGetInteger(POSITION_MAGIC) == magicno && PositionGetString(POSITION_SYMBOL) == Symbol())
  620. {
  621. //trade.PositionClose(PositionGetInteger(POSITION_TICKET))
  622. if(!trade.PositionClose(PositionGetInteger(POSITION_TICKET)))
  623. {Print("Problem in closing order order ",PositionGetInteger(POSITION_TICKET)); }
  624. else
  625. {
  626. Print("Order Closed by closeTrades() new filter",PositionGetInteger(POSITION_TICKET));
  627. }
  628. }
  629. }
  630. }
  631. }
  632. }
  633. //+------------------------------------------------------------------+
  634. //| |
  635. //+------------------------------------------------------------------+
  636. int orderCount_1(int type,int magic)
  637. {
  638. int count1=0;
  639. for(int i= PositionsTotal()-1; i>=0; i--)
  640. {
  641. // Print(" Selection: ",OrderSelect(i,SELECT_BY_POS)," i: ",i," OrdersTotal(): ", OrdersTotal());
  642. ulong ticket = PositionGetTicket(i);
  643. if(PositionSelectByTicket(ticket))
  644. {
  645. // if(PositionGetInteger(POSITION_TYPE) == POSITION_TYPE_BUY || PositionGetInteger(POSITION_TYPE) == POSITION_TYPE_SELL)
  646. if(PositionGetInteger(POSITION_MAGIC) == magic && PositionGetString(POSITION_SYMBOL) == Symbol())
  647. {
  648. //trade.PositionClose(PositionGetInteger(POSITION_TICKET))
  649. if(PositionGetInteger(POSITION_TYPE) == type)
  650. {
  651. count1++;
  652. }
  653. }
  654. }
  655. }
  656. return count1;
  657. }
  658. //+------------------------------------------------------------------+
  659. //| |
  660. //+------------------------------------------------------------------+
  661. int orderCount(int type)
  662. {
  663. int count = 0;
  664. for(int i= PositionsTotal()-1; i>=0; i--)
  665. {
  666. ulong ticket = PositionGetTicket(i);
  667. if(PositionSelectByTicket(ticket))
  668. {
  669. if(PositionGetInteger(POSITION_MAGIC) == magic_no && PositionGetString(POSITION_SYMBOL) == Symbol())
  670. {
  671. if(PositionGetInteger(POSITION_TYPE) == type)
  672. {
  673. count++;
  674. }
  675. }
  676. }
  677. }
  678. return count;
  679. }
  680. //+------------------------------------------------------------------+
  681. //| |
  682. //+------------------------------------------------------------------+
  683. bool level_present(double priceIs)
  684. {
  685. for(int i = 0 ; i < MaxOrders ; i++)
  686. {
  687. if(newTradeStore[i].price > 0)
  688. {
  689. if(priceIs == newTradeStore[i].price)
  690. {
  691. return true;
  692. }
  693. }
  694. }
  695. return false;
  696. }
  697. //+------------------------------------------------------------------+
  698. //| |
  699. //+------------------------------------------------------------------+
  700. void struct_level_check()
  701. {
  702. for(int i = 0; i < MaxOrders; i++)
  703. {
  704. if(newTradeStore[i].price > 0)
  705. {
  706. bool found = false;
  707. for(int j = 0; j < ArraySize(levelsAre); j++)
  708. {
  709. if(newTradeStore[i].price == levelsAre[j])
  710. {
  711. found = true;
  712. break;
  713. }
  714. }
  715. if(!found)
  716. {
  717. Print("Price not found in levelsAre[] -> index:", i, " | price:", newTradeStore[i].price);
  718. newTradeStore[i].buy_ticket = (ulong)-1;
  719. newTradeStore[i].sell_ticket = (ulong)-1;
  720. bool buy_virtual_tp_hit = true;
  721. bool sell_virtual_tp_hit = true;
  722. if(bothHitsSl)
  723. {
  724. buy_virtual_tp_hit = false;
  725. sell_virtual_tp_hit = false;
  726. }
  727. newTradeStore[i].buy_hit_virtual_sl = buy_virtual_tp_hit;
  728. newTradeStore[i].sell_hit_virtual_sl = sell_virtual_tp_hit;
  729. newTradeStore[i].symbol = "";
  730. newTradeStore[i].price = 0.0;
  731. newTradeStore[i].stop_loss_buy = 0.0;
  732. newTradeStore[i].take_profit_buy = 0.0;
  733. newTradeStore[i].stop_loss_sell = 0.0;
  734. newTradeStore[i].take_profit_sell = 0.0;
  735. newTradeStore[i].start_time = 0;
  736. newTradeStore[i].end_time = 0;
  737. return;
  738. }
  739. }
  740. }
  741. return;
  742. }
  743. //+------------------------------------------------------------------+
  744. //| |
  745. //+------------------------------------------------------------------+
  746. void print_newTradeStore()
  747. {
  748. bool anyPrinted = false;
  749. Print("=== newTradeStore DUMP ===");
  750. for(int i = 0; i < MaxOrders; i++)
  751. {
  752. // only print populated slots (price > 0)
  753. if(newTradeStore[i].price > 0.0)
  754. {
  755. anyPrinted = true;
  756. // convert booleans to readable text
  757. string buyHit = newTradeStore[i].buy_hit_virtual_sl ? "true" : "false";
  758. string sellHit = newTradeStore[i].sell_hit_virtual_sl ? "true" : "false";
  759. // header line for the entry
  760. Print("---- Entry ", i, " ----");
  761. // summary line (symbol, price, times)
  762. Print(" symbol:", newTradeStore[i].symbol,
  763. " | price:", DoubleToString(newTradeStore[i].price, Digits()),
  764. " | start:", IntegerToString(newTradeStore[i].start_time),
  765. " | end:", IntegerToString(newTradeStore[i].end_time));
  766. // ticket line
  767. Print(" tickets -> buy:", newTradeStore[i].buy_ticket,
  768. " | sell:", newTradeStore[i].sell_ticket);
  769. // flags line
  770. Print(" flags -> buy_hit_virtual_sl:", buyHit,
  771. " | sell_hit_virtual_sl:", sellHit,
  772. " | bothHitsSl:", (bothHitsSl ? "true" : "false"));
  773. // SL/TP line
  774. Print(" SL/TP -> buySL:", DoubleToString(newTradeStore[i].stop_loss_buy, Digits()),
  775. " | buyTP:", DoubleToString(newTradeStore[i].take_profit_buy, Digits()),
  776. " | sellSL:", DoubleToString(newTradeStore[i].stop_loss_sell, Digits()),
  777. " | sellTP:", DoubleToString(newTradeStore[i].take_profit_sell, Digits()));
  778. }
  779. }
  780. if(!anyPrinted)
  781. Print(" (no active newTradeStore entries found)");
  782. Print("=== end dump ===");
  783. }
  784. //+------------------------------------------------------------------+
  785. //| |
  786. //+------------------------------------------------------------------+
  787. void addToNewTradeStore(ulong r_buy_ticket, ulong r_sell_ticket,
  788. string r_symbol, double r_price,
  789. double r_stop_loss_buy, double r_take_profit_buy,
  790. double r_stop_loss_sell, double r_take_profit_sell,
  791. datetime r_start_time, datetime r_end_time, bool r_demand_level_hit, bool r_buy_hit_sl, bool r_sell_hit_sl)
  792. {
  793. Print(" Tier 1. ");
  794. for(int i = 0; i < MaxOrders; i++)
  795. {
  796. // treat slot as empty when both tickets are -1 (same convention as constructor)
  797. if(newTradeStore[i].buy_ticket == -1 && newTradeStore[i].sell_ticket == -1)
  798. {
  799. if(newTradeStore[i].price == 0)
  800. {
  801. newTradeStore[i].buy_ticket = r_buy_ticket;
  802. newTradeStore[i].sell_ticket = r_sell_ticket;
  803. newTradeStore[i].symbol = r_symbol;
  804. newTradeStore[i].price = r_price;
  805. newTradeStore[i].stop_loss_buy = r_stop_loss_buy;
  806. newTradeStore[i].take_profit_buy = r_take_profit_buy;
  807. newTradeStore[i].stop_loss_sell = r_stop_loss_sell;
  808. newTradeStore[i].take_profit_sell = r_take_profit_sell;
  809. newTradeStore[i].start_time = r_start_time;
  810. newTradeStore[i].end_time = r_end_time;
  811. newTradeStore[i].demand_level_hit = r_demand_level_hit;
  812. newTradeStore[i].buy_hit_virtual_sl = r_buy_hit_sl;
  813. newTradeStore[i].sell_hit_virtual_sl = r_sell_hit_sl;
  814. Print("Stored -> idx: ", i,
  815. " | Symbol: ", newTradeStore[i].symbol,
  816. " | price: ", DoubleToString(newTradeStore[i].price, Digits()),
  817. " | Sl Buy: ", DoubleToString(newTradeStore[i].stop_loss_buy, Digits()),
  818. " | Tp Buy: ", DoubleToString(newTradeStore[i].take_profit_buy, Digits()),
  819. "\n | Sl Sell: ", DoubleToString(newTradeStore[i].stop_loss_sell, Digits()),
  820. " | Tp Sell: ", DoubleToString(newTradeStore[i].take_profit_sell, Digits()),
  821. " | start: ", TimeToString(newTradeStore[i].start_time, TIME_DATE|TIME_SECONDS),
  822. " | end: ", TimeToString(newTradeStore[i].end_time, TIME_DATE|TIME_SECONDS),
  823. " | Demand Level Hit: ", newTradeStore[i].demand_level_hit,
  824. " | Buy Virtal Sl Hit: ", newTradeStore[i].buy_hit_virtual_sl,
  825. " | Sell Virtual Sl Hit: ", newTradeStore[i].sell_hit_virtual_sl);
  826. break;
  827. }
  828. }
  829. }
  830. }
  831. //+------------------------------------------------------------------+
  832. //| |
  833. //+------------------------------------------------------------------+
  834. void tradePlacingCheck()
  835. {
  836. for(int i = 0; i < MaxOrders; i++)
  837. {
  838. if(newTradeStore[i].buy_ticket == -1 && newTradeStore[i].sell_ticket == -1)
  839. {
  840. if(newTradeStore[i].price > 0)
  841. {
  842. if((TimeCurrent() > newTradeStore[i].start_time && TimeCurrent() < newTradeStore[i].end_time) || (newTradeStore[i].start_time == 0 || newTradeStore[i].end_time == 0))
  843. {
  844. if(newTradeStore[i].buy_hit_virtual_sl == true && newTradeStore[i].sell_hit_virtual_sl == true)
  845. {
  846. double levelPriceIs = newTradeStore[i].price;
  847. if((tickPreviousBid > levelPriceIs && tickCurrentBid <= levelPriceIs) ||
  848. (tickPreviousBid < levelPriceIs && tickCurrentBid >= levelPriceIs))
  849. {
  850. Print(" ------------------- Level Crossed. Level is: ", levelPriceIs, " -------------------- ");
  851. if(isTradingAllowedByWeek())
  852. {
  853. if(isTradingAllowedByMonth())
  854. {
  855. if((enableSpreadFilter && spreadFilter()) || !enableSpreadFilter)
  856. {
  857. ulong buyTicket = -1, sellTicket = -1;
  858. if(countLiveTrades() < maxTrades)
  859. {
  860. buyTicket = placeBuyTrade(newTradeStore[i].stop_loss_buy, newTradeStore[i].take_profit_buy);
  861. sellTicket = placeSellTrade(newTradeStore[i].stop_loss_sell, newTradeStore[i].take_profit_sell);
  862. newTradeStore[i].buy_ticket = buyTicket;
  863. newTradeStore[i].sell_ticket = sellTicket;
  864. }
  865. }
  866. }
  867. }
  868. }
  869. }
  870. }
  871. }
  872. }
  873. }
  874. }
  875. //+------------------------------------------------------------------+
  876. //| |
  877. //+------------------------------------------------------------------+
  878. void draw_lines(string name, datetime dateTime, double price, color selectColor, long lineStyle)
  879. {
  880. if(!ObjectCreate(0, name, OBJ_HLINE, 0, dateTime, price))
  881. {
  882. Print(" Error in creating ", name," : ","line: "," ",GetLastError());
  883. }
  884. else
  885. {
  886. ObjectSetInteger(0, name, OBJPROP_COLOR, selectColor);
  887. ObjectSetInteger(0, name, OBJPROP_STYLE, lineStyle);
  888. }
  889. }
  890. //+------------------------------------------------------------------+
  891. //| |
  892. //+------------------------------------------------------------------+
  893. void drawLevels()
  894. {
  895. for(int i = 0; i < MaxOrders; i++)
  896. {
  897. if(newTradeStore[i].price > 0)
  898. {
  899. if((TimeCurrent() > newTradeStore[i].start_time && TimeCurrent() < newTradeStore[i].end_time) || (newTradeStore[i].start_time == 0 || newTradeStore[i].end_time == 0))
  900. {
  901. if(ObjectFind(0, "level" + (string)newTradeStore[i].price) < 0)
  902. {
  903. draw_lines("level" + (string)newTradeStore[i].price, TimeCurrent(), newTradeStore[i].price, clrAqua, STYLE_SOLID);
  904. }
  905. }
  906. else
  907. {
  908. if(ObjectFind(0, "level" + (string)newTradeStore[i].price) >= 0)
  909. {
  910. ObjectDelete(0, "level" + (string)newTradeStore[i].price);
  911. }
  912. }
  913. }
  914. }
  915. }
  916. //+------------------------------------------------------------------+
  917. //| |
  918. //+------------------------------------------------------------------+
  919. ulong placeBuyTrade(double stoploss, double takeprofit)
  920. {
  921. double buySL = 0, buyTp=0;
  922. //openPrice = SymbolInfoDouble(Symbol(),SYMBOL_ASK);
  923. double Ask = SymbolInfoDouble(Symbol(),SYMBOL_ASK);
  924. double Bid = SymbolInfoDouble(Symbol(),SYMBOL_BID);
  925. if(useTpSlPips)
  926. {
  927. if(stopLoss != 0)
  928. {
  929. buySL = Ask - (stopLoss * Point());
  930. }
  931. if(takeProfit != 0)
  932. {
  933. buyTp = Ask + (takeProfit * Point());
  934. }
  935. }
  936. else
  937. {
  938. if(stoploss > 0)
  939. {
  940. buySL = stoploss;
  941. }
  942. if(takeprofit > 0)
  943. {
  944. buyTp = takeprofit;
  945. }
  946. }
  947. double distance = MathAbs((Ask - buySL) / Point());
  948. if(trade.PositionOpen(Symbol(),ORDER_TYPE_BUY,getLot(distance),Ask,buySL,buyTp,tradeComment+" Buy"))
  949. {
  950. Print("Buy Trade Placed: ",trade.ResultOrder());
  951. return trade.ResultOrder();
  952. }
  953. else
  954. {
  955. Print("Error in placing Buy: "+Symbol()+" ",GetLastError());
  956. return -1;
  957. }
  958. return -1;
  959. }
  960. //+------------------------------------------------------------------+
  961. //| |
  962. //+------------------------------------------------------------------+
  963. ulong placeSellTrade(double stoploss, double takeprofit)
  964. {
  965. double sellSL = 0, sellTp = 0;
  966. double Ask = SymbolInfoDouble(Symbol(),SYMBOL_ASK);
  967. double Bid = SymbolInfoDouble(Symbol(),SYMBOL_BID);
  968. if(useTpSlPips)
  969. {
  970. if(stopLoss != 0)
  971. {
  972. sellSL = Bid + (stopLoss * Point());
  973. }
  974. if(takeProfit != 0)
  975. {
  976. sellTp = Bid - (takeProfit * Point());
  977. }
  978. }
  979. else
  980. {
  981. if(stoploss > 0)
  982. {
  983. sellSL = stoploss;
  984. }
  985. if(takeprofit > 0)
  986. {
  987. sellTp = takeprofit;
  988. }
  989. }
  990. double distance = MathAbs((Bid - sellSL) / Point());
  991. if(trade.PositionOpen(Symbol(),ORDER_TYPE_SELL,getLot(distance),Bid,sellSL,sellTp,tradeComment+ " Sell"))
  992. {
  993. Print("Sell Trade PLaced: ",trade.ResultOrder());
  994. return trade.ResultOrder();
  995. }
  996. else
  997. {
  998. Print("Error in placing Sell: "+Symbol()+" ",GetLastError());
  999. return -1;
  1000. }
  1001. return -1;
  1002. }
  1003. //+------------------------------------------------------------------+
  1004. //| |
  1005. //+------------------------------------------------------------------+
  1006. double getLot(double stop_loss)
  1007. {
  1008. Print("Tick Value: ",SymbolInfoDouble(Symbol(),SYMBOL_TRADE_TICK_VALUE));
  1009. Print("Tick Size: ",SymbolInfoDouble(Symbol(),SYMBOL_TRADE_TICK_SIZE));
  1010. double modeTickV=SymbolInfoDouble(Symbol(),SYMBOL_TRADE_TICK_VALUE)
  1011. ,modeTickS=SymbolInfoDouble(Symbol(),SYMBOL_TRADE_TICK_SIZE);
  1012. // Print("Pip value: ", NormalizeDouble(((SymbolInfoDouble(Symbol(),SYMBOL_TRADE_TICK_VALUE)/(SymbolInfoDouble(Symbol(),SYMBOL_TRADE_TICK_SIZE)/Point))*10),2));
  1013. double pipvalue = NormalizeDouble(((SymbolInfoDouble(Symbol(),SYMBOL_TRADE_TICK_VALUE)/(SymbolInfoDouble(Symbol(),SYMBOL_TRADE_TICK_SIZE)/Point()))*10),2);
  1014. // pipvalue=NormalizeDouble((modeTickV/modeTickS/Point()),)
  1015. // pipvalue=
  1016. pipvalue = pipvalue / 10;
  1017. double lotSize = lot_amount;
  1018. if(lot_calculator == rsk || lot_calculator == dollar) //calculating risk
  1019. {
  1020. double riskamount = 0;
  1021. if(lot_calculator == rsk)
  1022. {
  1023. riskamount = (risk/100)*AccountInfoDouble(ACCOUNT_BALANCE);
  1024. }
  1025. if(lot_calculator == dollar)
  1026. {
  1027. riskamount = dollars;
  1028. }
  1029. double pipvalue_required=riskamount/stop_loss;
  1030. lotSize = pipvalue_required/pipvalue;
  1031. //sl=riskamount/pipValuelot
  1032. int roundDigit=0;
  1033. double step=SymbolInfoDouble(Symbol(),SYMBOL_VOLUME_STEP);
  1034. while(step<1)
  1035. {
  1036. roundDigit++;
  1037. step=step*10;
  1038. }
  1039. Print("Round Digits:",roundDigit);
  1040. lotSize = NormalizeDouble(lotSize,roundDigit);
  1041. //
  1042. }
  1043. Print(" Before Normalizing Lot Size By Step : ",lotSize);
  1044. lotSize = NormalizeLot(lotSize,SymbolInfoDouble(Symbol(),SYMBOL_VOLUME_STEP));
  1045. Print(" After Normalizing Lot Size By Step : ",lotSize);
  1046. if(lotSize > SymbolInfoDouble(Symbol(),SYMBOL_VOLUME_MAX))
  1047. {
  1048. lotSize=SymbolInfoDouble(Symbol(),SYMBOL_VOLUME_MAX);
  1049. }
  1050. else
  1051. if(lotSize<SymbolInfoDouble(Symbol(),SYMBOL_VOLUME_MIN))
  1052. {
  1053. lotSize=SymbolInfoDouble(Symbol(),SYMBOL_VOLUME_MIN);
  1054. }
  1055. //---
  1056. return lotSize;
  1057. }
  1058. //+------------------------------------------------------------------+
  1059. //| |
  1060. //+------------------------------------------------------------------+
  1061. void timeFilter(bool onInit)
  1062. {
  1063. MqlDateTime sdate,edate;
  1064. datetime start_Time = 0, end_Time = 0;
  1065. if(newYorkSessionDay == prev)
  1066. {
  1067. if(onInit)
  1068. {
  1069. start_Time = iTime(Symbol(),PERIOD_D1,1);
  1070. end_Time = iTime(Symbol(),PERIOD_D1,0);
  1071. }
  1072. else
  1073. {
  1074. start_Time = newYorkStartTrading;
  1075. end_Time = newYorkEndTrading;
  1076. if(TimeCurrent() >= newYorkEndTrading && newYorkEndTrading != 0)
  1077. {
  1078. start_Time = iTime(Symbol(),PERIOD_D1,0);
  1079. end_Time = start_Time + 86400;
  1080. }
  1081. }
  1082. }
  1083. else
  1084. {
  1085. start_Time = iTime(Symbol(),PERIOD_D1,0);
  1086. end_Time = iTime(Symbol(),PERIOD_D1,0);
  1087. }
  1088. if(TimeToStruct(end_Time,edate))
  1089. {
  1090. edate.hour = newYorkEndHour;
  1091. edate.min = newYorkEndMin;
  1092. edate.sec = 0;
  1093. }
  1094. else
  1095. Print("Error in Converting Time: ",GetLastError());
  1096. newYorkEndTrading = StructToTime(edate);
  1097. if(TimeToStruct(start_Time,sdate))
  1098. {
  1099. sdate.hour = newYorkStartTime;
  1100. sdate.min = newYorkStartMin;
  1101. sdate.sec = 0;
  1102. }
  1103. else
  1104. Print("Error in Converting Time: ",GetLastError());
  1105. newYorkStartTrading = StructToTime(sdate);
  1106. // if(onInit)
  1107. //Print("NewYork Start Time ",newYorkStartTrading,"End Date: ",newYorkEndTrading);
  1108. //Print("Edate: ",edate.hour," ",edate.min," Sdate: ",sdate.hour," ",sdate.min);
  1109. }
  1110. //+------------------------------------------------------------------+
  1111. //| |
  1112. //+------------------------------------------------------------------+
  1113. void removeFromStructure()
  1114. {
  1115. for(int i = 0 ; i < MaxOrders ; i++)
  1116. {
  1117. bool isBuyPresent=false, isSellPresent=false;
  1118. if(newTradeStore[i].buy_ticket != -1 && newTradeStore[i].sell_ticket != -1)
  1119. {
  1120. for(int j = PositionsTotal()-1; j>=0; j--)
  1121. {
  1122. ulong ticket = PositionGetTicket(j);
  1123. if(PositionSelectByTicket(ticket))
  1124. {
  1125. if(ticket == newTradeStore[i].buy_ticket)
  1126. {
  1127. isBuyPresent=true;
  1128. }
  1129. }
  1130. }
  1131. for(int j = PositionsTotal()-1; j>=0; j--)
  1132. {
  1133. ulong ticket = PositionGetTicket(j);
  1134. if(PositionSelectByTicket(ticket))
  1135. {
  1136. if(ticket == newTradeStore[i].sell_ticket)
  1137. {
  1138. isSellPresent = true;
  1139. }
  1140. }
  1141. }
  1142. if(!isBuyPresent && !isSellPresent)
  1143. {
  1144. Print("Buy/Sell Ticket is closed so removed from struct. Buy Ticket: ", newTradeStore[i].buy_ticket, " Sell Ticket: ", newTradeStore[i].sell_ticket);
  1145. newTradeStore[i].buy_ticket = (ulong)-1;
  1146. newTradeStore[i].sell_ticket = (ulong)-1;
  1147. bool buy_virtual_tp_hit = true;
  1148. bool sell_virtual_tp_hit = true;
  1149. bool demand_level_hit_value = true;
  1150. if(bothHitsSl)
  1151. {
  1152. buy_virtual_tp_hit = false;
  1153. sell_virtual_tp_hit = false;
  1154. demand_level_hit_value = false;
  1155. }
  1156. newTradeStore[i].buy_hit_virtual_sl = buy_virtual_tp_hit;
  1157. newTradeStore[i].sell_hit_virtual_sl = sell_virtual_tp_hit;
  1158. newTradeStore[i].demand_level_hit = demand_level_hit_value;
  1159. //newTradeStore[i].symbol = "";
  1160. //newTradeStore[i].price = 0.0;
  1161. //newTradeStore[i].stop_loss = 0.0;
  1162. //newTradeStore[i].take_profit = 0.0;
  1163. //newTradeStore[i].start_time = 0;
  1164. //newTradeStore[i].end_time = 0;
  1165. }
  1166. }
  1167. }
  1168. }
  1169. //+------------------------------------------------------------------+
  1170. //| |
  1171. //+------------------------------------------------------------------+
  1172. void virtualSLHitCheck()
  1173. {
  1174. for(int i = 0 ; i < MaxOrders ; i++)
  1175. {
  1176. if(newTradeStore[i].buy_ticket == -1 && newTradeStore[i].sell_ticket == -1)
  1177. {
  1178. if(TimeCurrent() > newTradeStore[i].start_time && TimeCurrent() < newTradeStore[i].end_time)
  1179. {
  1180. if(!newTradeStore[i].demand_level_hit)
  1181. {
  1182. double levelPriceIs = newTradeStore[i].price;
  1183. if((tickPreviousBid > levelPriceIs && tickCurrentBid < levelPriceIs) ||
  1184. (tickPreviousBid < levelPriceIs && tickCurrentBid > levelPriceIs))
  1185. {
  1186. newTradeStore[i].demand_level_hit = true;
  1187. Print(" Demand Level Hit. newTradeStore[i].demand_level_hit: ", newTradeStore[i].demand_level_hit, " Order Price is: ", newTradeStore[i].price, " Time Demand Hit is: ", TimeCurrent());
  1188. }
  1189. }
  1190. if(newTradeStore[i].demand_level_hit)
  1191. {
  1192. double buy_sl = 0, sell_sl = 0;
  1193. if(!useTpSlPips)
  1194. {
  1195. buy_sl = newTradeStore[i].stop_loss_buy;
  1196. sell_sl = newTradeStore[i].stop_loss_sell;
  1197. }
  1198. else
  1199. {
  1200. buy_sl = stopLoss != 0 ? newTradeStore[i].price - (stopLoss * Point()) : 0;
  1201. sell_sl = stopLoss != 0 ? newTradeStore[i].price + (stopLoss * Point()) : 0;
  1202. }
  1203. if(newTradeStore[i].buy_hit_virtual_sl == false)
  1204. {
  1205. if((tickPreviousBid > buy_sl && tickCurrentBid <= buy_sl))
  1206. {
  1207. newTradeStore[i].buy_hit_virtual_sl = true;
  1208. 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());
  1209. }
  1210. }
  1211. if(newTradeStore[i].sell_hit_virtual_sl == false)
  1212. {
  1213. if((tickPreviousAsk < sell_sl && tickCurrentAsk >= sell_sl))
  1214. {
  1215. newTradeStore[i].sell_hit_virtual_sl = true;
  1216. 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());
  1217. }
  1218. }
  1219. }
  1220. }
  1221. }
  1222. }
  1223. }
  1224. //+------------------------------------------------------------------+
  1225. //| |
  1226. //+------------------------------------------------------------------+
  1227. int countLiveTrades()
  1228. {
  1229. int count = 0;
  1230. for(int i = 0; i < PositionsTotal(); i++)
  1231. {
  1232. ulong ticket = PositionGetTicket(i);
  1233. if(PositionSelectByTicket(ticket))
  1234. {
  1235. if(PositionGetInteger(POSITION_MAGIC) == magic_no)
  1236. {
  1237. if(PositionGetString(POSITION_SYMBOL) == Symbol())
  1238. {
  1239. if(PositionGetInteger(POSITION_TYPE) == POSITION_TYPE_BUY || PositionGetInteger(POSITION_TYPE) == POSITION_TYPE_SELL)
  1240. {
  1241. count++;
  1242. }
  1243. }
  1244. }
  1245. }
  1246. }
  1247. return count;
  1248. }
  1249. //+------------------------------------------------------------------+
  1250. //| |
  1251. //+------------------------------------------------------------------+
  1252. bool spreadFilter()
  1253. {
  1254. long spreadIs = SymbolInfoInteger(Symbol(), SYMBOL_SPREAD);
  1255. if(spreadIs > maximumSpread)
  1256. {
  1257. return false;
  1258. }
  1259. return true;
  1260. }
  1261. //+------------------------------------------------------------------+
  1262. //| |
  1263. //+------------------------------------------------------------------+
  1264. void breakEven()
  1265. {
  1266. for(int i = PositionsTotal()-1; i>=0; i--)
  1267. {
  1268. ulong ticket = PositionGetTicket(i);
  1269. string symbol=PositionGetSymbol(i);
  1270. double mySL = 0,newSL = 0;
  1271. double SymbolTickSize = SymbolInfoDouble(symbol, SYMBOL_TRADE_TICK_SIZE);
  1272. ////Print("ticket ",ticket," Symbol : ",symbol);
  1273. if(PositionSelectByTicket(ticket))
  1274. {
  1275. if(PositionGetString(POSITION_SYMBOL)==Symbol() && PositionGetInteger(POSITION_MAGIC) == magic_no)
  1276. {
  1277. if(isCounterpartOpen(ticket))
  1278. {
  1279. // counterpart still open -> skip trailing for this position
  1280. continue;
  1281. }
  1282. //========================================================Buy Condition=========================================================================
  1283. if(PositionGetInteger(POSITION_TYPE) == POSITION_TYPE_BUY)
  1284. {
  1285. mySL = PositionGetDouble(POSITION_PRICE_OPEN) + (breakEvenPoints * SymbolTickSize);
  1286. if(SymbolInfoDouble(Symbol(),SYMBOL_BID) >= mySL && PositionGetDouble(POSITION_PRICE_OPEN) > PositionGetDouble(POSITION_SL))
  1287. {
  1288. newSL= PositionGetDouble(POSITION_PRICE_OPEN) + (breakStopPoint * SymbolTickSize);
  1289. if(trade.PositionModify(ticket,newSL,PositionGetDouble(POSITION_TP)))
  1290. {
  1291. Print("Buy Order BreakEven Successfully ");
  1292. }
  1293. else
  1294. {
  1295. Print("Error in BreakEven Buy Position ",GetLastError());
  1296. }
  1297. }
  1298. }
  1299. //=======================================================Sell condition ===============================================================
  1300. if(PositionGetInteger(POSITION_TYPE) == POSITION_TYPE_SELL)
  1301. {
  1302. mySL = PositionGetDouble(POSITION_PRICE_OPEN) - (breakEvenPoints * SymbolTickSize);
  1303. if(SymbolInfoDouble(Symbol(),SYMBOL_ASK) <= mySL && PositionGetDouble(POSITION_SL) > PositionGetDouble(POSITION_PRICE_OPEN))
  1304. {
  1305. newSL = PositionGetDouble(POSITION_PRICE_OPEN) - (breakStopPoint * SymbolTickSize);
  1306. if(trade.PositionModify(ticket,newSL,PositionGetDouble(POSITION_TP)))
  1307. {
  1308. Print("Order Sell BreakEven Successfully ");
  1309. }
  1310. else
  1311. {
  1312. Print("Error in BreakEven Sell Position ",GetLastError());
  1313. }
  1314. }
  1315. }
  1316. }
  1317. }
  1318. }
  1319. }
  1320. //+------------------------------------------------------------------+
  1321. //| |
  1322. //+------------------------------------------------------------------+
  1323. bool isCounterpartOpen(ulong ticket)
  1324. {
  1325. // scan stored pairs
  1326. for(int k=0; k<MaxOrders; k++)
  1327. {
  1328. // check if this ticket is the buy side in the pair
  1329. if(newTradeStore[k].buy_ticket == ticket)
  1330. {
  1331. ulong other = newTradeStore[k].sell_ticket;
  1332. if(other <= 0)
  1333. return false; // no counterpart recorded -> treat as closed
  1334. // check if counterpart ticket exists in current positions
  1335. for(int p = PositionsTotal()-1; p >= 0; p--)
  1336. {
  1337. ulong t = PositionGetTicket(p);
  1338. if(t == other)
  1339. return true; // counterpart still open
  1340. }
  1341. return false; // counterpart not found -> closed
  1342. }
  1343. // check if this ticket is the sell side in the pair
  1344. if(newTradeStore[k].sell_ticket == ticket)
  1345. {
  1346. ulong other = newTradeStore[k].buy_ticket;
  1347. if(other <= 0)
  1348. return false; // no counterpart recorded -> treat as closed
  1349. for(int p = PositionsTotal()-1; p >= 0; p--)
  1350. {
  1351. ulong t = PositionGetTicket(p);
  1352. if(t == other)
  1353. return true; // counterpart still open
  1354. }
  1355. return false; // counterpart not found -> closed
  1356. }
  1357. }
  1358. // ticket not found in the stored pairs -> treat as no counterpart open
  1359. return false;
  1360. }
  1361. //+------------------------------------------------------------------+
  1362. //| |
  1363. //+------------------------------------------------------------------+
  1364. void Individual_Trailing()
  1365. {
  1366. int openedpositions;
  1367. double mySL,myResult;
  1368. openedpositions=PositionsTotal();
  1369. if((openedpositions>0))
  1370. {
  1371. int totalorders=PositionsTotal();
  1372. for(int i=0; i<totalorders; i++) // scan all orders and positions. ..
  1373. {
  1374. ulong ticket = PositionGetTicket(i);
  1375. if(PositionSelectByTicket(ticket))
  1376. {
  1377. if(PositionGetString(POSITION_SYMBOL)==Symbol() && PositionGetInteger(POSITION_MAGIC) == magic_no) // only look if mygrid and symbol. ..
  1378. {
  1379. if(isCounterpartOpen(ticket))
  1380. {
  1381. // counterpart still open -> skip trailing for this position
  1382. continue;
  1383. }
  1384. double SymbolAsk = SymbolInfoDouble(PositionGetString(POSITION_SYMBOL), SYMBOL_ASK);
  1385. double SymbolBid = SymbolInfoDouble(PositionGetString(POSITION_SYMBOL), SYMBOL_BID);
  1386. int SymbolDigits = (int)SymbolInfoInteger(PositionGetString(POSITION_SYMBOL), SYMBOL_DIGITS);
  1387. double SymbolTickSize = SymbolInfoDouble(PositionGetString(POSITION_SYMBOL), SYMBOL_TRADE_TICK_SIZE);
  1388. int type= (int)PositionGetInteger(POSITION_TYPE);
  1389. if(type==POSITION_TYPE_BUY) // its a long position
  1390. {
  1391. mySL=NormalizeDouble(SymbolAsk-(ts*SymbolTickSize),Digits()); // new SL
  1392. double startSl=PositionGetDouble(POSITION_PRICE_OPEN)+(ts_sl*SymbolTickSize);
  1393. if(PositionGetDouble(POSITION_SL) != mySL)
  1394. if(mySL>PositionGetDouble(POSITION_SL) && SymbolAsk>=startSl)
  1395. {
  1396. myResult=trade.PositionModify(ticket,mySL,PositionGetDouble(POSITION_TP)); //OrderModify(OrderTicket(),OrderOpenPrice(),mySL,OrderTakeProfit(),0,clrGreen);
  1397. if(!myResult)
  1398. {
  1399. Print(" Buy Trade Trailing Error: ",GetLastError());
  1400. }
  1401. }
  1402. }
  1403. if(type==POSITION_TYPE_SELL)
  1404. {
  1405. mySL=NormalizeDouble(SymbolBid+(ts*SymbolTickSize),Digits()); // new SL
  1406. double startSlSell=PositionGetDouble(POSITION_PRICE_OPEN)-(ts_sl*SymbolTickSize);
  1407. if(PositionGetDouble(POSITION_SL) != mySL)
  1408. if(((mySL<PositionGetDouble(POSITION_SL)) || (PositionGetDouble(POSITION_SL)<SymbolTickSize)) && SymbolBid<=startSlSell)
  1409. {
  1410. myResult=trade.PositionModify(ticket,mySL,PositionGetDouble(POSITION_TP)); //OrderModify(OrderTicket(),OrderOpenPrice(),mySL,OrderTakeProfit(),0,clrRed);
  1411. if(!myResult)
  1412. {
  1413. Print(" Sell Trade Trailing Error: ",GetLastError());
  1414. }
  1415. }
  1416. }
  1417. }
  1418. }
  1419. }
  1420. }
  1421. }
  1422. //+------------------------------------------------------------------+
  1423. //| |
  1424. //+------------------------------------------------------------------+
  1425. void saveNewTradeStoreFile()
  1426. {
  1427. // don't run in strategy tester
  1428. if(MQLInfoInteger(MQL_TESTER))
  1429. return;
  1430. string file_name = "new_trade_store_updated.csv";
  1431. int fileHandle = FileOpen(file_name,
  1432. FILE_WRITE | FILE_CSV | FILE_COMMON |
  1433. FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_READ);
  1434. if(fileHandle == INVALID_HANDLE)
  1435. {
  1436. PrintFormat("saveNewTradeStoreFile() -> Cannot open file '%s'. Error: %d", file_name, GetLastError());
  1437. return;
  1438. }
  1439. // header (optional) - comment out if you don't want header
  1440. //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";
  1441. //FileWriteString(fileHandle, header);
  1442. for(int i = 0; i < MaxOrders; i++)
  1443. {
  1444. // if(newTradeStore[i].buy_ticket != -1 && newTradeStore[i].sell_ticket != -1)
  1445. {
  1446. // decide whether this slot has useful data:
  1447. // you can tweak this condition as you prefer (symbol != "" is simple)
  1448. bool slotPopulated = (StringLen(newTradeStore[i].symbol) > 0)
  1449. || (newTradeStore[i].price != 0.0)
  1450. || (newTradeStore[i].start_time != 0);
  1451. if(!slotPopulated)
  1452. continue;
  1453. // convert values to strings
  1454. string buyTicketStr = IntegerToString((long)newTradeStore[i].buy_ticket);
  1455. string sellTicketStr = IntegerToString((long)newTradeStore[i].sell_ticket);
  1456. string priceStr = DoubleToString(newTradeStore[i].price, Digits());
  1457. string slBuyStr = DoubleToString(newTradeStore[i].stop_loss_buy, Digits());
  1458. string tpBuyStr = DoubleToString(newTradeStore[i].take_profit_buy, Digits());
  1459. string slSellStr = DoubleToString(newTradeStore[i].stop_loss_sell, Digits());
  1460. string tpSellStr = DoubleToString(newTradeStore[i].take_profit_sell, Digits());
  1461. string startTimeStr = (newTradeStore[i].start_time != 0) ? TimeToString(newTradeStore[i].start_time, TIME_DATE|TIME_SECONDS) : "";
  1462. string endTimeStr = (newTradeStore[i].end_time != 0) ? TimeToString(newTradeStore[i].end_time, TIME_DATE|TIME_SECONDS) : "";
  1463. string buyHitStr = ""; // IntegerToString(newTradeStore[i].buy_hit_virtual_sl ? 1 : 0);
  1464. string sellHitStr = ""; // IntegerToString(newTradeStore[i].sell_hit_virtual_sl ? 1 : 0);
  1465. string demandHitStr = "";
  1466. if(newTradeStore[i].buy_hit_virtual_sl == true)
  1467. {
  1468. buyHitStr = "true";
  1469. }
  1470. else
  1471. {
  1472. buyHitStr = "false";
  1473. }
  1474. if(newTradeStore[i].sell_hit_virtual_sl == true)
  1475. {
  1476. sellHitStr = "true";
  1477. }
  1478. else
  1479. {
  1480. sellHitStr = "false";
  1481. }
  1482. if(newTradeStore[i].demand_level_hit == true)
  1483. {
  1484. demandHitStr = "true";
  1485. }
  1486. else
  1487. {
  1488. demandHitStr = "false";
  1489. }
  1490. // build CSV line and write
  1491. string line = buyTicketStr + "," + sellTicketStr + "," +
  1492. newTradeStore[i].symbol + "," +
  1493. priceStr + "," + slBuyStr + "," + tpBuyStr + "," +
  1494. slSellStr + "," + tpSellStr + "," +
  1495. startTimeStr + "," + endTimeStr + "," +
  1496. demandHitStr + "," + buyHitStr + "," + sellHitStr + "\r\n";
  1497. FileWriteString(fileHandle, line);
  1498. }
  1499. }
  1500. FileClose(fileHandle);
  1501. PrintFormat("saveNewTradeStoreFile() -> saved to '%s'.", file_name);
  1502. }
  1503. //+------------------------------------------------------------------+
  1504. //| |
  1505. //+------------------------------------------------------------------+
  1506. void loadNewTradeStoreFile()
  1507. {
  1508. if(MQLInfoInteger(MQL_TESTER))
  1509. return;
  1510. string file_name = "new_trade_store_updated.csv";
  1511. int fileHandle = FileOpen(file_name,
  1512. FILE_READ | FILE_CSV | FILE_COMMON |
  1513. FILE_SHARE_READ | FILE_SHARE_WRITE);
  1514. if(fileHandle == INVALID_HANDLE)
  1515. {
  1516. Print("loadNewTradeStoreFile() -> Cannot open file '", file_name, "'. Error: ", GetLastError());
  1517. return;
  1518. }
  1519. // reset defaults
  1520. for(int j = 0; j < MaxOrders; j++)
  1521. {
  1522. newTradeStore[j].buy_ticket = (ulong)-1;
  1523. newTradeStore[j].sell_ticket = (ulong)-1;
  1524. newTradeStore[j].symbol = "";
  1525. newTradeStore[j].price = 0.0;
  1526. newTradeStore[j].stop_loss_buy = 0.0;
  1527. newTradeStore[j].take_profit_buy = 0.0;
  1528. newTradeStore[j].stop_loss_sell = 0.0;
  1529. newTradeStore[j].take_profit_sell = 0.0;
  1530. newTradeStore[j].start_time = 0;
  1531. newTradeStore[j].end_time = 0;
  1532. newTradeStore[j].demand_level_hit = false;
  1533. newTradeStore[j].buy_hit_virtual_sl = false;
  1534. newTradeStore[j].sell_hit_virtual_sl = false;
  1535. }
  1536. int idx = 0;
  1537. while(!FileIsEnding(fileHandle) && idx < MaxOrders)
  1538. {
  1539. string line = FileReadString(fileHandle);
  1540. if(StringLen(line) == 0)
  1541. continue;
  1542. string tokens[];
  1543. int total = StringSplit(line, ',', tokens);
  1544. if(total >= 13)
  1545. {
  1546. // if((ulong)tokens[0] != -1 && (ulong)tokens[1] != -1)
  1547. {
  1548. newTradeStore[idx].buy_ticket = (ulong)tokens[0];
  1549. newTradeStore[idx].sell_ticket = (ulong)tokens[1];
  1550. newTradeStore[idx].symbol = tokens[2];
  1551. newTradeStore[idx].price = StringToDouble(tokens[3]);
  1552. newTradeStore[idx].stop_loss_buy = StringToDouble(tokens[4]);
  1553. newTradeStore[idx].take_profit_buy = StringToDouble(tokens[5]);
  1554. newTradeStore[idx].stop_loss_sell = StringToDouble(tokens[6]);
  1555. newTradeStore[idx].take_profit_sell = StringToDouble(tokens[7]);
  1556. string sStart = tokens[8];
  1557. string sEnd = tokens[9];
  1558. newTradeStore[idx].start_time = (StringLen(sStart) > 0) ? StringToTime(sStart) : 0;
  1559. newTradeStore[idx].end_time = (StringLen(sEnd) > 0) ? StringToTime(sEnd) : 0;
  1560. bool bHit = false;
  1561. bool sHit = false;
  1562. bool dHit = false;
  1563. if(tokens[10] == "true")
  1564. {
  1565. dHit = true;
  1566. }
  1567. else
  1568. {
  1569. dHit = false;
  1570. }
  1571. if(tokens[11] == "true")
  1572. {
  1573. bHit = true;
  1574. }
  1575. else
  1576. {
  1577. bHit = false;
  1578. }
  1579. if(tokens[12] == "true")
  1580. {
  1581. sHit = true;
  1582. }
  1583. else
  1584. {
  1585. sHit = false;
  1586. }
  1587. if(bothHitsSl == false)
  1588. {
  1589. newTradeStore[idx].buy_hit_virtual_sl = true;
  1590. newTradeStore[idx].sell_hit_virtual_sl = true;
  1591. newTradeStore[idx].demand_level_hit = true;
  1592. }
  1593. if(bothHitsSl == true)
  1594. {
  1595. newTradeStore[idx].buy_hit_virtual_sl = bHit;
  1596. newTradeStore[idx].sell_hit_virtual_sl = sHit;
  1597. newTradeStore[idx].demand_level_hit = dHit;
  1598. }
  1599. // --- simple Print instead of PrintFormat ---
  1600. Print(
  1601. "Loaded newTradeStore[", idx, "]:",
  1602. " buy_ticket=", newTradeStore[idx].buy_ticket,
  1603. " sell_ticket=", newTradeStore[idx].sell_ticket,
  1604. " symbol=", newTradeStore[idx].symbol,
  1605. " price=", DoubleToString(newTradeStore[idx].price, Digits()),
  1606. " \n sl buy=", DoubleToString(newTradeStore[idx].stop_loss_buy, Digits()),
  1607. " tp buy=", DoubleToString(newTradeStore[idx].take_profit_buy, Digits()),
  1608. " sl sell=", DoubleToString(newTradeStore[idx].stop_loss_sell, Digits()),
  1609. " tp sell=", DoubleToString(newTradeStore[idx].take_profit_sell, Digits()),
  1610. " start=", (newTradeStore[idx].start_time != 0 ? TimeToString(newTradeStore[idx].start_time, TIME_DATE|TIME_SECONDS) : ""),
  1611. " end=", (newTradeStore[idx].end_time != 0 ? TimeToString(newTradeStore[idx].end_time, TIME_DATE|TIME_SECONDS) : ""),
  1612. " demandHit=", newTradeStore[idx].demand_level_hit,
  1613. " buyHit=", newTradeStore[idx].buy_hit_virtual_sl,
  1614. " sellHit=", newTradeStore[idx].sell_hit_virtual_sl
  1615. );
  1616. idx++;
  1617. }
  1618. }
  1619. else
  1620. {
  1621. Print("loadNewTradeStoreFile(): skipping malformed line (tokens=", total, "): ", line);
  1622. }
  1623. }
  1624. FileClose(fileHandle);
  1625. Print("loadNewTradeStoreFile() -> loaded ", idx, " entries from '", file_name, "'.");
  1626. }
  1627. //+------------------------------------------------------------------+
  1628. //| |
  1629. //+------------------------------------------------------------------+
  1630. double NormalizeLot(double lot, double step)
  1631. {
  1632. double steps = lot / step;
  1633. double rounded_steps = MathRound(steps); // round to nearest whole step
  1634. double rounded_lot = rounded_steps * step;
  1635. return NormalizeDouble(rounded_lot, 2); // 2 decimals for safety
  1636. }
  1637. //+------------------------------------------------------------------+