Nenhuma descrição

vol_shield_v5.mq5 142KB

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