暫無描述

Pulse_EA_project_MT5.mq5 79KB

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