Ingen beskrivning

Pulse_EA_project_MT5.mq5 72KB

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