Sin descripción

vol_hedge_strategy_mt5.mq5 127KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593
  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. if(!MQLInfoInteger(MQL_TESTER))
  348. {
  349. saveNewTradeStoreFile();
  350. }
  351. }
  352. //+------------------------------------------------------------------+
  353. //| Expert tick function |
  354. //+------------------------------------------------------------------+
  355. void OnTick()
  356. {
  357. bool masterSide = false;
  358. if(selectEaType == master)
  359. {
  360. masterSide = true;
  361. }
  362. else
  363. {
  364. masterSide = false;
  365. }
  366. static int status=-1,preStatus=-1;
  367. if(!MQLInfoInteger(MQL_TESTER))
  368. {
  369. status=returnNewsStatus(High_Impact_News
  370. ,High_Start_Time
  371. ,High_Stop_Time
  372. ,show_high_line
  373. ,Medium_Impact_News
  374. ,Medium_Start_Time
  375. ,Medium_Stop_Time
  376. ,show_medium_line
  377. ,Low_Impact_News
  378. ,Low_Start_Time
  379. ,Low_Stop_Time
  380. ,show_low_line
  381. ,Symbol()
  382. ,MQLInfoString(MQL_PROGRAM_NAME)
  383. ,GMT_Broker_Time
  384. ,Select_News_Line
  385. ,"", masterSide
  386. );
  387. }
  388. else
  389. status=0;
  390. if(status==0)
  391. {
  392. mainActivity();
  393. }
  394. if(status==1 || status==2 || status==3)
  395. {
  396. if(newsClose==0)
  397. {
  398. if(orderCount_1(POSITION_TYPE_BUY,magic_no)>0)
  399. closeTrades(POSITION_TYPE_BUY,magic_no);
  400. if(orderCount_1(POSITION_TYPE_SELL,magic_no)>0)
  401. closeTrades(POSITION_TYPE_SELL,magic_no);
  402. }
  403. else
  404. if(newsClose==1)
  405. {
  406. if((orderCount_1(POSITION_TYPE_BUY,magic_no)>0) || (orderCount_1(POSITION_TYPE_SELL,magic_no)>0))
  407. {
  408. mainActivity();
  409. }
  410. }
  411. }
  412. if(status!=preStatus)
  413. {
  414. if(status==0 && preStatus!=-1)
  415. {
  416. // if(ObjectFind(0,Lname))
  417. {
  418. // ObjectSetInteger(0,Lname,OBJPROP_COLOR,clrRed);
  419. ObjectSetString(0,Lname,OBJPROP_TEXT,"");
  420. }
  421. Alert("Trading is start");
  422. if(mobileAlert)
  423. SendNotification("Trading is start");
  424. preStatus=status;
  425. }
  426. else
  427. if(status==1)
  428. {
  429. ObjectSetInteger(0,Lname,OBJPROP_COLOR,clrRed);
  430. ObjectSetString(0,Lname,OBJPROP_TEXT,"High Impact News");
  431. Alert("Trading Stop due to high impact news");
  432. if(mobileAlert)
  433. SendNotification("Trading Stop due to high impact news");
  434. preStatus=status;
  435. }
  436. else
  437. if(status==2)
  438. {
  439. ObjectSetInteger(0,Lname,OBJPROP_COLOR,clrBlue);
  440. ObjectSetString(0,Lname,OBJPROP_TEXT,"Medium Impact News");
  441. Alert("Trading Stop due to medium impact news");
  442. if(mobileAlert)
  443. SendNotification("Trading Stop due to medium impact news");
  444. preStatus=status;
  445. }
  446. else
  447. if(status==3)
  448. {
  449. ObjectSetInteger(0,Lname,OBJPROP_COLOR,clrGreen);
  450. ObjectSetString(0,Lname,OBJPROP_TEXT,"Low Impact News");
  451. Alert("Trading Stop due to low impact news");
  452. if(mobileAlert)
  453. SendNotification("Trading Stop due to low impact news");
  454. preStatus=status;
  455. }
  456. }
  457. else
  458. {
  459. mainActivity();
  460. }
  461. }
  462. //+------------------------------------------------------------------+
  463. //| |
  464. //+------------------------------------------------------------------+
  465. void mainActivity()
  466. {
  467. //---
  468. newBar();
  469. if(indivial_trailing)
  470. {
  471. Individual_Trailing();
  472. }
  473. if(UseBreakEven)
  474. {
  475. breakEven();
  476. }
  477. double Bid = SymbolInfoDouble(Symbol(), SYMBOL_BID);
  478. double Ask = SymbolInfoDouble(Symbol(), SYMBOL_ASK);
  479. if(tickPreviousBid == 0 && tickCurrentBid == 0)
  480. {
  481. tickPreviousBid = Bid;
  482. tickCurrentBid = Bid;
  483. }
  484. else
  485. {
  486. tickPreviousBid = tickCurrentBid;
  487. tickCurrentBid = Bid;
  488. }
  489. if(tickPreviousAsk == 0 && tickCurrentAsk == 0)
  490. {
  491. tickPreviousAsk = Ask;
  492. tickCurrentAsk = Ask;
  493. }
  494. else
  495. {
  496. tickPreviousAsk = tickCurrentAsk;
  497. tickCurrentAsk = Ask;
  498. }
  499. timeFilter(false);
  500. Comment(" Session Start = ", newYorkStartTrading, " Asian Session End = ", newYorkEndTrading);
  501. if((enableTimeFilter && TimeCurrent() >= newYorkStartTrading && TimeCurrent() <= newYorkEndTrading) || !enableTimeFilter)
  502. {
  503. removeFromStructure();
  504. if(bothHitsSl)
  505. {
  506. virtualSLHitCheck();
  507. }
  508. tradePlacingCheck();
  509. }
  510. }
  511. //+------------------------------------------------------------------+
  512. //+------------------------------------------------------------------+
  513. //| |
  514. //+------------------------------------------------------------------+
  515. bool isTradingAllowedByWeek()
  516. {
  517. if(!enableWeekFilter) // filter disabled -> allow trading
  518. return true;
  519. // validate inputs quickly
  520. if(filterMonthNumber < 1 || filterMonthNumber > 12)
  521. {
  522. PrintFormat("⚠️ filterMonthNumber out of range (%d). Week filter disabled.", filterMonthNumber);
  523. return true;
  524. }
  525. if(filterWeekNumber < 1 || filterWeekNumber > 5)
  526. {
  527. PrintFormat("⚠️ filterWeekNumber out of range (%d). Week filter disabled.", filterWeekNumber);
  528. return true;
  529. }
  530. MqlDateTime t;
  531. TimeToStruct(TimeCurrent(), t); // t.mon (1..12), t.day (1..31)
  532. // if the months don't match, week filter doesn't apply -> allow
  533. if(t.mon != filterMonthNumber)
  534. return true;
  535. // compute week of month: days 1-7 -> week 1, 8-14 -> week 2, etc.
  536. int weekOfMonth = ((t.day - 1) / 7) + 1; // yields 1..5
  537. // if current week equals the filtered week -> block trading (return false)
  538. if(weekOfMonth == filterWeekNumber)
  539. {
  540. return false; // trading NOT allowed this week of the specified month
  541. }
  542. return true; // otherwise allow trading
  543. }
  544. //+------------------------------------------------------------------+
  545. //| |
  546. //+------------------------------------------------------------------+
  547. bool newBar()
  548. {
  549. static datetime lastbar;
  550. datetime curbar = iTime(Symbol(), PERIOD_CURRENT, 0);
  551. if(lastbar != curbar)
  552. {
  553. lastbar = curbar;
  554. Print(" ---------------------- New Bar :: ---------------------- ",lastbar);
  555. return (true);
  556. }
  557. else
  558. {
  559. return (false);
  560. }
  561. }
  562. //+------------------------------------------------------------------+
  563. //| |
  564. //+------------------------------------------------------------------+
  565. void closeTrades(int type,int magicno)
  566. {
  567. Print("Total order: ",OrdersTotal());
  568. for(int i= PositionsTotal()-1; i>=0; i--)
  569. {
  570. // Print(" Selection: ",OrderSelect(i,SELECT_BY_POS)," i: ",i," OrdersTotal(): ", OrdersTotal());
  571. ulong ticket = PositionGetTicket(i);
  572. if(PositionSelectByTicket(ticket))
  573. {
  574. if(PositionGetInteger(POSITION_TYPE) == type)
  575. {
  576. if(PositionGetInteger(POSITION_MAGIC) == magicno && PositionGetString(POSITION_SYMBOL) == Symbol())
  577. {
  578. //trade.PositionClose(PositionGetInteger(POSITION_TICKET))
  579. if(!trade.PositionClose(PositionGetInteger(POSITION_TICKET)))
  580. {Print("Problem in closing order order ",PositionGetInteger(POSITION_TICKET)); }
  581. else
  582. {
  583. Print("Order Closed by closeTrades() new filter",PositionGetInteger(POSITION_TICKET));
  584. }
  585. }
  586. }
  587. }
  588. }
  589. }
  590. //+------------------------------------------------------------------+
  591. //| |
  592. //+------------------------------------------------------------------+
  593. int orderCount_1(int type,int magic)
  594. {
  595. int count1=0;
  596. for(int i= PositionsTotal()-1; i>=0; i--)
  597. {
  598. // Print(" Selection: ",OrderSelect(i,SELECT_BY_POS)," i: ",i," OrdersTotal(): ", OrdersTotal());
  599. ulong ticket = PositionGetTicket(i);
  600. if(PositionSelectByTicket(ticket))
  601. {
  602. // if(PositionGetInteger(POSITION_TYPE) == POSITION_TYPE_BUY || PositionGetInteger(POSITION_TYPE) == POSITION_TYPE_SELL)
  603. if(PositionGetInteger(POSITION_MAGIC) == magic && PositionGetString(POSITION_SYMBOL) == Symbol())
  604. {
  605. //trade.PositionClose(PositionGetInteger(POSITION_TICKET))
  606. if(PositionGetInteger(POSITION_TYPE) == type)
  607. {
  608. count1++;
  609. }
  610. }
  611. }
  612. }
  613. return count1;
  614. }
  615. //+------------------------------------------------------------------+
  616. //| |
  617. //+------------------------------------------------------------------+
  618. int orderCount(int type)
  619. {
  620. int count = 0;
  621. for(int i= PositionsTotal()-1; i>=0; i--)
  622. {
  623. ulong ticket = PositionGetTicket(i);
  624. if(PositionSelectByTicket(ticket))
  625. {
  626. if(PositionGetInteger(POSITION_MAGIC) == magic_no && PositionGetString(POSITION_SYMBOL) == Symbol())
  627. {
  628. if(PositionGetInteger(POSITION_TYPE) == type)
  629. {
  630. count++;
  631. }
  632. }
  633. }
  634. }
  635. return count;
  636. }
  637. //+------------------------------------------------------------------+
  638. //| |
  639. //+------------------------------------------------------------------+
  640. bool level_present(double priceIs)
  641. {
  642. for(int i = 0 ; i < MaxOrders ; i++)
  643. {
  644. if(newTradeStore[i].price > 0)
  645. {
  646. if(priceIs == newTradeStore[i].price)
  647. {
  648. return true;
  649. }
  650. }
  651. }
  652. return false;
  653. }
  654. //+------------------------------------------------------------------+
  655. //| |
  656. //+------------------------------------------------------------------+
  657. void struct_level_check()
  658. {
  659. for(int i = 0; i < MaxOrders; i++)
  660. {
  661. if(newTradeStore[i].price > 0)
  662. {
  663. bool found = false;
  664. for(int j = 0; j < ArraySize(levelsAre); j++)
  665. {
  666. if(newTradeStore[i].price == levelsAre[j])
  667. {
  668. found = true;
  669. break;
  670. }
  671. }
  672. if(!found)
  673. {
  674. Print("Price not found in levelsAre[] -> index:", i, " | price:", newTradeStore[i].price);
  675. newTradeStore[i].buy_ticket = (ulong)-1;
  676. newTradeStore[i].sell_ticket = (ulong)-1;
  677. bool buy_virtual_tp_hit = true;
  678. bool sell_virtual_tp_hit = true;
  679. if(bothHitsSl)
  680. {
  681. buy_virtual_tp_hit = false;
  682. sell_virtual_tp_hit = false;
  683. }
  684. newTradeStore[i].buy_hit_virtual_sl = buy_virtual_tp_hit;
  685. newTradeStore[i].sell_hit_virtual_sl = sell_virtual_tp_hit;
  686. newTradeStore[i].symbol = "";
  687. newTradeStore[i].price = 0.0;
  688. newTradeStore[i].stop_loss_buy = 0.0;
  689. newTradeStore[i].take_profit_buy = 0.0;
  690. newTradeStore[i].stop_loss_sell = 0.0;
  691. newTradeStore[i].take_profit_sell = 0.0;
  692. newTradeStore[i].start_time = 0;
  693. newTradeStore[i].end_time = 0;
  694. return;
  695. }
  696. }
  697. }
  698. return;
  699. }
  700. //+------------------------------------------------------------------+
  701. //| |
  702. //+------------------------------------------------------------------+
  703. void addToNewTradeStore(ulong r_buy_ticket, ulong r_sell_ticket,
  704. string r_symbol, double r_price,
  705. double r_stop_loss_buy, double r_take_profit_buy,
  706. double r_stop_loss_sell, double r_take_profit_sell,
  707. datetime r_start_time, datetime r_end_time, bool r_buy_hit_sl, bool r_sell_hit_sl)
  708. {
  709. Print(" Tier 1. ");
  710. for(int i = 0; i < MaxOrders; i++)
  711. {
  712. // treat slot as empty when both tickets are -1 (same convention as constructor)
  713. if(newTradeStore[i].buy_ticket == -1 && newTradeStore[i].sell_ticket == -1)
  714. {
  715. if(newTradeStore[i].price == 0)
  716. {
  717. newTradeStore[i].buy_ticket = r_buy_ticket;
  718. newTradeStore[i].sell_ticket = r_sell_ticket;
  719. newTradeStore[i].symbol = r_symbol;
  720. newTradeStore[i].price = r_price;
  721. newTradeStore[i].stop_loss_buy = r_stop_loss_buy;
  722. newTradeStore[i].take_profit_buy = r_take_profit_buy;
  723. newTradeStore[i].stop_loss_sell = r_stop_loss_sell;
  724. newTradeStore[i].take_profit_sell = r_take_profit_sell;
  725. newTradeStore[i].start_time = r_start_time;
  726. newTradeStore[i].end_time = r_end_time;
  727. newTradeStore[i].buy_hit_virtual_sl = r_buy_hit_sl;
  728. newTradeStore[i].sell_hit_virtual_sl = r_sell_hit_sl;
  729. Print("Stored -> idx: ", i,
  730. " | Symbol: ", newTradeStore[i].symbol,
  731. " | price: ", DoubleToString(newTradeStore[i].price, Digits()),
  732. " | Sl Buy: ", DoubleToString(newTradeStore[i].stop_loss_buy, Digits()),
  733. " | Tp Buy: ", DoubleToString(newTradeStore[i].take_profit_buy, Digits()),
  734. "\n | Sl Sell: ", DoubleToString(newTradeStore[i].stop_loss_sell, Digits()),
  735. " | Tp Sell: ", DoubleToString(newTradeStore[i].take_profit_sell, Digits()),
  736. " | start: ", TimeToString(newTradeStore[i].start_time, TIME_DATE|TIME_SECONDS),
  737. " | end: ", TimeToString(newTradeStore[i].end_time, TIME_DATE|TIME_SECONDS),
  738. " | Buy Virtal Sl Hit: ", newTradeStore[i].buy_hit_virtual_sl,
  739. " | Sell Virtual Sl Hit: ", newTradeStore[i].sell_hit_virtual_sl);
  740. break;
  741. }
  742. }
  743. }
  744. }
  745. //+------------------------------------------------------------------+
  746. //| |
  747. //+------------------------------------------------------------------+
  748. void tradePlacingCheck()
  749. {
  750. for(int i = 0; i < MaxOrders; i++)
  751. {
  752. if(newTradeStore[i].buy_ticket == -1 && newTradeStore[i].sell_ticket == -1)
  753. {
  754. if(newTradeStore[i].price > 0)
  755. {
  756. if((TimeCurrent() > newTradeStore[i].start_time && TimeCurrent() < newTradeStore[i].end_time) || (newTradeStore[i].start_time == 0 || newTradeStore[i].end_time == 0))
  757. {
  758. if(newTradeStore[i].buy_hit_virtual_sl == true && newTradeStore[i].sell_hit_virtual_sl == true)
  759. {
  760. double levelPriceIs = newTradeStore[i].price;
  761. if((tickPreviousBid > levelPriceIs && tickCurrentBid < levelPriceIs) ||
  762. (tickPreviousBid < levelPriceIs && tickCurrentBid > levelPriceIs))
  763. {
  764. if(isTradingAllowedByWeek())
  765. {
  766. if((enableSpreadFilter && spreadFilter()) || !enableSpreadFilter)
  767. {
  768. ulong buyTicket = -1, sellTicket = -1;
  769. if(countLiveTrades() < maxTrades)
  770. {
  771. buyTicket = placeBuyTrade(newTradeStore[i].stop_loss_buy, newTradeStore[i].take_profit_buy);
  772. sellTicket = placeSellTrade(newTradeStore[i].stop_loss_sell, newTradeStore[i].take_profit_sell);
  773. newTradeStore[i].buy_ticket = buyTicket;
  774. newTradeStore[i].sell_ticket = sellTicket;
  775. }
  776. }
  777. }
  778. }
  779. }
  780. }
  781. }
  782. }
  783. }
  784. }
  785. //+------------------------------------------------------------------+
  786. //| |
  787. //+------------------------------------------------------------------+
  788. void draw_lines(string name, datetime dateTime, double price, color selectColor, long lineStyle)
  789. {
  790. if(!ObjectCreate(0, name, OBJ_HLINE, 0, dateTime, price))
  791. {
  792. Print(" Error in creating ", name," : ","line: "," ",GetLastError());
  793. }
  794. else
  795. {
  796. ObjectSetInteger(0, name, OBJPROP_COLOR, selectColor);
  797. ObjectSetInteger(0, name, OBJPROP_STYLE, lineStyle);
  798. }
  799. }
  800. //+------------------------------------------------------------------+
  801. //| |
  802. //+------------------------------------------------------------------+
  803. void drawLevels()
  804. {
  805. for(int i = 0; i < MaxOrders; i++)
  806. {
  807. if(newTradeStore[i].price > 0)
  808. {
  809. draw_lines("level" + (string)newTradeStore[i].price, TimeCurrent(), newTradeStore[i].price, clrAqua, STYLE_SOLID);
  810. }
  811. }
  812. }
  813. //+------------------------------------------------------------------+
  814. //| |
  815. //+------------------------------------------------------------------+
  816. ulong placeBuyTrade(double stoploss, double takeprofit)
  817. {
  818. double buySL = 0, buyTp=0;
  819. //openPrice = SymbolInfoDouble(Symbol(),SYMBOL_ASK);
  820. double Ask = SymbolInfoDouble(Symbol(),SYMBOL_ASK);
  821. double Bid = SymbolInfoDouble(Symbol(),SYMBOL_BID);
  822. if(useTpSlPips)
  823. {
  824. if(stopLoss != 0)
  825. {
  826. buySL = Ask - (stopLoss * Point());
  827. }
  828. if(takeProfit != 0)
  829. {
  830. buyTp = Ask + (takeProfit * Point());
  831. }
  832. }
  833. else
  834. {
  835. if(stoploss > 0)
  836. {
  837. buySL = stoploss;
  838. }
  839. if(takeprofit > 0)
  840. {
  841. buyTp = takeprofit;
  842. }
  843. }
  844. double distance = MathAbs((Ask - buySL) / Point());
  845. if(trade.PositionOpen(Symbol(),ORDER_TYPE_BUY,getLot(distance),Ask,buySL,buyTp,tradeComment+" Buy"))
  846. {
  847. Print("Buy Trade Placed: ",trade.ResultOrder());
  848. return trade.ResultOrder();
  849. }
  850. else
  851. {
  852. Print("Error in placing Buy: "+Symbol()+" ",GetLastError());
  853. return -1;
  854. }
  855. return -1;
  856. }
  857. //+------------------------------------------------------------------+
  858. //| |
  859. //+------------------------------------------------------------------+
  860. ulong placeSellTrade(double stoploss, double takeprofit)
  861. {
  862. double sellSL = 0, sellTp = 0;
  863. double Ask = SymbolInfoDouble(Symbol(),SYMBOL_ASK);
  864. double Bid = SymbolInfoDouble(Symbol(),SYMBOL_BID);
  865. if(useTpSlPips)
  866. {
  867. if(stopLoss != 0)
  868. {
  869. sellSL = Bid + (stopLoss * Point());
  870. }
  871. if(takeProfit != 0)
  872. {
  873. sellTp = Bid - (takeProfit * Point());
  874. }
  875. }
  876. else
  877. {
  878. if(stoploss > 0)
  879. {
  880. sellSL = stoploss;
  881. }
  882. if(takeprofit > 0)
  883. {
  884. sellTp = takeprofit;
  885. }
  886. }
  887. double distance = MathAbs((Bid - sellSL) / Point());
  888. if(trade.PositionOpen(Symbol(),ORDER_TYPE_SELL,getLot(distance),Bid,sellSL,sellTp,tradeComment+ " Sell"))
  889. {
  890. Print("Sell Trade PLaced: ",trade.ResultOrder());
  891. return trade.ResultOrder();
  892. }
  893. else
  894. {
  895. Print("Error in placing Sell: "+Symbol()+" ",GetLastError());
  896. return -1;
  897. }
  898. return -1;
  899. }
  900. //+------------------------------------------------------------------+
  901. //| |
  902. //+------------------------------------------------------------------+
  903. double getLot(double stop_loss)
  904. {
  905. Print("Tick Value: ",SymbolInfoDouble(Symbol(),SYMBOL_TRADE_TICK_VALUE));
  906. Print("Tick Size: ",SymbolInfoDouble(Symbol(),SYMBOL_TRADE_TICK_SIZE));
  907. double modeTickV=SymbolInfoDouble(Symbol(),SYMBOL_TRADE_TICK_VALUE)
  908. ,modeTickS=SymbolInfoDouble(Symbol(),SYMBOL_TRADE_TICK_SIZE);
  909. // Print("Pip value: ", NormalizeDouble(((SymbolInfoDouble(Symbol(),SYMBOL_TRADE_TICK_VALUE)/(SymbolInfoDouble(Symbol(),SYMBOL_TRADE_TICK_SIZE)/Point))*10),2));
  910. double pipvalue = NormalizeDouble(((SymbolInfoDouble(Symbol(),SYMBOL_TRADE_TICK_VALUE)/(SymbolInfoDouble(Symbol(),SYMBOL_TRADE_TICK_SIZE)/Point()))*10),2);
  911. // pipvalue=NormalizeDouble((modeTickV/modeTickS/Point()),)
  912. // pipvalue=
  913. pipvalue = pipvalue / 10;
  914. double lotSize = lot_amount;
  915. if(lot_calculator == rsk || lot_calculator == dollar) //calculating risk
  916. {
  917. double riskamount = 0;
  918. if(lot_calculator == rsk)
  919. {
  920. riskamount = (risk/100)*AccountInfoDouble(ACCOUNT_BALANCE);
  921. }
  922. if(lot_calculator == dollar)
  923. {
  924. riskamount = dollars;
  925. }
  926. double pipvalue_required=riskamount/stop_loss;
  927. lotSize = pipvalue_required/pipvalue;
  928. //sl=riskamount/pipValuelot
  929. int roundDigit=0;
  930. double step=SymbolInfoDouble(Symbol(),SYMBOL_VOLUME_STEP);
  931. while(step<1)
  932. {
  933. roundDigit++;
  934. step=step*10;
  935. }
  936. Print("Round Digits:",roundDigit);
  937. lotSize = NormalizeDouble(lotSize,roundDigit);
  938. //
  939. }
  940. Print("Lot Size: ",lotSize);
  941. if(lotSize > SymbolInfoDouble(Symbol(),SYMBOL_VOLUME_MAX))
  942. {
  943. lotSize=SymbolInfoDouble(Symbol(),SYMBOL_VOLUME_MAX);
  944. }
  945. else
  946. if(lotSize<SymbolInfoDouble(Symbol(),SYMBOL_VOLUME_MIN))
  947. {
  948. lotSize=SymbolInfoDouble(Symbol(),SYMBOL_VOLUME_MIN);
  949. }
  950. //---
  951. return lotSize;
  952. }
  953. //+------------------------------------------------------------------+
  954. //| |
  955. //+------------------------------------------------------------------+
  956. void timeFilter(bool onInit)
  957. {
  958. MqlDateTime sdate,edate;
  959. datetime start_Time = 0, end_Time = 0;
  960. if(newYorkSessionDay == prev)
  961. {
  962. if(onInit)
  963. {
  964. start_Time = iTime(Symbol(),PERIOD_D1,1);
  965. end_Time = iTime(Symbol(),PERIOD_D1,0);
  966. }
  967. else
  968. {
  969. start_Time = newYorkStartTrading;
  970. end_Time = newYorkEndTrading;
  971. if(TimeCurrent() >= newYorkEndTrading && newYorkEndTrading != 0)
  972. {
  973. start_Time = iTime(Symbol(),PERIOD_D1,0);
  974. end_Time = start_Time + 86400;
  975. }
  976. }
  977. }
  978. else
  979. {
  980. start_Time = iTime(Symbol(),PERIOD_D1,0);
  981. end_Time = iTime(Symbol(),PERIOD_D1,0);
  982. }
  983. if(TimeToStruct(end_Time,edate))
  984. {
  985. edate.hour = newYorkEndHour;
  986. edate.min = newYorkEndMin;
  987. edate.sec = 0;
  988. }
  989. else
  990. Print("Error in Converting Time: ",GetLastError());
  991. newYorkEndTrading = StructToTime(edate);
  992. if(TimeToStruct(start_Time,sdate))
  993. {
  994. sdate.hour = newYorkStartTime;
  995. sdate.min = newYorkStartMin;
  996. sdate.sec = 0;
  997. }
  998. else
  999. Print("Error in Converting Time: ",GetLastError());
  1000. newYorkStartTrading = StructToTime(sdate);
  1001. // if(onInit)
  1002. //Print("NewYork Start Time ",newYorkStartTrading,"End Date: ",newYorkEndTrading);
  1003. //Print("Edate: ",edate.hour," ",edate.min," Sdate: ",sdate.hour," ",sdate.min);
  1004. }
  1005. //+------------------------------------------------------------------+
  1006. //| |
  1007. //+------------------------------------------------------------------+
  1008. void removeFromStructure()
  1009. {
  1010. for(int i = 0 ; i < MaxOrders ; i++)
  1011. {
  1012. bool isBuyPresent=false, isSellPresent=false;
  1013. if(newTradeStore[i].buy_ticket != -1 && newTradeStore[i].sell_ticket != -1)
  1014. {
  1015. for(int j = PositionsTotal()-1; j>=0; j--)
  1016. {
  1017. ulong ticket = PositionGetTicket(j);
  1018. if(PositionSelectByTicket(ticket))
  1019. {
  1020. if(ticket == newTradeStore[i].buy_ticket)
  1021. {
  1022. isBuyPresent=true;
  1023. }
  1024. }
  1025. }
  1026. for(int j = PositionsTotal()-1; j>=0; j--)
  1027. {
  1028. ulong ticket = PositionGetTicket(j);
  1029. if(PositionSelectByTicket(ticket))
  1030. {
  1031. if(ticket == newTradeStore[i].sell_ticket)
  1032. {
  1033. isSellPresent = true;
  1034. }
  1035. }
  1036. }
  1037. if(!isBuyPresent && !isSellPresent)
  1038. {
  1039. Print("Buy/Sell Ticket is closed so removed from struct. Buy Ticket: ", newTradeStore[i].buy_ticket, " Sell Ticket: ", newTradeStore[i].sell_ticket);
  1040. newTradeStore[i].buy_ticket = (ulong)-1;
  1041. newTradeStore[i].sell_ticket = (ulong)-1;
  1042. bool buy_virtual_tp_hit = true;
  1043. bool sell_virtual_tp_hit = true;
  1044. if(bothHitsSl)
  1045. {
  1046. buy_virtual_tp_hit = false;
  1047. sell_virtual_tp_hit = false;
  1048. }
  1049. newTradeStore[i].buy_hit_virtual_sl = buy_virtual_tp_hit;
  1050. newTradeStore[i].sell_hit_virtual_sl = sell_virtual_tp_hit;
  1051. //newTradeStore[i].symbol = "";
  1052. //newTradeStore[i].price = 0.0;
  1053. //newTradeStore[i].stop_loss = 0.0;
  1054. //newTradeStore[i].take_profit = 0.0;
  1055. //newTradeStore[i].start_time = 0;
  1056. //newTradeStore[i].end_time = 0;
  1057. }
  1058. }
  1059. }
  1060. }
  1061. //+------------------------------------------------------------------+
  1062. //| |
  1063. //+------------------------------------------------------------------+
  1064. void virtualSLHitCheck()
  1065. {
  1066. for(int i = 0 ; i < MaxOrders ; i++)
  1067. {
  1068. if(newTradeStore[i].buy_ticket == -1 && newTradeStore[i].sell_ticket == -1)
  1069. {
  1070. if(TimeCurrent() > newTradeStore[i].start_time && TimeCurrent() < newTradeStore[i].end_time)
  1071. {
  1072. double buy_sl = 0, sell_sl = 0;
  1073. if(!useTpSlPips)
  1074. {
  1075. buy_sl = newTradeStore[i].stop_loss_buy;
  1076. sell_sl = newTradeStore[i].stop_loss_sell;
  1077. }
  1078. else
  1079. {
  1080. buy_sl = stopLoss != 0 ? newTradeStore[i].price - (stopLoss * Point()) : 0;
  1081. sell_sl = stopLoss != 0 ? newTradeStore[i].price + (stopLoss * Point()) : 0;
  1082. }
  1083. if(newTradeStore[i].buy_hit_virtual_sl == false)
  1084. {
  1085. if((tickPreviousBid < buy_sl && tickCurrentBid > buy_sl))
  1086. {
  1087. newTradeStore[i].buy_hit_virtual_sl = true;
  1088. 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());
  1089. }
  1090. }
  1091. if(newTradeStore[i].sell_hit_virtual_sl == false)
  1092. {
  1093. if((tickPreviousAsk > sell_sl && tickCurrentAsk < sell_sl))
  1094. {
  1095. newTradeStore[i].sell_hit_virtual_sl = true;
  1096. 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());
  1097. }
  1098. }
  1099. }
  1100. }
  1101. }
  1102. }
  1103. //+------------------------------------------------------------------+
  1104. //| |
  1105. //+------------------------------------------------------------------+
  1106. int countLiveTrades()
  1107. {
  1108. int count = 0;
  1109. for(int i = 0; i < PositionsTotal(); i++)
  1110. {
  1111. ulong ticket = PositionGetTicket(i);
  1112. if(PositionSelectByTicket(ticket))
  1113. {
  1114. if(PositionGetInteger(POSITION_MAGIC) == magic_no)
  1115. {
  1116. if(PositionGetString(POSITION_SYMBOL) == Symbol())
  1117. {
  1118. if(PositionGetInteger(POSITION_TYPE) == POSITION_TYPE_BUY || PositionGetInteger(POSITION_TYPE) == POSITION_TYPE_SELL)
  1119. {
  1120. count++;
  1121. }
  1122. }
  1123. }
  1124. }
  1125. }
  1126. return count;
  1127. }
  1128. //+------------------------------------------------------------------+
  1129. //| |
  1130. //+------------------------------------------------------------------+
  1131. bool spreadFilter()
  1132. {
  1133. long spreadIs = SymbolInfoInteger(Symbol(), SYMBOL_SPREAD);
  1134. if(spreadIs > maximumSpread)
  1135. {
  1136. return false;
  1137. }
  1138. return true;
  1139. }
  1140. //+------------------------------------------------------------------+
  1141. //| |
  1142. //+------------------------------------------------------------------+
  1143. void breakEven()
  1144. {
  1145. for(int i = PositionsTotal()-1; i>=0; i--)
  1146. {
  1147. ulong ticket = PositionGetTicket(i);
  1148. string symbol=PositionGetSymbol(i);
  1149. double mySL = 0,newSL = 0;
  1150. double SymbolTickSize = SymbolInfoDouble(symbol, SYMBOL_TRADE_TICK_SIZE);
  1151. ////Print("ticket ",ticket," Symbol : ",symbol);
  1152. if(PositionSelectByTicket(ticket))
  1153. {
  1154. if(PositionGetString(POSITION_SYMBOL)==Symbol() && PositionGetInteger(POSITION_MAGIC) == magic_no)
  1155. {
  1156. if(isCounterpartOpen(ticket))
  1157. {
  1158. // counterpart still open -> skip trailing for this position
  1159. continue;
  1160. }
  1161. //========================================================Buy Condition=========================================================================
  1162. if(PositionGetInteger(POSITION_TYPE) == POSITION_TYPE_BUY)
  1163. {
  1164. mySL = PositionGetDouble(POSITION_PRICE_OPEN) + (breakEvenPoints * SymbolTickSize);
  1165. if(SymbolInfoDouble(Symbol(),SYMBOL_BID) >= mySL && PositionGetDouble(POSITION_PRICE_OPEN) > PositionGetDouble(POSITION_SL))
  1166. {
  1167. newSL= PositionGetDouble(POSITION_PRICE_OPEN) + (breakStopPoint * SymbolTickSize);
  1168. if(trade.PositionModify(ticket,newSL,PositionGetDouble(POSITION_TP)))
  1169. {
  1170. Print("Buy Order BreakEven Successfully ");
  1171. }
  1172. else
  1173. {
  1174. Print("Error in BreakEven Buy Position ",GetLastError());
  1175. }
  1176. }
  1177. }
  1178. //=======================================================Sell condition ===============================================================
  1179. if(PositionGetInteger(POSITION_TYPE) == POSITION_TYPE_SELL)
  1180. {
  1181. mySL = PositionGetDouble(POSITION_PRICE_OPEN) - (breakEvenPoints * SymbolTickSize);
  1182. if(SymbolInfoDouble(Symbol(),SYMBOL_ASK) <= mySL && PositionGetDouble(POSITION_SL) > PositionGetDouble(POSITION_PRICE_OPEN))
  1183. {
  1184. newSL = PositionGetDouble(POSITION_PRICE_OPEN) - (breakStopPoint * SymbolTickSize);
  1185. if(trade.PositionModify(ticket,newSL,PositionGetDouble(POSITION_TP)))
  1186. {
  1187. Print("Order Sell BreakEven Successfully ");
  1188. }
  1189. else
  1190. {
  1191. Print("Error in BreakEven Sell Position ",GetLastError());
  1192. }
  1193. }
  1194. }
  1195. }
  1196. }
  1197. }
  1198. }
  1199. //+------------------------------------------------------------------+
  1200. //| |
  1201. //+------------------------------------------------------------------+
  1202. bool isCounterpartOpen(ulong ticket)
  1203. {
  1204. // scan stored pairs
  1205. for(int k=0; k<MaxOrders; k++)
  1206. {
  1207. // check if this ticket is the buy side in the pair
  1208. if(newTradeStore[k].buy_ticket == ticket)
  1209. {
  1210. ulong other = newTradeStore[k].sell_ticket;
  1211. if(other <= 0)
  1212. return false; // no counterpart recorded -> treat as closed
  1213. // check if counterpart ticket exists in current positions
  1214. for(int p = PositionsTotal()-1; p >= 0; p--)
  1215. {
  1216. ulong t = PositionGetTicket(p);
  1217. if(t == other)
  1218. return true; // counterpart still open
  1219. }
  1220. return false; // counterpart not found -> closed
  1221. }
  1222. // check if this ticket is the sell side in the pair
  1223. if(newTradeStore[k].sell_ticket == ticket)
  1224. {
  1225. ulong other = newTradeStore[k].buy_ticket;
  1226. if(other <= 0)
  1227. return false; // no counterpart recorded -> treat as closed
  1228. for(int p = PositionsTotal()-1; p >= 0; p--)
  1229. {
  1230. ulong t = PositionGetTicket(p);
  1231. if(t == other)
  1232. return true; // counterpart still open
  1233. }
  1234. return false; // counterpart not found -> closed
  1235. }
  1236. }
  1237. // ticket not found in the stored pairs -> treat as no counterpart open
  1238. return false;
  1239. }
  1240. //+------------------------------------------------------------------+
  1241. //| |
  1242. //+------------------------------------------------------------------+
  1243. void Individual_Trailing()
  1244. {
  1245. int openedpositions;
  1246. double mySL,myResult;
  1247. openedpositions=PositionsTotal();
  1248. if((openedpositions>0))
  1249. {
  1250. int totalorders=PositionsTotal();
  1251. for(int i=0; i<totalorders; i++) // scan all orders and positions. ..
  1252. {
  1253. ulong ticket = PositionGetTicket(i);
  1254. if(PositionSelectByTicket(ticket))
  1255. {
  1256. if(PositionGetString(POSITION_SYMBOL)==Symbol() && PositionGetInteger(POSITION_MAGIC) == magic_no) // only look if mygrid and symbol. ..
  1257. {
  1258. if(isCounterpartOpen(ticket))
  1259. {
  1260. // counterpart still open -> skip trailing for this position
  1261. continue;
  1262. }
  1263. double SymbolAsk = SymbolInfoDouble(PositionGetString(POSITION_SYMBOL), SYMBOL_ASK);
  1264. double SymbolBid = SymbolInfoDouble(PositionGetString(POSITION_SYMBOL), SYMBOL_BID);
  1265. int SymbolDigits = (int)SymbolInfoInteger(PositionGetString(POSITION_SYMBOL), SYMBOL_DIGITS);
  1266. double SymbolTickSize = SymbolInfoDouble(PositionGetString(POSITION_SYMBOL), SYMBOL_TRADE_TICK_SIZE);
  1267. int type= (int)PositionGetInteger(POSITION_TYPE);
  1268. if(type==POSITION_TYPE_BUY) // its a long position
  1269. {
  1270. mySL=NormalizeDouble(SymbolAsk-(ts*SymbolTickSize),Digits()); // new SL
  1271. double startSl=PositionGetDouble(POSITION_PRICE_OPEN)+(ts_sl*SymbolTickSize);
  1272. if(PositionGetDouble(POSITION_SL) != mySL)
  1273. if(mySL>PositionGetDouble(POSITION_SL) && SymbolAsk>=startSl)
  1274. {
  1275. myResult=trade.PositionModify(ticket,mySL,PositionGetDouble(POSITION_TP)); //OrderModify(OrderTicket(),OrderOpenPrice(),mySL,OrderTakeProfit(),0,clrGreen);
  1276. if(!myResult)
  1277. {
  1278. Print(" Buy Trade Trailing Error: ",GetLastError());
  1279. }
  1280. }
  1281. }
  1282. if(type==POSITION_TYPE_SELL)
  1283. {
  1284. mySL=NormalizeDouble(SymbolBid+(ts*SymbolTickSize),Digits()); // new SL
  1285. double startSlSell=PositionGetDouble(POSITION_PRICE_OPEN)-(ts_sl*SymbolTickSize);
  1286. if(PositionGetDouble(POSITION_SL) != mySL)
  1287. if(((mySL<PositionGetDouble(POSITION_SL)) || (PositionGetDouble(POSITION_SL)<SymbolTickSize)) && SymbolBid<=startSlSell)
  1288. {
  1289. myResult=trade.PositionModify(ticket,mySL,PositionGetDouble(POSITION_TP)); //OrderModify(OrderTicket(),OrderOpenPrice(),mySL,OrderTakeProfit(),0,clrRed);
  1290. if(!myResult)
  1291. {
  1292. Print(" Sell Trade Trailing Error: ",GetLastError());
  1293. }
  1294. }
  1295. }
  1296. }
  1297. }
  1298. }
  1299. }
  1300. }
  1301. //+------------------------------------------------------------------+
  1302. //| |
  1303. //+------------------------------------------------------------------+
  1304. void saveNewTradeStoreFile()
  1305. {
  1306. // don't run in strategy tester
  1307. if(MQLInfoInteger(MQL_TESTER))
  1308. return;
  1309. string file_name = "new_trade_store.csv";
  1310. int fileHandle = FileOpen(file_name,
  1311. FILE_WRITE | FILE_CSV | FILE_COMMON |
  1312. FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_READ);
  1313. if(fileHandle == INVALID_HANDLE)
  1314. {
  1315. PrintFormat("saveNewTradeStoreFile() -> Cannot open file '%s'. Error: %d", file_name, GetLastError());
  1316. return;
  1317. }
  1318. // header (optional) - comment out if you don't want header
  1319. //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";
  1320. //FileWriteString(fileHandle, header);
  1321. for(int i = 0; i < MaxOrders; i++)
  1322. {
  1323. // decide whether this slot has useful data:
  1324. // you can tweak this condition as you prefer (symbol != "" is simple)
  1325. bool slotPopulated = (StringLen(newTradeStore[i].symbol) > 0)
  1326. || (newTradeStore[i].price != 0.0)
  1327. || (newTradeStore[i].start_time != 0);
  1328. if(!slotPopulated)
  1329. continue;
  1330. // convert values to strings
  1331. string buyTicketStr = IntegerToString((long)newTradeStore[i].buy_ticket);
  1332. string sellTicketStr = IntegerToString((long)newTradeStore[i].sell_ticket);
  1333. string priceStr = DoubleToString(newTradeStore[i].price, Digits());
  1334. string slBuyStr = DoubleToString(newTradeStore[i].stop_loss_buy, Digits());
  1335. string tpBuyStr = DoubleToString(newTradeStore[i].take_profit_buy, Digits());
  1336. string slSellStr = DoubleToString(newTradeStore[i].stop_loss_sell, Digits());
  1337. string tpSellStr = DoubleToString(newTradeStore[i].take_profit_sell, Digits());
  1338. string startTimeStr = (newTradeStore[i].start_time != 0) ? TimeToString(newTradeStore[i].start_time, TIME_DATE|TIME_SECONDS) : "";
  1339. string endTimeStr = (newTradeStore[i].end_time != 0) ? TimeToString(newTradeStore[i].end_time, TIME_DATE|TIME_SECONDS) : "";
  1340. string buyHitStr = ""; // IntegerToString(newTradeStore[i].buy_hit_virtual_sl ? 1 : 0);
  1341. string sellHitStr = ""; // IntegerToString(newTradeStore[i].sell_hit_virtual_sl ? 1 : 0);
  1342. if(newTradeStore[i].buy_hit_virtual_sl == true)
  1343. {
  1344. buyHitStr = "true";
  1345. }
  1346. else
  1347. {
  1348. buyHitStr = "false";
  1349. }
  1350. if(newTradeStore[i].sell_hit_virtual_sl == true)
  1351. {
  1352. sellHitStr = "true";
  1353. }
  1354. else
  1355. {
  1356. sellHitStr = "false";
  1357. }
  1358. // build CSV line and write
  1359. string line = buyTicketStr + "," + sellTicketStr + "," +
  1360. newTradeStore[i].symbol + "," +
  1361. priceStr + "," + slBuyStr + "," + tpBuyStr + "," +
  1362. slSellStr + "," + tpSellStr + "," +
  1363. startTimeStr + "," + endTimeStr + "," +
  1364. buyHitStr + "," + sellHitStr + "\r\n";
  1365. FileWriteString(fileHandle, line);
  1366. }
  1367. FileClose(fileHandle);
  1368. PrintFormat("saveNewTradeStoreFile() -> saved to '%s'.", file_name);
  1369. }
  1370. //+------------------------------------------------------------------+
  1371. //| |
  1372. //+------------------------------------------------------------------+
  1373. void loadNewTradeStoreFile()
  1374. {
  1375. if(MQLInfoInteger(MQL_TESTER))
  1376. return;
  1377. string file_name = "new_trade_store.csv";
  1378. int fileHandle = FileOpen(file_name,
  1379. FILE_READ | FILE_CSV | FILE_COMMON |
  1380. FILE_SHARE_READ | FILE_SHARE_WRITE);
  1381. if(fileHandle == INVALID_HANDLE)
  1382. {
  1383. Print("loadNewTradeStoreFile() -> Cannot open file '", file_name, "'. Error: ", GetLastError());
  1384. return;
  1385. }
  1386. // reset defaults
  1387. for(int j = 0; j < MaxOrders; j++)
  1388. {
  1389. newTradeStore[j].buy_ticket = (ulong)-1;
  1390. newTradeStore[j].sell_ticket = (ulong)-1;
  1391. newTradeStore[j].symbol = "";
  1392. newTradeStore[j].price = 0.0;
  1393. newTradeStore[j].stop_loss_buy = 0.0;
  1394. newTradeStore[j].take_profit_buy = 0.0;
  1395. newTradeStore[j].stop_loss_sell = 0.0;
  1396. newTradeStore[j].take_profit_sell = 0.0;
  1397. newTradeStore[j].start_time = 0;
  1398. newTradeStore[j].end_time = 0;
  1399. newTradeStore[j].buy_hit_virtual_sl = false;
  1400. newTradeStore[j].sell_hit_virtual_sl = false;
  1401. }
  1402. int idx = 0;
  1403. while(!FileIsEnding(fileHandle) && idx < MaxOrders)
  1404. {
  1405. string line = FileReadString(fileHandle);
  1406. if(StringLen(line) == 0)
  1407. continue;
  1408. string tokens[];
  1409. int total = StringSplit(line, ',', tokens);
  1410. if(total >= 12)
  1411. {
  1412. newTradeStore[idx].buy_ticket = (ulong)tokens[0];
  1413. newTradeStore[idx].sell_ticket = (ulong)tokens[1];
  1414. newTradeStore[idx].symbol = tokens[2];
  1415. newTradeStore[idx].price = StringToDouble(tokens[3]);
  1416. newTradeStore[idx].stop_loss_buy = StringToDouble(tokens[4]);
  1417. newTradeStore[idx].take_profit_buy = StringToDouble(tokens[5]);
  1418. newTradeStore[idx].stop_loss_sell = StringToDouble(tokens[6]);
  1419. newTradeStore[idx].take_profit_sell = StringToDouble(tokens[7]);
  1420. string sStart = tokens[8];
  1421. string sEnd = tokens[9];
  1422. newTradeStore[idx].start_time = (StringLen(sStart) > 0) ? StringToTime(sStart) : 0;
  1423. newTradeStore[idx].end_time = (StringLen(sEnd) > 0) ? StringToTime(sEnd) : 0;
  1424. bool bHit = false;
  1425. bool sHit = false;
  1426. if(tokens[10] == "true")
  1427. {
  1428. bHit = true;
  1429. }
  1430. else
  1431. {
  1432. bHit = false;
  1433. }
  1434. if(tokens[11] == "true")
  1435. {
  1436. sHit = true;
  1437. }
  1438. else
  1439. {
  1440. sHit = false;
  1441. }
  1442. newTradeStore[idx].buy_hit_virtual_sl = bHit;
  1443. newTradeStore[idx].sell_hit_virtual_sl = sHit;
  1444. // --- simple Print instead of PrintFormat ---
  1445. Print(
  1446. "Loaded newTradeStore[", idx, "]:",
  1447. " buy_ticket=", newTradeStore[idx].buy_ticket,
  1448. " sell_ticket=", newTradeStore[idx].sell_ticket,
  1449. " symbol=", newTradeStore[idx].symbol,
  1450. " price=", DoubleToString(newTradeStore[idx].price, Digits()),
  1451. " \n sl buy=", DoubleToString(newTradeStore[idx].stop_loss_buy, Digits()),
  1452. " tp buy=", DoubleToString(newTradeStore[idx].take_profit_buy, Digits()),
  1453. " sl sell=", DoubleToString(newTradeStore[idx].stop_loss_sell, Digits()),
  1454. " tp sell=", DoubleToString(newTradeStore[idx].take_profit_sell, Digits()),
  1455. " start=", (newTradeStore[idx].start_time != 0 ? TimeToString(newTradeStore[idx].start_time, TIME_DATE|TIME_SECONDS) : ""),
  1456. " end=", (newTradeStore[idx].end_time != 0 ? TimeToString(newTradeStore[idx].end_time, TIME_DATE|TIME_SECONDS) : ""),
  1457. " buyHit=", newTradeStore[idx].buy_hit_virtual_sl,
  1458. " sellHit=", newTradeStore[idx].sell_hit_virtual_sl
  1459. );
  1460. idx++;
  1461. }
  1462. else
  1463. {
  1464. Print("loadNewTradeStoreFile(): skipping malformed line (tokens=", total, "): ", line);
  1465. }
  1466. }
  1467. FileClose(fileHandle);
  1468. Print("loadNewTradeStoreFile() -> loaded ", idx, " entries from '", file_name, "'.");
  1469. }
  1470. //+------------------------------------------------------------------+
  1471. //| |
  1472. //+------------------------------------------------------------------+
  1473. //+------------------------------------------------------------------+