Nenhuma descrição

Pulse_EA_project_MT5.mq5 88KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300
  1. //+------------------------------------------------------------------+
  2. //| Pulse_EA_project_MT5.mq5 |
  3. //| Copyright 2024, MQL Development |
  4. //| https://www.mqldevelopment.com/ |
  5. //+------------------------------------------------------------------+
  6. #property copyright "Copyright 2024, MQL Development"
  7. #property link "https://www.mqldevelopment.com/"
  8. #property version "1.00"
  9. #include <Trade\Trade.mqh>
  10. CTrade trade;
  11. #define MaxOrders 10000
  12. struct new_trade_store
  13. {
  14. int trade_ticket;
  15. int trade_type;
  16. int trade_magic_no;
  17. double trade_open_price;
  18. double trade_close_price;
  19. datetime trade_open_time;
  20. datetime trade_close_time;
  21. double trade_sl;
  22. double trade_tp;
  23. double trade_lot;
  24. double trade_profit;
  25. new_trade_store()
  26. {
  27. trade_ticket = -1;
  28. trade_type = -1;
  29. trade_magic_no = -1;
  30. trade_open_price = -1;
  31. trade_close_price = -1;
  32. trade_open_time = -1;
  33. trade_close_time = -1;
  34. trade_sl = -1;
  35. trade_tp = -1;
  36. trade_lot = -1;
  37. trade_profit = -1;
  38. }
  39. };
  40. new_trade_store od[MaxOrders];
  41. enum trade_typ
  42. {
  43. buy, // Buy
  44. reverse, // Reverse
  45. };
  46. enum EA_TYPE
  47. {
  48. Tally_Sim, // Tally Sim
  49. Tally_Trade, // Tally Trade
  50. };
  51. input string gnrlsettings = " ================ General Settings =================== ";//_
  52. input EA_TYPE eaType = Tally_Sim; // EA Option
  53. input double tpPips = 20; // Tp Pips
  54. input double slPips = 20; // SL Pips
  55. input double lot = 0.1; // Lot Size
  56. input string gnrlesettings = " ================ Tally Sim Settings =================== ";//_
  57. trade_typ ordTyp = buy; // Order Type (Tally Sim)
  58. input int magicNo = 12345; // Magic #
  59. input string fileName = "TradeDataFile"; // File Name (Tally Sim)
  60. input string grlesettings = " ================ Tally Trade Settings =================== ";//_
  61. input trade_typ tradesDirection = buy; // Order Type (Tally Trade)
  62. input int magicNo1 = 1; // Copy Trade Magic #
  63. input bool CopyTallyTrade = true; // Enable Copy Trade
  64. input double glTp = 20; // Copy Take Profit
  65. input double glSl = 10; // Copy Stop Loss
  66. input string Settings6 = "------------- Display Settings -------------"; //_
  67. input int tradeLineThickness = 2; // Trade Line Thickness
  68. input int dollarFontSize = 10; // Dollar Text Font Size
  69. input color dollarFontColor = clrAqua; // Dollar Text Font Colour
  70. input string horizontalLineName = "close"; // Horizontal Line Name
  71. input string Settings5 = "------------- Time Filter Settings -------------"; //_
  72. input bool enableTimeFilter = false; // Enable Time Filter
  73. input string startTime = "22:00"; // Start Time
  74. input string endTime = "01:00"; // End Time
  75. input bool useFridayClose = false; // Use Friday Close
  76. input string closeFriday = "23:00"; // Friday Close Time
  77. input bool useMondayOpen = false; // Use Monday Open
  78. input string mondayOpen = "01:00"; // Monday Open Time
  79. input string Settings25 = "------------- Daily Draw Limit Settings -------------"; //_
  80. input bool UseDailyDrawdownLimit = true; // Enable Daily Draw Down
  81. input double DailyDrawdownAmount = 2000; // $2000 limit
  82. input string DrawdownResetTime = "05:00"; // Enable Trading At
  83. input string indSettings = " ================ Indicator Settings =================== ";//_
  84. input color Dot_Color = clrOrangeRed;
  85. input double StartingBalance = 10000;
  86. input string MagicNumbers = "";
  87. input int MA_Period = 5;
  88. input ENUM_MA_METHOD MA_Method = MODE_SMA;
  89. input string fileName1 = "TradeDataFile"; // File Name
  90. input int historyTrades = 50;
  91. bool tpSlHit = false;
  92. int ticketAssigner = 1;
  93. int handler;
  94. double bufferData[];
  95. ushort u_sep; // The code of the separator character
  96. string sep = ":"; // A separator as a character
  97. string result1[];
  98. datetime startTradingTime = 0, endTradingTime = 0, dailyDrawDownTime = 0;
  99. datetime mondayTradingStart = 0, fridayTradingClose = 0;
  100. datetime eaStartTime; // Store EA start time
  101. double g_dailyStartBalance;
  102. bool enableTradingDaily = true;
  103. bool doTrading = true;
  104. int prevOrderCount = 0;
  105. //+------------------------------------------------------------------+
  106. //| |
  107. //+------------------------------------------------------------------+
  108. string filename = fileName + Symbol() + ".csv";
  109. //+------------------------------------------------------------------+
  110. //| Expert initialization function |
  111. //+------------------------------------------------------------------+
  112. int OnInit()
  113. {
  114. //---
  115. if(eaType == Tally_Sim)
  116. {
  117. FileDelete(filename,FILE_WRITE|FILE_CSV|FILE_COMMON|FILE_END);
  118. int filehandle = FileOpen(filename,FILE_WRITE|FILE_CSV|FILE_COMMON|FILE_END,",");
  119. if(filehandle != INVALID_HANDLE)
  120. {
  121. FileClose(filehandle);
  122. }
  123. }
  124. else
  125. {
  126. prevOrderCount = orderCount();
  127. }
  128. string typ = eaType == 0 ? "Tally Sim" :"Tally_Trade";
  129. Comment(" Current Mode: ",typ);
  130. tpSlHit = false;
  131. doTrading = true;
  132. ticketAssigner = 1;
  133. if(eaType == Tally_Trade)
  134. {
  135. ArrayInitialize(bufferData,0.0);
  136. handler = iCustom(Symbol(),PERIOD_CURRENT,"Pulse Balance Indicator Sim",Dot_Color,StartingBalance,MagicNumbers,MA_Period,MA_Method,fileName1,historyTrades);
  137. ArraySetAsSeries(bufferData,true);
  138. }
  139. trade.SetExpertMagicNumber(magicNo1);
  140. trade.SetDeviationInPoints(10);
  141. trade.SetTypeFilling(ORDER_FILLING_IOC);
  142. trade.LogLevel(LOG_LEVEL_ALL);
  143. trade.SetAsyncMode(false);
  144. setStart_EndTime_modify(true,startTime,endTime,startTradingTime,endTradingTime);
  145. setStart_EndTime(true,startTime,endTime,startTradingTime,endTradingTime);
  146. g_dailyStartBalance = AccountInfoDouble(ACCOUNT_BALANCE);
  147. enableTradingDaily = true;
  148. eaStartTime = TimeCurrent(); // Track EA start time
  149. //---
  150. return(INIT_SUCCEEDED);
  151. }
  152. //+------------------------------------------------------------------+
  153. //| Expert deinitialization function |
  154. //+------------------------------------------------------------------+
  155. void OnDeinit(const int reason)
  156. {
  157. //---
  158. Comment("");
  159. }
  160. //+------------------------------------------------------------------+
  161. //| Expert tick function |
  162. //+------------------------------------------------------------------+
  163. void OnTick()
  164. {
  165. //---
  166. doTrading = true;
  167. timeConversion();
  168. if(TimeCurrent() >= dailyDrawDownTime && enableTradingDaily == false)
  169. {
  170. enableTradingDaily = true;
  171. }
  172. if(eaType == Tally_Trade)
  173. {
  174. markClosedOrder(eaStartTime);
  175. CheckVirtualGlobalTpSl();
  176. }
  177. if(eaType == Tally_Sim)
  178. checkTPSLHit();
  179. newBar();
  180. if(newDayBar())
  181. {
  182. g_dailyStartBalance = AccountInfoDouble(ACCOUNT_BALANCE);
  183. }
  184. MqlDateTime dt;
  185. TimeToStruct(TimeCurrent(), dt);
  186. if(useMondayOpen)
  187. {
  188. if(dt.day_of_week == 1 && TimeCurrent() < mondayTradingStart) // it's Monday
  189. {
  190. doTrading = false;
  191. }
  192. }
  193. if(useFridayClose)
  194. {
  195. if(dt.day_of_week == 5 && TimeCurrent() >= fridayTradingClose) // it's Friday
  196. {
  197. doTrading = false;
  198. closeAllActiveOrders();
  199. }
  200. }
  201. setStart_EndTime_modify(false,startTime,endTime,startTradingTime,endTradingTime);
  202. setStart_EndTime(false,startTime,endTime,startTradingTime,endTradingTime);
  203. if(enableTimeFilter && TimeCurrent() >= startTradingTime && TimeCurrent() < endTradingTime)
  204. {
  205. return;
  206. }
  207. placeTrade();
  208. }
  209. //+------------------------------------------------------------------+
  210. //| |
  211. //+------------------------------------------------------------------+
  212. bool newBar()
  213. {
  214. static datetime lastbar;
  215. datetime curbar = iTime(Symbol(), PERIOD_CURRENT, 0);
  216. if(lastbar != curbar)
  217. {
  218. lastbar = curbar;
  219. Print(" ---------------------- New Bar :: ---------------------- ",lastbar);
  220. return (true);
  221. }
  222. else
  223. {
  224. return (false);
  225. }
  226. }
  227. //+------------------------------------------------------------------+
  228. //| |
  229. //+------------------------------------------------------------------+
  230. bool newDayBar()
  231. {
  232. static datetime lastbar1;
  233. datetime curbar1 = iTime(Symbol(), PERIOD_D1, 0);
  234. if(lastbar1 != curbar1)
  235. {
  236. lastbar1 = curbar1;
  237. Print(" ---------------------- New Day Bar :: ---------------------- ",lastbar1);
  238. return (true);
  239. }
  240. else
  241. {
  242. return (false);
  243. }
  244. }
  245. //+------------------------------------------------------------------+
  246. //| |
  247. //+------------------------------------------------------------------+
  248. void closeAllActiveOrders()
  249. {
  250. for(int i=PositionsTotal()-1; i >=0 ; i--)
  251. {
  252. ulong ticket = PositionGetTicket(i);
  253. if(PositionSelectByTicket(ticket))
  254. {
  255. if(PositionGetInteger(POSITION_MAGIC) == magicNo &&
  256. PositionGetString(POSITION_SYMBOL) == Symbol())
  257. {
  258. if(trade.PositionClose(ticket))
  259. {
  260. Print("Closing All Active Orders");
  261. Print("Position closed ", ticket);
  262. }
  263. else
  264. {
  265. Print("Cannot close order: ",GetLastError());
  266. }
  267. }
  268. }
  269. }
  270. }
  271. //+------------------------------------------------------------------+
  272. //| |
  273. //+------------------------------------------------------------------+
  274. void timeConversion()
  275. {
  276. MqlDateTime date1, date_1,date_2;
  277. TimeToStruct(iTime(Symbol(),PERIOD_CURRENT,0),date1);
  278. u_sep=StringGetCharacter(sep,0);
  279. StringSplit(mondayOpen,u_sep,result1);
  280. date1.hour = (int)StringToInteger(result1[0]);
  281. date1.min = (int)StringToInteger(result1[1]);
  282. mondayTradingStart = StructToTime(date1);
  283. TimeToStruct(iTime(Symbol(),PERIOD_CURRENT,0),date_1);
  284. StringSplit(closeFriday,u_sep,result1);
  285. date_1.hour = (int)StringToInteger(result1[0]);
  286. date_1.min = (int)StringToInteger(result1[1]);
  287. fridayTradingClose = StructToTime(date_1);
  288. TimeToStruct(iTime(Symbol(),PERIOD_CURRENT,0),date_2);
  289. StringSplit(DrawdownResetTime,u_sep,result1);
  290. date_2.hour = (int)StringToInteger(result1[0]);
  291. date_2.min = (int)StringToInteger(result1[1]);
  292. dailyDrawDownTime = StructToTime(date_2);
  293. }
  294. //+------------------------------------------------------------------+
  295. //| |
  296. //+------------------------------------------------------------------+
  297. void placeTrade()
  298. {
  299. if(tpSlHit == false)
  300. {
  301. if(ordTyp == buy)
  302. {
  303. placeBuyTrade();
  304. }
  305. if(ordTyp == reverse)
  306. {
  307. placeSellTrade();
  308. }
  309. tpSlHit = true;
  310. }
  311. }
  312. //+------------------------------------------------------------------+
  313. //| |
  314. //+------------------------------------------------------------------+
  315. void placeBuyTrade()
  316. {
  317. double buySl = 0,buyTp=0;
  318. double Ask = SymbolInfoDouble(Symbol(),SYMBOL_ASK);
  319. if(slPips != 0)
  320. {
  321. buySl = Ask - (slPips * Point() * 10);
  322. }
  323. if(tpPips != 0)
  324. {
  325. buyTp = Ask + (tpPips * Point() * 10);
  326. }
  327. if(eaType == Tally_Sim)
  328. {
  329. AddToStructure(ticketAssigner,0,magicNo,Ask,0,TimeCurrent(),0,buySl,buyTp,lot,0);
  330. ticketAssigner++;
  331. DrawVirtualBuyOpen(Ask);
  332. }
  333. else
  334. {
  335. int count = orderCount();
  336. if(prevOrderCount != count)
  337. {
  338. for(int k = prevOrderCount + 1;k <= count;k++)
  339. {
  340. getTicketByNumber(k,buySl,buyTp);
  341. if(enableTradingDaily == true && doTrading == true)
  342. {
  343. if(eaType == Tally_Trade && CopyTallyTrade)
  344. {
  345. if(CopyBuffer(handler, 0, 0, 4, bufferData) < 0)
  346. {
  347. Print("Error in copying Buffer data ", GetLastError());
  348. }
  349. double balance = bufferData[1];
  350. if(CopyBuffer(handler, 1, 0, 4, bufferData) < 0)
  351. {
  352. Print("Error in copying Buffer data ", GetLastError());
  353. }
  354. double MA = bufferData[1];
  355. Print(" Balance = ",balance," MA = ",MA);
  356. if(tradesDirection == buy)
  357. {
  358. if(balance > MA)
  359. {
  360. if(!trade.Buy(lot, Symbol(),SymbolInfoDouble(Symbol(),SYMBOL_ASK),buySl,buyTp,"Buy Trade"))
  361. {
  362. Print(" Error in Placing Buy Trade : ",GetLastError());
  363. }
  364. }
  365. else
  366. {
  367. Print(" Trade is not Placed because Balance is less than MA Value ");
  368. }
  369. }
  370. else
  371. {
  372. if(balance < MA)
  373. {
  374. if(!trade.Sell(lot,Symbol(),SymbolInfoDouble(Symbol(),SYMBOL_BID),buyTp,buySl,"Sell Trade"))
  375. {
  376. Print(" Error in Placing Sell Trade : ",GetLastError());
  377. }
  378. }
  379. else
  380. {
  381. Print(" Trade is not Placed because Balance is less than MA Value ");
  382. }
  383. }
  384. }
  385. }
  386. }
  387. }
  388. }
  389. }
  390. //+------------------------------------------------------------------+
  391. //| |
  392. //+------------------------------------------------------------------+
  393. void placeSellTrade()
  394. {
  395. double sellSl = 0, sellTp = 0;
  396. double Bid = SymbolInfoDouble(Symbol(),SYMBOL_BID);
  397. if(slPips != 0)
  398. {
  399. sellSl = Bid + (slPips * 10 * Point());
  400. }
  401. if(tpPips != 0)
  402. {
  403. sellTp = Bid - (tpPips * 10 * Point());
  404. }
  405. if(eaType == Tally_Sim)
  406. {
  407. AddToStructure(ticketAssigner,1,magicNo,Bid,0,TimeCurrent(),0,sellSl,sellTp,lot,0);
  408. ticketAssigner++;
  409. }
  410. else
  411. {
  412. int count = orderCount();
  413. if(prevOrderCount != count)
  414. {
  415. for(int k = prevOrderCount + 1;k <= count;k++)
  416. {
  417. getTicketByNumber(k,sellSl,sellTp);
  418. if(enableTradingDaily == true)
  419. {
  420. if(eaType == Tally_Trade && CopyTallyTrade)
  421. {
  422. if(CopyBuffer(handler, 0, 0, 4, bufferData) < 0)
  423. {
  424. Print("Error in copying Buffer data ", GetLastError());
  425. }
  426. double balance = bufferData[1];
  427. if(CopyBuffer(handler, 1, 0, 4, bufferData) < 0)
  428. {
  429. Print("Error in copying Buffer data ", GetLastError());
  430. }
  431. double MA = bufferData[1];
  432. Print(" Balance = ",balance," MA = ",MA);
  433. if(tradesDirection == reverse)
  434. {
  435. if(balance < MA)
  436. {
  437. if(!trade.Sell(lot,Symbol(),Bid,sellSl,sellTp,"Sell Trade"))
  438. {
  439. Print(" Error in Placing Sell Trade : ",GetLastError());
  440. }
  441. }
  442. else
  443. {
  444. Print(" Trade is not Placed because Balance is less than MA Value ");
  445. }
  446. }
  447. else
  448. {
  449. if(balance > MA)
  450. {
  451. if(!trade.Buy(lot,Symbol(),SymbolInfoDouble(Symbol(),SYMBOL_ASK),sellTp,sellSl,"Buy Trade"))
  452. {
  453. Print(" Error in Placing Buy Trade : ",GetLastError());
  454. }
  455. }
  456. else
  457. {
  458. Print(" Trade is not Placed because Balance is less than MA Value ");
  459. }
  460. }
  461. }
  462. }
  463. }
  464. }
  465. }
  466. }
  467. //+------------------------------------------------------------------+
  468. //| |
  469. //+------------------------------------------------------------------+
  470. void AddToStructure(int ticket, int type, int magic, double open_price,
  471. double close_price, datetime open_time, datetime close_time,
  472. double sl, double tp, double lotSize, double profit)
  473. {
  474. for(int i = 0; i < MaxOrders; i++)
  475. {
  476. if(od[i].trade_ticket == -1)
  477. {
  478. od[i].trade_ticket = ticket;
  479. od[i].trade_type = type;
  480. od[i].trade_magic_no = magic;
  481. od[i].trade_open_price = open_price;
  482. od[i].trade_close_price = close_price;
  483. od[i].trade_open_time = open_time;
  484. od[i].trade_close_time = close_time;
  485. od[i].trade_sl = sl;
  486. od[i].trade_tp = tp;
  487. od[i].trade_lot = lotSize;
  488. od[i].trade_profit = profit;
  489. Print(" ========== Trade Placed of Ticket ========== ",ticket);
  490. Print("[AddToStructure] Added at index: ", i,
  491. " | Ticket = ", ticket,
  492. " | Type = ", type,
  493. " | Magic = ", magic,
  494. " | OpenPrice = ", open_price,
  495. " | ClosePrice = ", close_price,
  496. " | SL = ", sl,
  497. " | TP = ", tp,
  498. " | Lots = ", lotSize,
  499. " | Profit = ", profit);
  500. break;
  501. }
  502. }
  503. }
  504. //+------------------------------------------------------------------+
  505. //| |
  506. //+------------------------------------------------------------------+
  507. void checkTPSLHit()
  508. {
  509. double bid = SymbolInfoDouble(_Symbol, SYMBOL_BID);
  510. double ask = SymbolInfoDouble(_Symbol, SYMBOL_ASK);
  511. for(int i = 0; i < MaxOrders; i++)
  512. {
  513. if(od[i].trade_ticket != -1 && od[i].trade_close_price == 0)
  514. {
  515. int ticket = od[i].trade_ticket;
  516. int type = od[i].trade_type;
  517. double sl = od[i].trade_sl;
  518. double tp = od[i].trade_tp;
  519. double closePrice = 0;
  520. // ----------------------------------------------
  521. // BUY ORDER CHECK
  522. // ----------------------------------------------
  523. if(type == 0)
  524. {
  525. // TP hit → Bid >= TP
  526. if(bid >= tp && tp > 0)
  527. {
  528. closePrice = bid;
  529. Print(" ======== Buy Trade TP Hit ======= ",ticket);
  530. }
  531. // SL hit → Bid <= SL
  532. if(bid <= sl && sl > 0)
  533. {
  534. closePrice = bid;
  535. Print(" ======== Buy Trade SL Hit ======= ",ticket);
  536. }
  537. }
  538. // ----------------------------------------------
  539. // SELL ORDER CHECK
  540. // ----------------------------------------------
  541. if(type == 1)
  542. {
  543. // TP hit → Ask <= TP (price goes DOWN)
  544. if(ask <= tp && tp > 0)
  545. {
  546. closePrice = ask;
  547. Print(" ======== Sell Trade TP Hit ======= ",ticket);
  548. }
  549. // SL hit → Ask >= SL
  550. if(ask >= sl && sl > 0)
  551. {
  552. closePrice = ask;
  553. Print(" ======== Sell Trade SL Hit ======= ",ticket);
  554. }
  555. }
  556. // ----------------------------------------------
  557. // IF ANYTHING TRIGGERED → CLOSE TRADE
  558. // ----------------------------------------------
  559. if(closePrice > 0)
  560. {
  561. od[i].trade_close_price = closePrice;
  562. od[i].trade_close_time = TimeCurrent();
  563. double tpdifference = type == 1 ? (od[i].trade_open_price - od[i].trade_close_price) / Point() : (od[i].trade_close_price - od[i].trade_open_price) / Point();
  564. od[i].trade_profit += tpinDollar(od[i].trade_lot, tpdifference);
  565. Print("======= TRADE CLOSED of ticket =======",ticket);
  566. Print("Index: ", i,
  567. " | Ticket: ", ticket,
  568. " | Type: ", type,
  569. " | ClosePrice: ", closePrice,
  570. " | Time: ", od[i].trade_close_time,
  571. " | Profit: ", od[i].trade_profit);
  572. DrawVirtualBuyClose(closePrice);
  573. datetime t1 = od[i].trade_open_time;
  574. double price1 = od[i].trade_open_price;
  575. datetime t2 = od[i].trade_close_time;
  576. double price2 = od[i].trade_close_price;
  577. DrawDottedTrendline("Ticket "+string(ticket), t1, price1, t2, price2, clrGreen);
  578. tpSlHit = false; // make these zero so new trade place's
  579. string line = MakeTradeString(
  580. od[i].trade_ticket,
  581. od[i].trade_type,
  582. od[i].trade_magic_no,
  583. od[i].trade_open_price,
  584. od[i].trade_close_price,
  585. od[i].trade_open_time,
  586. od[i].trade_close_time,
  587. od[i].trade_sl,
  588. od[i].trade_tp,
  589. od[i].trade_lot,
  590. od[i].trade_profit
  591. );
  592. writeDatainFile(line);
  593. }
  594. }
  595. }
  596. }
  597. //+------------------------------------------------------------------+
  598. //| |
  599. //+------------------------------------------------------------------+
  600. double tpinDollar(double lotSize, double distance)
  601. {
  602. double pipvalue = NormalizeDouble(((SymbolInfoDouble(Symbol(),SYMBOL_TRADE_TICK_VALUE)/(SymbolInfoDouble(Symbol(),SYMBOL_TRADE_TICK_SIZE)/Point()))*10),2);
  603. pipvalue = pipvalue / 10;
  604. double dollar = lotSize * distance * pipvalue;
  605. return NormalizeDouble(dollar,2);
  606. }
  607. //+------------------------------------------------------------------+
  608. //| |
  609. //+------------------------------------------------------------------+
  610. void writeDatainFile(string str)
  611. {
  612. int filehandle = FileOpen(filename,FILE_WRITE|FILE_CSV|FILE_COMMON|FILE_END,",");
  613. if(filehandle != INVALID_HANDLE)
  614. {
  615. FileSeek(filehandle, 0, SEEK_END);
  616. FileWrite(filehandle,str);
  617. Print(str);
  618. FileClose(filehandle);
  619. }
  620. }
  621. //+------------------------------------------------------------------+
  622. //| |
  623. //+------------------------------------------------------------------+
  624. string MakeTradeString(int ticket, int type, int magic,
  625. double open_price, double close_price,
  626. datetime open_time, datetime close_time,
  627. double sl, double tp, double lotSize, double profit)
  628. {
  629. string str = StringFormat("%d,%d,%d,%.5f,%.5f,%s,%s,%.5f,%.5f,%.2f,%.2f",
  630. ticket,
  631. type,
  632. magic,
  633. open_price,
  634. close_price,
  635. TimeToString(open_time, TIME_DATE|TIME_SECONDS),
  636. TimeToString(close_time, TIME_DATE|TIME_SECONDS),
  637. sl,
  638. tp,
  639. lotSize,
  640. profit);
  641. return str;
  642. }
  643. //+------------------------------------------------------------------+
  644. //| |
  645. //+------------------------------------------------------------------+
  646. void setStart_EndTime(bool onInit,string start,string end,datetime & sessionStart,datetime & sessionEnd)
  647. {
  648. int newYorkStartHour = 0, newYorkStartMin = 0, newYorkEndHour = 0, newYorkEndMin = 0;
  649. datetime newYorkStartTrading,newYorkEndTrading;
  650. string time[];
  651. StringSplit(start,':',time);
  652. newYorkStartHour = (int)StringToInteger(time[0]);
  653. newYorkStartMin = (int)StringToInteger(time[1]);
  654. EventSetMillisecondTimer(500);
  655. time[0] = "";
  656. time[1] = "";
  657. StringSplit(end,':',time);
  658. newYorkEndHour = (int)StringToInteger(time[0]);
  659. newYorkEndMin = (int)StringToInteger(time[1]);
  660. // Print(" Start Time Hour: ",newYorkStartHour," Start Time Min: ",newYorkStartMin);
  661. // Print(" End Time Hour: ",newYorkEndHour," End Time Min: ",newYorkEndMin);
  662. datetime startDateTime;
  663. MqlDateTime st;
  664. TimeCurrent(st); // get current date
  665. st.hour = newYorkStartHour;
  666. st.min = newYorkStartMin;
  667. st.sec = 0;
  668. startDateTime = StructToTime(st);
  669. datetime endDateTime;
  670. MqlDateTime et;
  671. TimeCurrent(et); // get current date
  672. et.hour = newYorkEndHour;
  673. et.min = newYorkEndMin;
  674. et.sec = 0;
  675. endDateTime = StructToTime(et);
  676. MqlDateTime sdate,edate;
  677. datetime start_Time = 0, end_Time = 0;
  678. if(startDateTime > endDateTime)
  679. {
  680. if(onInit)
  681. {
  682. start_Time = iTime(Symbol(),PERIOD_D1,1);
  683. end_Time = iTime(Symbol(),PERIOD_D1,0);
  684. }
  685. else
  686. {
  687. start_Time = sessionStart;
  688. end_Time = sessionEnd;
  689. if(TimeCurrent() >= sessionEnd && sessionEnd != 0)
  690. {
  691. start_Time = iTime(Symbol(),PERIOD_D1,0);
  692. end_Time = start_Time + 86400;
  693. }
  694. }
  695. }
  696. else
  697. {
  698. start_Time = iTime(Symbol(),PERIOD_D1,0);
  699. end_Time = iTime(Symbol(),PERIOD_D1,0);
  700. }
  701. if(TimeToStruct(end_Time,edate))
  702. {
  703. edate.hour = newYorkEndHour;
  704. edate.min = newYorkEndMin;
  705. edate.sec = 0;
  706. }
  707. else
  708. Print("Error in Converting Time: ",GetLastError());
  709. newYorkEndTrading = StructToTime(edate);
  710. if(TimeToStruct(start_Time,sdate))
  711. {
  712. sdate.hour = newYorkStartHour;
  713. sdate.min = newYorkStartMin;
  714. sdate.sec = 0;
  715. }
  716. else
  717. Print("Error in Converting Time: ",GetLastError());
  718. newYorkStartTrading = StructToTime(sdate);
  719. sessionStart = newYorkStartTrading;
  720. sessionEnd = newYorkEndTrading;
  721. }
  722. //+------------------------------------------------------------------+
  723. //| |
  724. //+------------------------------------------------------------------+
  725. void setStart_EndTime_modify(bool onInit,string start,string end,datetime & sessionStart,datetime & sessionEnd)
  726. {
  727. int newYorkStartHour = 0, newYorkStartMin = 0, newYorkEndHour = 0, newYorkEndMin = 0;
  728. datetime newYorkStartTrading,newYorkEndTrading;
  729. string time[];
  730. StringSplit(start,':',time);
  731. newYorkStartHour = (int)StringToInteger(time[0]);
  732. newYorkStartMin = (int)StringToInteger(time[1]);
  733. time[0] = "";
  734. time[1] = "";
  735. StringSplit(end,':',time);
  736. newYorkEndHour = (int)StringToInteger(time[0]);
  737. newYorkEndMin = (int)StringToInteger(time[1]);
  738. // Print(" Start Time Hour: ",newYorkStartHour," Start Time Min: ",newYorkStartMin);
  739. // Print(" End Time Hour: ",newYorkEndHour," End Time Min: ",newYorkEndMin);
  740. datetime startDateTime;
  741. MqlDateTime st;
  742. TimeCurrent(st); // get current date
  743. st.hour = newYorkStartHour;
  744. st.min = newYorkStartMin;
  745. st.sec = 0;
  746. startDateTime = StructToTime(st);
  747. datetime endDateTime;
  748. MqlDateTime et;
  749. TimeCurrent(et); // get current date
  750. et.hour = newYorkEndHour;
  751. et.min = newYorkEndMin;
  752. et.sec = 0;
  753. endDateTime = StructToTime(et);
  754. MqlDateTime sdate,edate;
  755. datetime start_Time = 0, end_Time = 0;
  756. if(startDateTime > endDateTime)
  757. {
  758. start_Time = iTime(Symbol(),PERIOD_D1,1);
  759. end_Time = iTime(Symbol(),PERIOD_D1,0);
  760. }
  761. else
  762. {
  763. start_Time = iTime(Symbol(),PERIOD_D1,0);
  764. end_Time = iTime(Symbol(),PERIOD_D1,0);
  765. }
  766. if(TimeToStruct(end_Time,edate))
  767. {
  768. edate.hour = newYorkEndHour;
  769. edate.min = newYorkEndMin;
  770. edate.sec = 0;
  771. }
  772. else
  773. Print("Error in Converting Time: ",GetLastError());
  774. newYorkEndTrading = StructToTime(edate);
  775. if(TimeToStruct(start_Time,sdate))
  776. {
  777. sdate.hour = newYorkStartHour;
  778. sdate.min = newYorkStartMin;
  779. sdate.sec = 0;
  780. }
  781. else
  782. Print("Error in Converting Time: ",GetLastError());
  783. newYorkStartTrading = StructToTime(sdate);
  784. sessionStart = newYorkStartTrading;
  785. sessionEnd = newYorkEndTrading;
  786. }
  787. //+------------------------------------------------------------------+
  788. //| Check Virtual TP/SL for all positions |
  789. //+------------------------------------------------------------------+
  790. void CheckVirtualGlobalTpSl()
  791. {
  792. double bid = SymbolInfoDouble(_Symbol, SYMBOL_BID);
  793. double ask = SymbolInfoDouble(_Symbol, SYMBOL_ASK);
  794. for(int i=PositionsTotal()-1; i >=0 ; i--)
  795. {
  796. ulong ticket = PositionGetTicket(i);
  797. if(PositionSelectByTicket(ticket))
  798. {
  799. if(PositionGetInteger(POSITION_MAGIC) == magicNo &&
  800. PositionGetString(POSITION_SYMBOL) == _Symbol)
  801. {
  802. if(PositionGetInteger(POSITION_TYPE) == POSITION_TYPE_BUY)
  803. {
  804. double tp_price = PositionGetDouble(POSITION_PRICE_OPEN) + glTp * 10 * SymbolInfoDouble(_Symbol, SYMBOL_POINT);
  805. double sl_price = PositionGetDouble(POSITION_PRICE_OPEN) - glSl * 10 * SymbolInfoDouble(_Symbol, SYMBOL_POINT);
  806. if(bid >= tp_price || bid <= sl_price)
  807. {
  808. closeAllActiveOrders();
  809. return;
  810. }
  811. }
  812. if(PositionGetInteger(POSITION_TYPE) == POSITION_TYPE_SELL)
  813. {
  814. double tp_price = PositionGetDouble(POSITION_PRICE_OPEN) - glTp * 10 * SymbolInfoDouble(_Symbol, SYMBOL_POINT);
  815. double sl_price = PositionGetDouble(POSITION_PRICE_OPEN) + glSl * 10 * SymbolInfoDouble(_Symbol, SYMBOL_POINT);
  816. if(ask <= tp_price || ask >= sl_price)
  817. {
  818. closeAllActiveOrders();
  819. return;
  820. }
  821. }
  822. }
  823. }
  824. }
  825. }
  826. //+------------------------------------------------------------------+
  827. //| |
  828. //+------------------------------------------------------------------+
  829. void CheckDailyDrawdown()
  830. {
  831. if(!UseDailyDrawdownLimit)
  832. return;
  833. double equity = AccountInfoDouble(ACCOUNT_EQUITY);
  834. double drawdown = g_dailyStartBalance - equity;
  835. if(drawdown >= DailyDrawdownAmount)
  836. {
  837. Print("Daily Drawdown Limit Hit: ", drawdown, " >= ", DailyDrawdownAmount);
  838. closeAllActiveOrders();
  839. }
  840. }
  841. //+------------------------------------------------------------------+
  842. //| |
  843. //+------------------------------------------------------------------+
  844. void markClosedOrder(datetime eaTime)
  845. {
  846. HistorySelect(eaTime, TimeCurrent());
  847. for(int i = HistoryDealsTotal() - 1; i >= 0; i--)
  848. {
  849. ulong dealTicket = HistoryDealGetTicket(i);
  850. long dealMagic = HistoryDealGetInteger(dealTicket, DEAL_MAGIC);
  851. if(dealMagic != magicNo && dealMagic != 0)
  852. continue;
  853. if(HistoryDealGetString(dealTicket, DEAL_SYMBOL) == Symbol())
  854. {
  855. //Print("Condition 2 ",HistoryDealGetInteger(dealTicket, DEAL_ENTRY)," HistoryDealsTotal(): ",HistoryDealsTotal());
  856. if(HistoryDealGetInteger(dealTicket, DEAL_ENTRY) == DEAL_ENTRY_OUT)
  857. {
  858. //Print("deal out close: ",dealTicket);
  859. long dealType = HistoryDealGetInteger(dealTicket, DEAL_TYPE);
  860. if(dealType != DEAL_TYPE_BUY && dealType != DEAL_TYPE_SELL)
  861. continue;
  862. double profit = HistoryDealGetDouble(dealTicket, DEAL_PROFIT);
  863. profit = NormalizeDouble(profit, 2);
  864. string lineName = "TradeLine_" + (string)dealTicket;
  865. if(ObjectFind(0, lineName) >= 0)
  866. continue;
  867. ulong entryDeal = findEntryDeal(dealTicket);
  868. if(entryDeal == 0)
  869. continue;
  870. datetime openTime = (datetime)HistoryDealGetInteger(entryDeal, DEAL_TIME);
  871. double openPrice = HistoryDealGetDouble(entryDeal, DEAL_PRICE);
  872. datetime closeTime = (datetime)HistoryDealGetInteger(dealTicket, DEAL_TIME);
  873. double closePrice = HistoryDealGetDouble(dealTicket, DEAL_PRICE);
  874. createTrendLine(lineName, openTime, openPrice, closeTime, closePrice, dealType, profit);
  875. PrintFormat("Trend line created for closed trade #%I64u | Profit: %.2f", dealTicket, profit);
  876. }
  877. }
  878. }
  879. }
  880. //+------------------------------------------------------------------+
  881. //| |
  882. //+------------------------------------------------------------------+
  883. void createTrendLine(string name,
  884. datetime openTime, double openPrice,
  885. datetime closeTime, double closePrice,
  886. long dealType, double profit)
  887. {
  888. if(ObjectFind(0, name) >= 0)
  889. return;
  890. if(!ObjectCreate(0, name, OBJ_TREND, 0, openTime, openPrice, closeTime, closePrice))
  891. {
  892. Print("Error creating trend line: ", GetLastError());
  893. return;
  894. }
  895. ObjectSetInteger(0, name, OBJPROP_WIDTH, tradeLineThickness);
  896. ObjectSetInteger(0, name, OBJPROP_STYLE, STYLE_SOLID);
  897. ObjectSetInteger(0, name, OBJPROP_RAY, false);
  898. color lineColor = (dealType == DEAL_TYPE_BUY) ? clrRed : clrBlue;
  899. ObjectSetInteger(0, name, OBJPROP_COLOR, lineColor);
  900. createProfitLabel(name + "_label", openTime, openPrice, closeTime, closePrice, dealType, profit);
  901. }
  902. //+------------------------------------------------------------------+
  903. //| |
  904. //+------------------------------------------------------------------+
  905. void createProfitLabel(string name,
  906. datetime openTime, double openPrice,
  907. datetime closeTime, double closePrice,
  908. long dealType, double profit)
  909. {
  910. if(ObjectFind(0, name) >= 0)
  911. return;
  912. datetime middleTime = openTime + (closeTime - openTime) / 2;
  913. double midPrice = (openPrice + closePrice) / 2;
  914. if(!ObjectCreate(0, name, OBJ_TEXT, 0, middleTime, midPrice))
  915. {
  916. Print("Error creating profit label: ", GetLastError());
  917. return;
  918. }
  919. string profitText = "$" + DoubleToString(profit, 2);
  920. ObjectSetString(0, name, OBJPROP_TEXT, profitText);
  921. ObjectSetInteger(0, name, OBJPROP_FONTSIZE, dollarFontSize);
  922. ObjectSetInteger(0, name, OBJPROP_COLOR, dollarFontColor);
  923. ObjectSetInteger(0, name, OBJPROP_ANCHOR, ANCHOR_TOP);
  924. ObjectSetInteger(0, name, OBJPROP_SELECTABLE, false);
  925. }
  926. //+------------------------------------------------------------------+
  927. //| |
  928. //+------------------------------------------------------------------+
  929. ulong findEntryDeal(ulong closeDeal)
  930. {
  931. string symbol = HistoryDealGetString(closeDeal, DEAL_SYMBOL);
  932. long positionID = HistoryDealGetInteger(closeDeal, DEAL_POSITION_ID);
  933. int dealOutCount = 0;
  934. for(int i = HistoryDealsTotal() - 1; i >= 0; i--)
  935. {
  936. ulong deal = HistoryDealGetTicket(i);
  937. if(HistoryDealGetInteger(deal, DEAL_POSITION_ID) == positionID)
  938. {
  939. if(HistoryDealGetInteger(deal, DEAL_ENTRY) == DEAL_ENTRY_OUT)
  940. {
  941. dealOutCount++;
  942. }
  943. }
  944. }
  945. if(dealOutCount < 2)
  946. {
  947. for(int i = HistoryDealsTotal() - 1; i >= 0; i--)
  948. {
  949. ulong deal = HistoryDealGetTicket(i);
  950. if(HistoryDealGetInteger(deal, DEAL_POSITION_ID) == positionID &&
  951. HistoryDealGetInteger(deal, DEAL_ENTRY) == DEAL_ENTRY_IN &&
  952. HistoryDealGetString(deal, DEAL_SYMBOL) == symbol)
  953. return deal;
  954. //Print("Deal: ", deal);
  955. }
  956. }
  957. else
  958. {
  959. for(int i = 0; i < HistoryDealsTotal(); i++)
  960. {
  961. ulong deal = HistoryDealGetTicket(i);
  962. if(HistoryDealGetInteger(deal, DEAL_POSITION_ID) == positionID &&
  963. HistoryDealGetInteger(deal, DEAL_ENTRY) == DEAL_ENTRY_OUT)
  964. {
  965. return deal;
  966. }
  967. //Print("Deal: ", deal);
  968. }
  969. }
  970. return 0;
  971. }
  972. //+------------------------------------------------------------------+
  973. //| |
  974. //+------------------------------------------------------------------+
  975. void DrawArrow(string name, datetime time, double price, color clr, int arrow)
  976. {
  977. if(ObjectFind(0, name) == -1)
  978. {
  979. ObjectCreate(0, name, OBJ_ARROW, 0, time, price);
  980. ObjectSetInteger(0, name, OBJPROP_COLOR, clr);
  981. ObjectSetInteger(0, name, OBJPROP_WIDTH, 1);
  982. ObjectSetInteger(0, name, OBJPROP_ARROWCODE, arrow);
  983. }
  984. }
  985. //+------------------------------------------------------------------+
  986. //| |
  987. //+------------------------------------------------------------------+
  988. void DrawVirtualBuyOpen(double openPrice)
  989. {
  990. datetime t = TimeCurrent();
  991. string name = "VBUY_OPEN_" + IntegerToString(t);
  992. // DrawArrow(name, t, openPrice, clrLime, 233);
  993. ObjectCreate(0,name,OBJ_ARROW_BUY,0,TimeCurrent(),openPrice);
  994. }
  995. //+------------------------------------------------------------------+
  996. //| |
  997. //+------------------------------------------------------------------+
  998. void DrawVirtualBuyClose(double closePrice)
  999. {
  1000. datetime t = TimeCurrent();
  1001. string name = "VBUY_CLOSE_" + IntegerToString(t);
  1002. // DrawArrow(name, t, closePrice, clrRed, 234);
  1003. ObjectCreate(0,name,OBJ_ARROW_SELL,0,TimeCurrent(),closePrice);
  1004. }
  1005. //+------------------------------------------------------------------+
  1006. //| |
  1007. //+------------------------------------------------------------------+
  1008. void DrawDottedTrendline(string name, datetime time1, double price1, datetime time2, double price2, color clr)
  1009. {
  1010. // Delete if already exists
  1011. if(ObjectFind(0, name) != -1)
  1012. ObjectDelete(0, name);
  1013. // Create the trendline
  1014. if(!ObjectCreate(0, name, OBJ_TREND, 0, time1, price1, time2, price2))
  1015. Print("Error creating trendline: ", GetLastError());
  1016. // Set properties
  1017. ObjectSetInteger(0, name, OBJPROP_COLOR, clr);
  1018. ObjectSetInteger(0, name, OBJPROP_STYLE, STYLE_DOT); // Dotted line
  1019. ObjectSetInteger(0, name, OBJPROP_WIDTH, 1); // Line width
  1020. }
  1021. //+------------------------------------------------------------------+
  1022. //| |
  1023. //+------------------------------------------------------------------+
  1024. int orderCount()
  1025. {
  1026. int handle = FileOpen(filename, FILE_READ | FILE_COMMON);
  1027. if(handle == INVALID_HANDLE)
  1028. {
  1029. Print("File not found: ", filename);
  1030. return 0;
  1031. }
  1032. int index = 0;
  1033. while(!FileIsEnding(handle))
  1034. {
  1035. string line = FileReadString(handle);
  1036. // Skip empty line
  1037. if(StringLen(line) < 2)
  1038. continue;
  1039. string parts[];
  1040. int count = StringSplit(line, ',', parts);
  1041. int ticket = (int)StringToInteger(parts[0]);
  1042. int type = (int)StringToInteger(parts[1]);
  1043. int magic = (int)StringToInteger(parts[2]);
  1044. double open_price = StringToDouble(parts[3]);
  1045. double close_price = StringToDouble(parts[4]);
  1046. datetime open_time = StringToTime(parts[5]);
  1047. datetime close_time = StringToTime(parts[6]);
  1048. double sl = StringToDouble(parts[7]);
  1049. double tp = StringToDouble(parts[8]);
  1050. double lotS = StringToDouble(parts[9]);
  1051. double profit = StringToDouble(parts[10]);
  1052. index++;
  1053. }
  1054. FileClose(handle);
  1055. return index;
  1056. }
  1057. //+------------------------------------------------------------------+
  1058. //| |
  1059. //+------------------------------------------------------------------+
  1060. int getTicketByNumber(int id,double & buySl,double & buyTp)
  1061. {
  1062. int handle = FileOpen(filename, FILE_READ | FILE_COMMON);
  1063. if(handle == INVALID_HANDLE)
  1064. {
  1065. Print("File not found: ", filename);
  1066. return 0;
  1067. }
  1068. int index = 0;
  1069. while(!FileIsEnding(handle))
  1070. {
  1071. string line = FileReadString(handle);
  1072. // Skip empty line
  1073. if(StringLen(line) < 2)
  1074. continue;
  1075. string parts[];
  1076. int count = StringSplit(line, ',', parts);
  1077. int ticket = (int)StringToInteger(parts[0]);
  1078. int type = (int)StringToInteger(parts[1]);
  1079. int magic = (int)StringToInteger(parts[2]);
  1080. double open_price = StringToDouble(parts[3]);
  1081. double close_price = StringToDouble(parts[4]);
  1082. datetime open_time = StringToTime(parts[5]);
  1083. datetime close_time = StringToTime(parts[6]);
  1084. double sl = StringToDouble(parts[7]);
  1085. double tp = StringToDouble(parts[8]);
  1086. double lotS = StringToDouble(parts[9]);
  1087. double profit = StringToDouble(parts[10]);
  1088. if(id == ticket)
  1089. {
  1090. buySl = sl;
  1091. buyTp = tp;
  1092. }
  1093. }
  1094. FileClose(handle);
  1095. return index;
  1096. }
  1097. //+------------------------------------------------------------------+