説明なし

Pulse_EA_project_MT5.mq5 79KB

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