Brak opisu

Pulse_EA_project_MT5.mq5 88KB

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