暫無描述

Pulse_EA_project_MT5.mq5 79KB

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