説明なし

vol_hedge_strategy_mt5.mq5 127KB

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