暂无描述

vol_hedge_strategy_mt5_v2.mq5 120KB

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