Sin descripción

vol_hedge_strategy_mt5_v2.mq5 122KB

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