Nenhuma descrição

Pulse_EA_project_MT5.mq5 75KB

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