Nessuna descrizione

vol_hedge_strategy_mt5_v2.mq5 120KB

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