Sin descripción

vol_shield_v5.mq5 143KB

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