Няма описание

Pulse_EA_project_MT5.mq5 89KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301
  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 = 123; // 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 = "123";
  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 || eaType == Tally_Trade)
  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 && count != -1)
  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. prevOrderCount = count;
  388. }
  389. }
  390. }
  391. //+------------------------------------------------------------------+
  392. //| |
  393. //+------------------------------------------------------------------+
  394. void placeSellTrade()
  395. {
  396. double sellSl = 0, sellTp = 0;
  397. double Bid = SymbolInfoDouble(Symbol(),SYMBOL_BID);
  398. if(slPips != 0)
  399. {
  400. sellSl = Bid + (slPips * 10 * Point());
  401. }
  402. if(tpPips != 0)
  403. {
  404. sellTp = Bid - (tpPips * 10 * Point());
  405. }
  406. if(eaType == Tally_Sim)
  407. {
  408. AddToStructure(ticketAssigner,1,magicNo,Bid,0,TimeCurrent(),0,sellSl,sellTp,lot,0);
  409. ticketAssigner++;
  410. }
  411. else
  412. {
  413. int count = orderCount();
  414. if(prevOrderCount != count && count != -1)
  415. {
  416. for(int k = prevOrderCount + 1;k <= count;k++)
  417. {
  418. getTicketByNumber(k,sellSl,sellTp);
  419. if(enableTradingDaily == true)
  420. {
  421. if(eaType == Tally_Trade && CopyTallyTrade)
  422. {
  423. if(CopyBuffer(handler, 0, 0, 4, bufferData) < 0)
  424. {
  425. Print("Error in copying Buffer data ", GetLastError());
  426. }
  427. double balance = bufferData[1];
  428. if(CopyBuffer(handler, 1, 0, 4, bufferData) < 0)
  429. {
  430. Print("Error in copying Buffer data ", GetLastError());
  431. }
  432. double MA = bufferData[1];
  433. Print(" Balance = ",balance," MA = ",MA);
  434. if(tradesDirection == reverse)
  435. {
  436. if(balance < MA)
  437. {
  438. if(!trade.Sell(lot,Symbol(),Bid,sellSl,sellTp,"Sell Trade"))
  439. {
  440. Print(" Error in Placing Sell Trade : ",GetLastError());
  441. }
  442. }
  443. else
  444. {
  445. Print(" Trade is not Placed because Balance is less than MA Value ");
  446. }
  447. }
  448. else
  449. {
  450. if(balance > MA)
  451. {
  452. if(!trade.Buy(lot,Symbol(),SymbolInfoDouble(Symbol(),SYMBOL_ASK),sellTp,sellSl,"Buy Trade"))
  453. {
  454. Print(" Error in Placing Buy Trade : ",GetLastError());
  455. }
  456. }
  457. else
  458. {
  459. Print(" Trade is not Placed because Balance is less than MA Value ");
  460. }
  461. }
  462. }
  463. }
  464. }
  465. prevOrderCount = count;
  466. }
  467. }
  468. }
  469. //+------------------------------------------------------------------+
  470. //| |
  471. //+------------------------------------------------------------------+
  472. void AddToStructure(int ticket, int type, int magic, double open_price,
  473. double close_price, datetime open_time, datetime close_time,
  474. double sl, double tp, double lotSize, double profit)
  475. {
  476. for(int i = 0; i < MaxOrders; i++)
  477. {
  478. if(od[i].trade_ticket == -1)
  479. {
  480. od[i].trade_ticket = ticket;
  481. od[i].trade_type = type;
  482. od[i].trade_magic_no = magic;
  483. od[i].trade_open_price = open_price;
  484. od[i].trade_close_price = close_price;
  485. od[i].trade_open_time = open_time;
  486. od[i].trade_close_time = close_time;
  487. od[i].trade_sl = sl;
  488. od[i].trade_tp = tp;
  489. od[i].trade_lot = lotSize;
  490. od[i].trade_profit = profit;
  491. Print(" ========== Trade Placed of Ticket ========== ",ticket);
  492. Print("[AddToStructure] Added at index: ", i,
  493. " | Ticket = ", ticket,
  494. " | Type = ", type,
  495. " | Magic = ", magic,
  496. " | OpenPrice = ", open_price,
  497. " | ClosePrice = ", close_price,
  498. " | SL = ", sl,
  499. " | TP = ", tp,
  500. " | Lots = ", lotSize,
  501. " | Profit = ", profit);
  502. break;
  503. }
  504. }
  505. }
  506. //+------------------------------------------------------------------+
  507. //| |
  508. //+------------------------------------------------------------------+
  509. void checkTPSLHit()
  510. {
  511. double bid = SymbolInfoDouble(_Symbol, SYMBOL_BID);
  512. double ask = SymbolInfoDouble(_Symbol, SYMBOL_ASK);
  513. for(int i = 0; i < MaxOrders; i++)
  514. {
  515. if(od[i].trade_ticket != -1 && od[i].trade_close_price == 0)
  516. {
  517. int ticket = od[i].trade_ticket;
  518. int type = od[i].trade_type;
  519. double sl = od[i].trade_sl;
  520. double tp = od[i].trade_tp;
  521. double closePrice = 0;
  522. // ----------------------------------------------
  523. // BUY ORDER CHECK
  524. // ----------------------------------------------
  525. if(type == 0)
  526. {
  527. // TP hit → Bid >= TP
  528. if(bid >= tp && tp > 0)
  529. {
  530. closePrice = bid;
  531. Print(" ======== Buy Trade TP Hit ======= ",ticket);
  532. }
  533. // SL hit → Bid <= SL
  534. if(bid <= sl && sl > 0)
  535. {
  536. closePrice = bid;
  537. Print(" ======== Buy Trade SL Hit ======= ",ticket);
  538. }
  539. }
  540. // ----------------------------------------------
  541. // SELL ORDER CHECK
  542. // ----------------------------------------------
  543. if(type == 1)
  544. {
  545. // TP hit → Ask <= TP (price goes DOWN)
  546. if(ask <= tp && tp > 0)
  547. {
  548. closePrice = ask;
  549. Print(" ======== Sell Trade TP Hit ======= ",ticket);
  550. }
  551. // SL hit → Ask >= SL
  552. if(ask >= sl && sl > 0)
  553. {
  554. closePrice = ask;
  555. Print(" ======== Sell Trade SL Hit ======= ",ticket);
  556. }
  557. }
  558. // ----------------------------------------------
  559. // IF ANYTHING TRIGGERED → CLOSE TRADE
  560. // ----------------------------------------------
  561. if(closePrice > 0)
  562. {
  563. od[i].trade_close_price = closePrice;
  564. od[i].trade_close_time = TimeCurrent();
  565. 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();
  566. od[i].trade_profit += tpinDollar(od[i].trade_lot, tpdifference);
  567. Print("======= TRADE CLOSED of ticket =======",ticket);
  568. Print("Index: ", i,
  569. " | Ticket: ", ticket,
  570. " | Type: ", type,
  571. " | ClosePrice: ", closePrice,
  572. " | Time: ", od[i].trade_close_time,
  573. " | Profit: ", od[i].trade_profit);
  574. DrawVirtualBuyClose(closePrice);
  575. datetime t1 = od[i].trade_open_time;
  576. double price1 = od[i].trade_open_price;
  577. datetime t2 = od[i].trade_close_time;
  578. double price2 = od[i].trade_close_price;
  579. DrawDottedTrendline("Ticket "+string(ticket), t1, price1, t2, price2, clrGreen);
  580. tpSlHit = false; // make these zero so new trade place's
  581. string line = MakeTradeString(
  582. od[i].trade_ticket,
  583. od[i].trade_type,
  584. od[i].trade_magic_no,
  585. od[i].trade_open_price,
  586. od[i].trade_close_price,
  587. od[i].trade_open_time,
  588. od[i].trade_close_time,
  589. od[i].trade_sl,
  590. od[i].trade_tp,
  591. od[i].trade_lot,
  592. od[i].trade_profit
  593. );
  594. writeDatainFile(line);
  595. }
  596. }
  597. }
  598. }
  599. //+------------------------------------------------------------------+
  600. //| |
  601. //+------------------------------------------------------------------+
  602. double tpinDollar(double lotSize, double distance)
  603. {
  604. double pipvalue = NormalizeDouble(((SymbolInfoDouble(Symbol(),SYMBOL_TRADE_TICK_VALUE)/(SymbolInfoDouble(Symbol(),SYMBOL_TRADE_TICK_SIZE)/Point()))*10),2);
  605. pipvalue = pipvalue / 10;
  606. double dollar = lotSize * distance * pipvalue;
  607. return NormalizeDouble(dollar,2);
  608. }
  609. //+------------------------------------------------------------------+
  610. //| |
  611. //+------------------------------------------------------------------+
  612. void writeDatainFile(string str)
  613. {
  614. int filehandle = FileOpen(filename,FILE_WRITE|FILE_CSV|FILE_COMMON|FILE_END,",");
  615. if(filehandle != INVALID_HANDLE)
  616. {
  617. FileSeek(filehandle, 0, SEEK_END);
  618. FileWrite(filehandle,str);
  619. Print(str);
  620. FileClose(filehandle);
  621. }
  622. }
  623. //+------------------------------------------------------------------+
  624. //| |
  625. //+------------------------------------------------------------------+
  626. string MakeTradeString(int ticket, int type, int magic,
  627. double open_price, double close_price,
  628. datetime open_time, datetime close_time,
  629. double sl, double tp, double lotSize, double profit)
  630. {
  631. string str = StringFormat("%d,%d,%d,%.5f,%.5f,%s,%s,%.5f,%.5f,%.2f,%.2f",
  632. ticket,
  633. type,
  634. magic,
  635. open_price,
  636. close_price,
  637. TimeToString(open_time, TIME_DATE|TIME_SECONDS),
  638. TimeToString(close_time, TIME_DATE|TIME_SECONDS),
  639. sl,
  640. tp,
  641. lotSize,
  642. profit);
  643. return str;
  644. }
  645. //+------------------------------------------------------------------+
  646. //| |
  647. //+------------------------------------------------------------------+
  648. void setStart_EndTime(bool onInit,string start,string end,datetime & sessionStart,datetime & sessionEnd)
  649. {
  650. int newYorkStartHour = 0, newYorkStartMin = 0, newYorkEndHour = 0, newYorkEndMin = 0;
  651. datetime newYorkStartTrading,newYorkEndTrading;
  652. string time[];
  653. StringSplit(start,':',time);
  654. newYorkStartHour = (int)StringToInteger(time[0]);
  655. newYorkStartMin = (int)StringToInteger(time[1]);
  656. EventSetMillisecondTimer(500);
  657. time[0] = "";
  658. time[1] = "";
  659. StringSplit(end,':',time);
  660. newYorkEndHour = (int)StringToInteger(time[0]);
  661. newYorkEndMin = (int)StringToInteger(time[1]);
  662. // Print(" Start Time Hour: ",newYorkStartHour," Start Time Min: ",newYorkStartMin);
  663. // Print(" End Time Hour: ",newYorkEndHour," End Time Min: ",newYorkEndMin);
  664. datetime startDateTime;
  665. MqlDateTime st;
  666. TimeCurrent(st); // get current date
  667. st.hour = newYorkStartHour;
  668. st.min = newYorkStartMin;
  669. st.sec = 0;
  670. startDateTime = StructToTime(st);
  671. datetime endDateTime;
  672. MqlDateTime et;
  673. TimeCurrent(et); // get current date
  674. et.hour = newYorkEndHour;
  675. et.min = newYorkEndMin;
  676. et.sec = 0;
  677. endDateTime = StructToTime(et);
  678. MqlDateTime sdate,edate;
  679. datetime start_Time = 0, end_Time = 0;
  680. if(startDateTime > endDateTime)
  681. {
  682. if(onInit)
  683. {
  684. start_Time = iTime(Symbol(),PERIOD_D1,1);
  685. end_Time = iTime(Symbol(),PERIOD_D1,0);
  686. }
  687. else
  688. {
  689. start_Time = sessionStart;
  690. end_Time = sessionEnd;
  691. if(TimeCurrent() >= sessionEnd && sessionEnd != 0)
  692. {
  693. start_Time = iTime(Symbol(),PERIOD_D1,0);
  694. end_Time = start_Time + 86400;
  695. }
  696. }
  697. }
  698. else
  699. {
  700. start_Time = iTime(Symbol(),PERIOD_D1,0);
  701. end_Time = iTime(Symbol(),PERIOD_D1,0);
  702. }
  703. if(TimeToStruct(end_Time,edate))
  704. {
  705. edate.hour = newYorkEndHour;
  706. edate.min = newYorkEndMin;
  707. edate.sec = 0;
  708. }
  709. else
  710. Print("Error in Converting Time: ",GetLastError());
  711. newYorkEndTrading = StructToTime(edate);
  712. if(TimeToStruct(start_Time,sdate))
  713. {
  714. sdate.hour = newYorkStartHour;
  715. sdate.min = newYorkStartMin;
  716. sdate.sec = 0;
  717. }
  718. else
  719. Print("Error in Converting Time: ",GetLastError());
  720. newYorkStartTrading = StructToTime(sdate);
  721. sessionStart = newYorkStartTrading;
  722. sessionEnd = newYorkEndTrading;
  723. }
  724. //+------------------------------------------------------------------+
  725. //| |
  726. //+------------------------------------------------------------------+
  727. void setStart_EndTime_modify(bool onInit,string start,string end,datetime & sessionStart,datetime & sessionEnd)
  728. {
  729. int newYorkStartHour = 0, newYorkStartMin = 0, newYorkEndHour = 0, newYorkEndMin = 0;
  730. datetime newYorkStartTrading,newYorkEndTrading;
  731. string time[];
  732. StringSplit(start,':',time);
  733. newYorkStartHour = (int)StringToInteger(time[0]);
  734. newYorkStartMin = (int)StringToInteger(time[1]);
  735. time[0] = "";
  736. time[1] = "";
  737. StringSplit(end,':',time);
  738. newYorkEndHour = (int)StringToInteger(time[0]);
  739. newYorkEndMin = (int)StringToInteger(time[1]);
  740. // Print(" Start Time Hour: ",newYorkStartHour," Start Time Min: ",newYorkStartMin);
  741. // Print(" End Time Hour: ",newYorkEndHour," End Time Min: ",newYorkEndMin);
  742. datetime startDateTime;
  743. MqlDateTime st;
  744. TimeCurrent(st); // get current date
  745. st.hour = newYorkStartHour;
  746. st.min = newYorkStartMin;
  747. st.sec = 0;
  748. startDateTime = StructToTime(st);
  749. datetime endDateTime;
  750. MqlDateTime et;
  751. TimeCurrent(et); // get current date
  752. et.hour = newYorkEndHour;
  753. et.min = newYorkEndMin;
  754. et.sec = 0;
  755. endDateTime = StructToTime(et);
  756. MqlDateTime sdate,edate;
  757. datetime start_Time = 0, end_Time = 0;
  758. if(startDateTime > endDateTime)
  759. {
  760. start_Time = iTime(Symbol(),PERIOD_D1,1);
  761. end_Time = iTime(Symbol(),PERIOD_D1,0);
  762. }
  763. else
  764. {
  765. start_Time = iTime(Symbol(),PERIOD_D1,0);
  766. end_Time = iTime(Symbol(),PERIOD_D1,0);
  767. }
  768. if(TimeToStruct(end_Time,edate))
  769. {
  770. edate.hour = newYorkEndHour;
  771. edate.min = newYorkEndMin;
  772. edate.sec = 0;
  773. }
  774. else
  775. Print("Error in Converting Time: ",GetLastError());
  776. newYorkEndTrading = StructToTime(edate);
  777. if(TimeToStruct(start_Time,sdate))
  778. {
  779. sdate.hour = newYorkStartHour;
  780. sdate.min = newYorkStartMin;
  781. sdate.sec = 0;
  782. }
  783. else
  784. Print("Error in Converting Time: ",GetLastError());
  785. newYorkStartTrading = StructToTime(sdate);
  786. sessionStart = newYorkStartTrading;
  787. sessionEnd = newYorkEndTrading;
  788. }
  789. //+------------------------------------------------------------------+
  790. //| Check Virtual TP/SL for all positions |
  791. //+------------------------------------------------------------------+
  792. void CheckVirtualGlobalTpSl()
  793. {
  794. double bid = SymbolInfoDouble(_Symbol, SYMBOL_BID);
  795. double ask = SymbolInfoDouble(_Symbol, SYMBOL_ASK);
  796. for(int i=PositionsTotal()-1; i >=0 ; i--)
  797. {
  798. ulong ticket = PositionGetTicket(i);
  799. if(PositionSelectByTicket(ticket))
  800. {
  801. if(PositionGetInteger(POSITION_MAGIC) == magicNo &&
  802. PositionGetString(POSITION_SYMBOL) == _Symbol)
  803. {
  804. if(PositionGetInteger(POSITION_TYPE) == POSITION_TYPE_BUY)
  805. {
  806. double tp_price = PositionGetDouble(POSITION_PRICE_OPEN) + glTp * 10 * SymbolInfoDouble(_Symbol, SYMBOL_POINT);
  807. double sl_price = PositionGetDouble(POSITION_PRICE_OPEN) - glSl * 10 * SymbolInfoDouble(_Symbol, SYMBOL_POINT);
  808. if(bid >= tp_price || bid <= sl_price)
  809. {
  810. closeAllActiveOrders();
  811. return;
  812. }
  813. }
  814. if(PositionGetInteger(POSITION_TYPE) == POSITION_TYPE_SELL)
  815. {
  816. double tp_price = PositionGetDouble(POSITION_PRICE_OPEN) - glTp * 10 * SymbolInfoDouble(_Symbol, SYMBOL_POINT);
  817. double sl_price = PositionGetDouble(POSITION_PRICE_OPEN) + glSl * 10 * SymbolInfoDouble(_Symbol, SYMBOL_POINT);
  818. if(ask <= tp_price || ask >= sl_price)
  819. {
  820. closeAllActiveOrders();
  821. return;
  822. }
  823. }
  824. }
  825. }
  826. }
  827. }
  828. //+------------------------------------------------------------------+
  829. //| |
  830. //+------------------------------------------------------------------+
  831. void CheckDailyDrawdown()
  832. {
  833. if(!UseDailyDrawdownLimit)
  834. return;
  835. double equity = AccountInfoDouble(ACCOUNT_EQUITY);
  836. double drawdown = g_dailyStartBalance - equity;
  837. if(drawdown >= DailyDrawdownAmount)
  838. {
  839. Print("Daily Drawdown Limit Hit: ", drawdown, " >= ", DailyDrawdownAmount);
  840. closeAllActiveOrders();
  841. }
  842. }
  843. //+------------------------------------------------------------------+
  844. //| |
  845. //+------------------------------------------------------------------+
  846. void markClosedOrder(datetime eaTime)
  847. {
  848. HistorySelect(eaTime, TimeCurrent());
  849. for(int i = HistoryDealsTotal() - 1; i >= 0; i--)
  850. {
  851. ulong dealTicket = HistoryDealGetTicket(i);
  852. long dealMagic = HistoryDealGetInteger(dealTicket, DEAL_MAGIC);
  853. if(dealMagic != magicNo && dealMagic != 0)
  854. continue;
  855. if(HistoryDealGetString(dealTicket, DEAL_SYMBOL) == Symbol())
  856. {
  857. //Print("Condition 2 ",HistoryDealGetInteger(dealTicket, DEAL_ENTRY)," HistoryDealsTotal(): ",HistoryDealsTotal());
  858. if(HistoryDealGetInteger(dealTicket, DEAL_ENTRY) == DEAL_ENTRY_OUT)
  859. {
  860. //Print("deal out close: ",dealTicket);
  861. long dealType = HistoryDealGetInteger(dealTicket, DEAL_TYPE);
  862. if(dealType != DEAL_TYPE_BUY && dealType != DEAL_TYPE_SELL)
  863. continue;
  864. double profit = HistoryDealGetDouble(dealTicket, DEAL_PROFIT);
  865. profit = NormalizeDouble(profit, 2);
  866. string lineName = "TradeLine_" + (string)dealTicket;
  867. if(ObjectFind(0, lineName) >= 0)
  868. continue;
  869. ulong entryDeal = findEntryDeal(dealTicket);
  870. if(entryDeal == 0)
  871. continue;
  872. datetime openTime = (datetime)HistoryDealGetInteger(entryDeal, DEAL_TIME);
  873. double openPrice = HistoryDealGetDouble(entryDeal, DEAL_PRICE);
  874. datetime closeTime = (datetime)HistoryDealGetInteger(dealTicket, DEAL_TIME);
  875. double closePrice = HistoryDealGetDouble(dealTicket, DEAL_PRICE);
  876. createTrendLine(lineName, openTime, openPrice, closeTime, closePrice, dealType, profit);
  877. PrintFormat("Trend line created for closed trade #%I64u | Profit: %.2f", dealTicket, profit);
  878. }
  879. }
  880. }
  881. }
  882. //+------------------------------------------------------------------+
  883. //| |
  884. //+------------------------------------------------------------------+
  885. void createTrendLine(string name,
  886. datetime openTime, double openPrice,
  887. datetime closeTime, double closePrice,
  888. long dealType, double profit)
  889. {
  890. if(ObjectFind(0, name) >= 0)
  891. return;
  892. if(!ObjectCreate(0, name, OBJ_TREND, 0, openTime, openPrice, closeTime, closePrice))
  893. {
  894. Print("Error creating trend line: ", GetLastError());
  895. return;
  896. }
  897. ObjectSetInteger(0, name, OBJPROP_WIDTH, tradeLineThickness);
  898. ObjectSetInteger(0, name, OBJPROP_STYLE, STYLE_SOLID);
  899. ObjectSetInteger(0, name, OBJPROP_RAY, false);
  900. color lineColor = (dealType == DEAL_TYPE_BUY) ? clrRed : clrBlue;
  901. ObjectSetInteger(0, name, OBJPROP_COLOR, lineColor);
  902. createProfitLabel(name + "_label", openTime, openPrice, closeTime, closePrice, dealType, profit);
  903. }
  904. //+------------------------------------------------------------------+
  905. //| |
  906. //+------------------------------------------------------------------+
  907. void createProfitLabel(string name,
  908. datetime openTime, double openPrice,
  909. datetime closeTime, double closePrice,
  910. long dealType, double profit)
  911. {
  912. if(ObjectFind(0, name) >= 0)
  913. return;
  914. datetime middleTime = openTime + (closeTime - openTime) / 2;
  915. double midPrice = (openPrice + closePrice) / 2;
  916. if(!ObjectCreate(0, name, OBJ_TEXT, 0, middleTime, midPrice))
  917. {
  918. Print("Error creating profit label: ", GetLastError());
  919. return;
  920. }
  921. string profitText = "$" + DoubleToString(profit, 2);
  922. ObjectSetString(0, name, OBJPROP_TEXT, profitText);
  923. ObjectSetInteger(0, name, OBJPROP_FONTSIZE, dollarFontSize);
  924. ObjectSetInteger(0, name, OBJPROP_COLOR, dollarFontColor);
  925. ObjectSetInteger(0, name, OBJPROP_ANCHOR, ANCHOR_TOP);
  926. ObjectSetInteger(0, name, OBJPROP_SELECTABLE, false);
  927. }
  928. //+------------------------------------------------------------------+
  929. //| |
  930. //+------------------------------------------------------------------+
  931. ulong findEntryDeal(ulong closeDeal)
  932. {
  933. string symbol = HistoryDealGetString(closeDeal, DEAL_SYMBOL);
  934. long positionID = HistoryDealGetInteger(closeDeal, DEAL_POSITION_ID);
  935. int dealOutCount = 0;
  936. for(int i = HistoryDealsTotal() - 1; i >= 0; i--)
  937. {
  938. ulong deal = HistoryDealGetTicket(i);
  939. if(HistoryDealGetInteger(deal, DEAL_POSITION_ID) == positionID)
  940. {
  941. if(HistoryDealGetInteger(deal, DEAL_ENTRY) == DEAL_ENTRY_OUT)
  942. {
  943. dealOutCount++;
  944. }
  945. }
  946. }
  947. if(dealOutCount < 2)
  948. {
  949. for(int i = HistoryDealsTotal() - 1; i >= 0; i--)
  950. {
  951. ulong deal = HistoryDealGetTicket(i);
  952. if(HistoryDealGetInteger(deal, DEAL_POSITION_ID) == positionID &&
  953. HistoryDealGetInteger(deal, DEAL_ENTRY) == DEAL_ENTRY_IN &&
  954. HistoryDealGetString(deal, DEAL_SYMBOL) == symbol)
  955. return deal;
  956. //Print("Deal: ", deal);
  957. }
  958. }
  959. else
  960. {
  961. for(int i = 0; i < HistoryDealsTotal(); i++)
  962. {
  963. ulong deal = HistoryDealGetTicket(i);
  964. if(HistoryDealGetInteger(deal, DEAL_POSITION_ID) == positionID &&
  965. HistoryDealGetInteger(deal, DEAL_ENTRY) == DEAL_ENTRY_OUT)
  966. {
  967. return deal;
  968. }
  969. //Print("Deal: ", deal);
  970. }
  971. }
  972. return 0;
  973. }
  974. //+------------------------------------------------------------------+
  975. //| |
  976. //+------------------------------------------------------------------+
  977. void DrawArrow(string name, datetime time, double price, color clr, int arrow)
  978. {
  979. if(ObjectFind(0, name) == -1)
  980. {
  981. ObjectCreate(0, name, OBJ_ARROW, 0, time, price);
  982. ObjectSetInteger(0, name, OBJPROP_COLOR, clr);
  983. ObjectSetInteger(0, name, OBJPROP_WIDTH, 1);
  984. ObjectSetInteger(0, name, OBJPROP_ARROWCODE, arrow);
  985. }
  986. }
  987. //+------------------------------------------------------------------+
  988. //| |
  989. //+------------------------------------------------------------------+
  990. void DrawVirtualBuyOpen(double openPrice)
  991. {
  992. datetime t = TimeCurrent();
  993. string name = "VBUY_OPEN_" + IntegerToString(t);
  994. // DrawArrow(name, t, openPrice, clrLime, 233);
  995. ObjectCreate(0,name,OBJ_ARROW_BUY,0,TimeCurrent(),openPrice);
  996. }
  997. //+------------------------------------------------------------------+
  998. //| |
  999. //+------------------------------------------------------------------+
  1000. void DrawVirtualBuyClose(double closePrice)
  1001. {
  1002. datetime t = TimeCurrent();
  1003. string name = "VBUY_CLOSE_" + IntegerToString(t);
  1004. // DrawArrow(name, t, closePrice, clrRed, 234);
  1005. ObjectCreate(0,name,OBJ_ARROW_SELL,0,TimeCurrent(),closePrice);
  1006. }
  1007. //+------------------------------------------------------------------+
  1008. //| |
  1009. //+------------------------------------------------------------------+
  1010. void DrawDottedTrendline(string name, datetime time1, double price1, datetime time2, double price2, color clr)
  1011. {
  1012. // Delete if already exists
  1013. if(ObjectFind(0, name) != -1)
  1014. ObjectDelete(0, name);
  1015. // Create the trendline
  1016. if(!ObjectCreate(0, name, OBJ_TREND, 0, time1, price1, time2, price2))
  1017. Print("Error creating trendline: ", GetLastError());
  1018. // Set properties
  1019. ObjectSetInteger(0, name, OBJPROP_COLOR, clr);
  1020. ObjectSetInteger(0, name, OBJPROP_STYLE, STYLE_DOT); // Dotted line
  1021. ObjectSetInteger(0, name, OBJPROP_WIDTH, 1); // Line width
  1022. }
  1023. //+------------------------------------------------------------------+
  1024. //| |
  1025. //+------------------------------------------------------------------+
  1026. int orderCount()
  1027. {
  1028. int handle = FileOpen(filename, FILE_READ | FILE_COMMON);
  1029. if(handle == INVALID_HANDLE)
  1030. {
  1031. Print("EA=> Handler invalid: orderCount() ", filename," ",GetLastError()," eaType: ",eaType);
  1032. return -1;
  1033. }
  1034. int index = 0;
  1035. while(!FileIsEnding(handle))
  1036. {
  1037. string line = FileReadString(handle);
  1038. // Skip empty line
  1039. if(StringLen(line) < 2)
  1040. continue;
  1041. string parts[];
  1042. int count = StringSplit(line, ',', parts);
  1043. int ticket = (int)StringToInteger(parts[0]);
  1044. int type = (int)StringToInteger(parts[1]);
  1045. int magic = (int)StringToInteger(parts[2]);
  1046. double open_price = StringToDouble(parts[3]);
  1047. double close_price = StringToDouble(parts[4]);
  1048. datetime open_time = StringToTime(parts[5]);
  1049. datetime close_time = StringToTime(parts[6]);
  1050. double sl = StringToDouble(parts[7]);
  1051. double tp = StringToDouble(parts[8]);
  1052. double lotS = StringToDouble(parts[9]);
  1053. double profit = StringToDouble(parts[10]);
  1054. index++;
  1055. }
  1056. FileClose(handle);
  1057. return index;
  1058. }
  1059. //+------------------------------------------------------------------+
  1060. //| |
  1061. //+------------------------------------------------------------------+
  1062. int getTicketByNumber(int id,double & buySl,double & buyTp)
  1063. {
  1064. int handle = FileOpen(filename, FILE_READ | FILE_COMMON);
  1065. if(handle == INVALID_HANDLE)
  1066. {
  1067. Print("EA=> Handler invalid: getTicketByNumber() ", filename," error: ",GetLastError()," eaType: ",eaType);
  1068. return 0;
  1069. }
  1070. int index = 0;
  1071. while(!FileIsEnding(handle))
  1072. {
  1073. string line = FileReadString(handle);
  1074. // Skip empty line
  1075. if(StringLen(line) < 2)
  1076. continue;
  1077. string parts[];
  1078. int count = StringSplit(line, ',', parts);
  1079. int ticket = (int)StringToInteger(parts[0]);
  1080. int type = (int)StringToInteger(parts[1]);
  1081. int magic = (int)StringToInteger(parts[2]);
  1082. double open_price = StringToDouble(parts[3]);
  1083. double close_price = StringToDouble(parts[4]);
  1084. datetime open_time = StringToTime(parts[5]);
  1085. datetime close_time = StringToTime(parts[6]);
  1086. double sl = StringToDouble(parts[7]);
  1087. double tp = StringToDouble(parts[8]);
  1088. double lotS = StringToDouble(parts[9]);
  1089. double profit = StringToDouble(parts[10]);
  1090. if(id == ticket)
  1091. {
  1092. buySl = sl;
  1093. buyTp = tp;
  1094. }
  1095. }
  1096. FileClose(handle);
  1097. return index;
  1098. }
  1099. //+------------------------------------------------------------------+