Ei kuvausta

Pulse EA.mq5 121KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754
  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 global "var"
  12. #define MaxOrders 10000
  13. struct new_trade_store
  14. {
  15. int trade_ticket;
  16. int trade_type;
  17. int trade_magic_no;
  18. double trade_open_price;
  19. double trade_close_price;
  20. datetime trade_open_time;
  21. datetime trade_close_time;
  22. double trade_sl;
  23. double trade_tp;
  24. double trade_lot;
  25. double trade_profit;
  26. new_trade_store()
  27. {
  28. trade_ticket = -1;
  29. trade_type = -1;
  30. trade_magic_no = -1;
  31. trade_open_price = -1;
  32. trade_close_price = -1;
  33. trade_open_time = -1;
  34. trade_close_time = -1;
  35. trade_sl = -1;
  36. trade_tp = -1;
  37. trade_lot = -1;
  38. trade_profit = -1;
  39. }
  40. };
  41. new_trade_store od[MaxOrders];
  42. struct trade_sync
  43. {
  44. ulong sim_trade_ticket;
  45. ulong live_trade_ticket;
  46. trade_sync()
  47. {
  48. sim_trade_ticket = -1;
  49. live_trade_ticket = -1;
  50. }
  51. };
  52. trade_sync od_sync[MaxOrders];
  53. enum trade_typ
  54. {
  55. buy, // Buy
  56. reverse, // Reverse
  57. };
  58. enum EA_TYPE
  59. {
  60. Tally_Sim, // Tally Sim
  61. Tally_Trade, // Tally Trade
  62. };
  63. input string gnrlsettings = " ================ General Settings =================== ";//_
  64. input EA_TYPE eaType = Tally_Sim; // EA Option
  65. input double tpPips = 20; // Tp Pips
  66. input double slPips = 20; // SL Pips
  67. input double lot = 0.1; // Lot Size
  68. input string gnrlesettings = " ================ Tally Sim Settings =================== ";//_
  69. trade_typ ordTyp = buy; // Order Type (Tally Sim)
  70. input int magicNo = 123; // Magic #
  71. input string fileName = "TradeDataFile"; // File Name (Tally Sim)
  72. input string grlesettings = " ================ Tally Trade Settings =================== ";//_
  73. input trade_typ tradesDirection = buy; // Order Type (Tally Trade)
  74. input int magicNo1 = 1; // Copy Trade Magic #
  75. input bool CopyTallyTrade = true; // Enable Copy Trade
  76. input bool useMovingAVG = true; // Use moving average filter
  77. input double glTp = 20; // Copy Take Profit
  78. input double glSl = 10; // Copy Stop Loss
  79. input string Settings6 = "------------- Display Settings -------------"; //_
  80. input int tradeLineThickness = 2; // Trade Line Thickness
  81. input int dollarFontSize = 10; // Dollar Text Font Size
  82. input color dollarFontColor = clrAqua; // Dollar Text Font Colour
  83. input string horizontalLineName = "close"; // Horizontal Line Name
  84. input string Settings5 = "------------- Time Filter Settings -------------"; //_
  85. input bool enableTimeFilter = false; // Enable Time Filter
  86. input string startTime = "22:00"; // Start Time
  87. input string endTime = "01:00"; // End Time
  88. input bool useFridayClose = false; // Use Friday Close
  89. input string closeFriday = "23:00"; // Friday Close Time
  90. input bool useMondayOpen = false; // Use Monday Open
  91. input string mondayOpen = "01:00"; // Monday Open Time
  92. input string Settings25 = "------------- Daily Draw Limit Settings -------------"; //_
  93. input bool UseDailyDrawdownLimit = true; // Enable Daily Draw Down
  94. input double DailyDrawdownAmount = 2000; // $2000 limit
  95. input string DrawdownResetTime = "05:00"; // Enable Trading At
  96. input string indSettings = " ================ Indicator Settings =================== ";//_
  97. input color Dot_Color = clrOrangeRed;
  98. input double StartingBalance = 10000;
  99. input string MagicNumbers = "123";
  100. input int MA_Period = 5;
  101. input ENUM_MA_METHOD MA_Method = MODE_SMA;
  102. input string fileName1 = "TradeDataFile"; // File Name
  103. input int historyTrades = 50;
  104. bool tpSlHit = false;
  105. static int ticketAssigner = 1;
  106. int handler;
  107. double bufferData[];
  108. ushort u_sep; // The code of the separator character
  109. string sep = ":"; // A separator as a character
  110. string result1[];
  111. datetime startTradingTime = 0, endTradingTime = 0, dailyDrawDownTime = 0;
  112. datetime mondayTradingStart = 0, fridayTradingClose = 0;
  113. datetime eaStartTime; // Store EA start time
  114. double g_dailyStartBalance;
  115. bool enableTradingDaily = true;
  116. int prevOrderCount = 0;
  117. //+------------------------------------------------------------------+
  118. //| |
  119. //+------------------------------------------------------------------+
  120. string filename = fileName + Symbol() + ".csv";
  121. //+------------------------------------------------------------------+
  122. //| Expert initialization function |
  123. //+------------------------------------------------------------------+
  124. int OnInit()
  125. {
  126. //---
  127. if(!GlobalVariableCheck(global)) //for creating
  128. {
  129. GlobalVariableSet(global,0);
  130. // 0 means Free
  131. // 1 means busy
  132. }
  133. if(eaType == Tally_Sim)
  134. {
  135. FileDelete(filename,FILE_WRITE|FILE_CSV|FILE_COMMON|FILE_END);
  136. int filehandle = FileOpen(filename,FILE_WRITE|FILE_CSV|FILE_COMMON|FILE_END,",");
  137. if(filehandle != INVALID_HANDLE)
  138. {
  139. FileClose(filehandle);
  140. }
  141. }
  142. else
  143. {
  144. // prevOrderCount = orderCount();
  145. }
  146. string typ = eaType == 0 ? "Tally Sim" :"Tally Trade";
  147. Comment(" Current Mode: ",typ);
  148. tpSlHit = false;
  149. ticketAssigner = 1;
  150. if(eaType == Tally_Trade)
  151. {
  152. ArrayInitialize(bufferData,0.0);
  153. handler = iCustom(Symbol(),PERIOD_CURRENT,"Pulse Balance Indicator Sim",Dot_Color,StartingBalance,MagicNumbers,MA_Period,MA_Method,fileName1,historyTrades);
  154. ArraySetAsSeries(bufferData,true);
  155. }
  156. trade.SetExpertMagicNumber(magicNo1);
  157. trade.SetDeviationInPoints(10);
  158. trade.SetTypeFilling(ORDER_FILLING_IOC);
  159. trade.LogLevel(LOG_LEVEL_ALL);
  160. trade.SetAsyncMode(false);
  161. setStart_EndTime_modify(true,startTime,endTime,startTradingTime,endTradingTime);
  162. setStart_EndTime(true,startTime,endTime,startTradingTime,endTradingTime);
  163. g_dailyStartBalance = AccountInfoDouble(ACCOUNT_BALANCE);
  164. enableTradingDaily = true;
  165. eaStartTime = TimeCurrent(); // Track EA start time
  166. double balance = AccountInfoDouble(ACCOUNT_BALANCE);
  167. int magic = 123456;
  168. int maPeriod = 50;
  169. bool useMA = true;
  170. bool ddReached = false;
  171. CreateInfoLabels(balance, magic, maPeriod, useMA, ddReached);
  172. //---
  173. return(INIT_SUCCEEDED);
  174. }
  175. //+------------------------------------------------------------------+
  176. //| Expert deinitialization function |
  177. //+------------------------------------------------------------------+
  178. void OnDeinit(const int reason)
  179. {
  180. //---
  181. GlobalVariableSet(global,0);
  182. if(eaType == Tally_Sim)
  183. {
  184. deleteObjects();
  185. }
  186. Comment("");
  187. }
  188. //+------------------------------------------------------------------+
  189. //| Expert tick function |
  190. //+------------------------------------------------------------------+
  191. void OnTick()
  192. {
  193. //---
  194. timeConversion();
  195. CheckDailyDrawdown();
  196. if(TimeCurrent() >= dailyDrawDownTime && enableTradingDaily == false)
  197. {
  198. enableTradingDaily = true;
  199. g_dailyStartBalance = AccountInfoDouble(ACCOUNT_BALANCE);
  200. }
  201. if(eaType == Tally_Trade)
  202. {
  203. markClosedOrder(eaStartTime);
  204. checkVirtualTicketClosed(); // check if virtual trade closed so close Active Trade as well
  205. }
  206. if(eaType == Tally_Sim)
  207. {
  208. checkTPSLHit();
  209. }
  210. newBar();
  211. MqlDateTime dt;
  212. TimeToStruct(TimeCurrent(), dt);
  213. if(useMondayOpen)
  214. {
  215. // Print(" Week == ",dt.day_of_week," Start Time = ",mondayTradingStart);
  216. if(dt.day_of_week == 1 && TimeCurrent() < mondayTradingStart) // it's Monday
  217. {
  218. return;
  219. }
  220. }
  221. if(useFridayClose)
  222. {
  223. // Print(" Week == ",dt.day_of_week," End Time = ",fridayTradingClose);
  224. if(dt.day_of_week == 5 && TimeCurrent() >= fridayTradingClose) // it's Friday
  225. {
  226. closeAllActiveOrders();
  227. closeAllVirtualTrades();
  228. return;
  229. }
  230. }
  231. setStart_EndTime_modify(false,startTime,endTime,startTradingTime,endTradingTime);
  232. setStart_EndTime(false,startTime,endTime,startTradingTime,endTradingTime);
  233. if(enableTimeFilter && TimeCurrent() >= startTradingTime && TimeCurrent() < endTradingTime)
  234. {
  235. return;
  236. }
  237. placeTrade();
  238. }
  239. //+------------------------------------------------------------------+
  240. //| |
  241. //+------------------------------------------------------------------+
  242. bool newBar()
  243. {
  244. static datetime lastbar;
  245. datetime curbar = iTime(Symbol(), PERIOD_CURRENT, 0);
  246. if(lastbar != curbar)
  247. {
  248. lastbar = curbar;
  249. Print(" ---------------------- New Bar :: ---------------------- ",lastbar);
  250. return (true);
  251. }
  252. else
  253. {
  254. return (false);
  255. }
  256. }
  257. //+------------------------------------------------------------------+
  258. //| |
  259. //+------------------------------------------------------------------+
  260. bool newDayBar()
  261. {
  262. static datetime lastbar1;
  263. datetime curbar1 = iTime(Symbol(), PERIOD_D1, 0);
  264. if(lastbar1 != curbar1)
  265. {
  266. lastbar1 = curbar1;
  267. Print(" ---------------------- New Day Bar :: ---------------------- ",lastbar1);
  268. return (true);
  269. }
  270. else
  271. {
  272. return (false);
  273. }
  274. }
  275. //+------------------------------------------------------------------+
  276. //| |
  277. //+------------------------------------------------------------------+
  278. void closeAllActiveOrders()
  279. {
  280. for(int i=PositionsTotal()-1; i >=0 ; i--)
  281. {
  282. ulong ticket = PositionGetTicket(i);
  283. if(PositionSelectByTicket(ticket))
  284. {
  285. if(PositionGetInteger(POSITION_MAGIC) == magicNo &&
  286. PositionGetString(POSITION_SYMBOL) == Symbol())
  287. {
  288. if(trade.PositionClose(ticket))
  289. {
  290. Print("Closing All Active Orders");
  291. Print("Position closed ", ticket);
  292. }
  293. else
  294. {
  295. Print("Cannot close order: ",GetLastError());
  296. }
  297. }
  298. }
  299. }
  300. }
  301. //+------------------------------------------------------------------+
  302. //| |
  303. //+------------------------------------------------------------------+
  304. void timeConversion()
  305. {
  306. MqlDateTime date1, date_1,date_2;
  307. TimeToStruct(iTime(Symbol(),PERIOD_CURRENT,0),date1);
  308. u_sep=StringGetCharacter(sep,0);
  309. StringSplit(mondayOpen,u_sep,result1);
  310. date1.hour = (int)StringToInteger(result1[0]);
  311. date1.min = (int)StringToInteger(result1[1]);
  312. mondayTradingStart = StructToTime(date1);
  313. TimeToStruct(iTime(Symbol(),PERIOD_CURRENT,0),date_1);
  314. StringSplit(closeFriday,u_sep,result1);
  315. date_1.hour = (int)StringToInteger(result1[0]);
  316. date_1.min = (int)StringToInteger(result1[1]);
  317. fridayTradingClose = StructToTime(date_1);
  318. TimeToStruct(iTime(Symbol(),PERIOD_CURRENT,0),date_2);
  319. StringSplit(DrawdownResetTime,u_sep,result1);
  320. date_2.hour = (int)StringToInteger(result1[0]);
  321. date_2.min = (int)StringToInteger(result1[1]);
  322. dailyDrawDownTime = StructToTime(date_2);
  323. }
  324. //+------------------------------------------------------------------+
  325. //| |
  326. //+------------------------------------------------------------------+
  327. void placeTrade()
  328. {
  329. if(tpSlHit == false || eaType == Tally_Trade)
  330. {
  331. if(ordTyp == buy)
  332. {
  333. placeBuyTrade();
  334. }
  335. if(ordTyp == reverse)
  336. {
  337. placeSellTrade();
  338. }
  339. tpSlHit = true;
  340. }
  341. }
  342. //+------------------------------------------------------------------+
  343. //| |
  344. //+------------------------------------------------------------------+
  345. void placeBuyTrade()
  346. {
  347. double buySl = 0,buyTp=0;
  348. double Ask = SymbolInfoDouble(Symbol(),SYMBOL_ASK);
  349. if(slPips != 0)
  350. {
  351. buySl = Ask - (slPips * Point() * 10);
  352. }
  353. if(tpPips != 0)
  354. {
  355. buyTp = Ask + (tpPips * Point() * 10);
  356. }
  357. if(eaType == Tally_Sim)
  358. {
  359. AddToStructure(ticketAssigner,0,magicNo,Ask,0,TimeCurrent(),0,buySl,buyTp,lot,0);
  360. ticketAssigner++;
  361. DrawVirtualBuyOpen(Ask);
  362. }
  363. else
  364. {
  365. if(GlobalVariableGet(global) == 0)
  366. {
  367. int count = orderCount();
  368. if(prevOrderCount != count && count != -1)
  369. {
  370. for(int k = prevOrderCount + 1;k <= count;k++)
  371. {
  372. if(getTicketByNumber(k,buySl,buyTp) != -1)
  373. {
  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 == buy)
  390. {
  391. if((balance > MA && useMovingAVG) || !(useMovingAVG))
  392. {
  393. double buy_Tp = SymbolInfoDouble(Symbol(),SYMBOL_ASK) + glTp * 10 * SymbolInfoDouble(_Symbol, SYMBOL_POINT);
  394. double buy_Sl = SymbolInfoDouble(Symbol(),SYMBOL_ASK) - glSl * 10 * SymbolInfoDouble(_Symbol, SYMBOL_POINT);
  395. if(!trade.Buy(lot, Symbol(),SymbolInfoDouble(Symbol(),SYMBOL_ASK),buy_Sl,buy_Tp,"Buy Trade"))
  396. {
  397. Print(" Error in Placing Buy Trade : ",GetLastError());
  398. }
  399. else
  400. {
  401. tradeSyncAddToStruct(k,trade.ResultOrder());
  402. }
  403. }
  404. else
  405. {
  406. Print(" Trade is not Placed because Balance is less than MA Value ");
  407. }
  408. }
  409. else
  410. {
  411. if((balance < MA && useMovingAVG) || !(useMovingAVG))
  412. {
  413. double sell_SL = SymbolInfoDouble(Symbol(),SYMBOL_BID) + glSl * 10 * SymbolInfoDouble(_Symbol, SYMBOL_POINT);
  414. double Sell_TP = SymbolInfoDouble(Symbol(),SYMBOL_BID) - glTp * 10 * SymbolInfoDouble(_Symbol, SYMBOL_POINT);
  415. if(!trade.Sell(lot,Symbol(),SymbolInfoDouble(Symbol(),SYMBOL_BID),sell_SL,Sell_TP,"Sell Trade"))
  416. {
  417. Print(" Error in Placing Sell Trade : ",GetLastError());
  418. }
  419. else
  420. {
  421. tradeSyncAddToStruct(k,trade.ResultOrder());
  422. }
  423. }
  424. else
  425. {
  426. Print(" Trade is not Placed because Balance is less than MA Value ");
  427. }
  428. }
  429. }
  430. }
  431. prevOrderCount = count;
  432. }
  433. }
  434. }
  435. }
  436. }
  437. }
  438. //+------------------------------------------------------------------+
  439. //| |
  440. //+------------------------------------------------------------------+
  441. void placeSellTrade()
  442. {
  443. double sellSl = 0, sellTp = 0;
  444. double Bid = SymbolInfoDouble(Symbol(),SYMBOL_BID);
  445. if(slPips != 0)
  446. {
  447. sellSl = Bid + (slPips * 10 * Point());
  448. }
  449. if(tpPips != 0)
  450. {
  451. sellTp = Bid - (tpPips * 10 * Point());
  452. }
  453. if(eaType == Tally_Sim)
  454. {
  455. AddToStructure(ticketAssigner,1,magicNo,Bid,0,TimeCurrent(),0,sellSl,sellTp,lot,0);
  456. ticketAssigner++;
  457. }
  458. else
  459. {
  460. int count = orderCount();
  461. if(prevOrderCount != count && count != -1)
  462. {
  463. for(int k = prevOrderCount + 1;k <= count;k++)
  464. {
  465. getTicketByNumber(k,sellSl,sellTp);
  466. if(getTicketByNumber(k,sellSl,sellTp) != -1)
  467. {
  468. if(enableTradingDaily == true)
  469. {
  470. if(eaType == Tally_Trade && CopyTallyTrade)
  471. {
  472. if(CopyBuffer(handler, 0, 0, 4, bufferData) < 0)
  473. {
  474. Print("Error in copying Buffer data ", GetLastError());
  475. }
  476. double balance = bufferData[1];
  477. if(CopyBuffer(handler, 1, 0, 4, bufferData) < 0)
  478. {
  479. Print("Error in copying Buffer data ", GetLastError());
  480. }
  481. double MA = bufferData[1];
  482. Print(" Balance = ",balance," MA = ",MA);
  483. if(tradesDirection == reverse)
  484. {
  485. if(balance < MA)
  486. {
  487. if(!trade.Sell(lot,Symbol(),Bid,sellSl,sellTp,"Sell Trade"))
  488. {
  489. Print(" Error in Placing Sell Trade : ",GetLastError());
  490. }
  491. }
  492. else
  493. {
  494. Print(" Trade is not Placed because Balance is less than MA Value ");
  495. }
  496. }
  497. else
  498. {
  499. if(balance > MA)
  500. {
  501. if(!trade.Buy(lot,Symbol(),SymbolInfoDouble(Symbol(),SYMBOL_ASK),sellTp,sellSl,"Buy Trade"))
  502. {
  503. Print(" Error in Placing Buy Trade : ",GetLastError());
  504. }
  505. }
  506. else
  507. {
  508. Print(" Trade is not Placed because Balance is less than MA Value ");
  509. }
  510. }
  511. }
  512. }
  513. prevOrderCount = count;
  514. }
  515. }
  516. }
  517. }
  518. }
  519. //+------------------------------------------------------------------+
  520. //| |
  521. //+------------------------------------------------------------------+
  522. void AddToStructure(int ticket, int type, int magic, double open_price,
  523. double close_price, datetime open_time, datetime close_time,
  524. double sl, double tp, double lotSize, double profit)
  525. {
  526. if(GlobalVariableGet(global) == 0)
  527. {
  528. for(int i = 0; i < MaxOrders; i++)
  529. {
  530. if(od[i].trade_ticket == -1)
  531. {
  532. od[i].trade_ticket = ticket;
  533. od[i].trade_type = type;
  534. od[i].trade_magic_no = magic;
  535. od[i].trade_open_price = open_price;
  536. od[i].trade_close_price = close_price;
  537. od[i].trade_open_time = open_time;
  538. od[i].trade_close_time = close_time;
  539. od[i].trade_sl = sl;
  540. od[i].trade_tp = tp;
  541. od[i].trade_lot = lotSize;
  542. od[i].trade_profit = profit;
  543. Print(" ========== Trade Placed of Ticket ========== ",ticket);
  544. Print("[AddToStructure] Added at index: ", i,
  545. " | Ticket = ", ticket,
  546. " | Type = ", type,
  547. " | Magic = ", magic,
  548. " | OpenPrice = ", open_price,
  549. " | ClosePrice = ", close_price,
  550. " | SL = ", sl,
  551. " | TP = ", tp,
  552. " | Lots = ", lotSize,
  553. " | Profit = ", profit);
  554. string line = MakeTradeString(
  555. od[i].trade_ticket,
  556. od[i].trade_type,
  557. od[i].trade_magic_no,
  558. od[i].trade_open_price,
  559. od[i].trade_close_price,
  560. od[i].trade_open_time,
  561. od[i].trade_close_time,
  562. od[i].trade_sl,
  563. od[i].trade_tp,
  564. od[i].trade_lot,
  565. od[i].trade_profit
  566. );
  567. writeDatainFile(line);
  568. break;
  569. }
  570. }
  571. }
  572. }
  573. //+------------------------------------------------------------------+
  574. //| |
  575. //+------------------------------------------------------------------+
  576. void writeAllDataToFile()
  577. {
  578. for(int i = 0; i < MaxOrders; i++)
  579. {
  580. if(od[i].trade_ticket != -1)
  581. {
  582. string line = MakeTradeString(
  583. od[i].trade_ticket,
  584. od[i].trade_type,
  585. od[i].trade_magic_no,
  586. od[i].trade_open_price,
  587. od[i].trade_close_price,
  588. od[i].trade_open_time,
  589. od[i].trade_close_time,
  590. od[i].trade_sl,
  591. od[i].trade_tp,
  592. od[i].trade_lot,
  593. od[i].trade_profit
  594. );
  595. if(GlobalVariableGet(global) == 0)
  596. {
  597. int filehandle = FileOpen(filename,FILE_WRITE|FILE_CSV|FILE_COMMON,",");
  598. if(filehandle != INVALID_HANDLE)
  599. {
  600. GlobalVariableSet(global,1);
  601. FileWrite(filehandle,line);
  602. Print(line);
  603. FileClose(filehandle);
  604. GlobalVariableSet(global,0);
  605. }
  606. }
  607. }
  608. }
  609. }
  610. //+------------------------------------------------------------------+
  611. //| |
  612. //+------------------------------------------------------------------+
  613. void tradeSyncAddToStruct(ulong sim_ticket,ulong live_ticket)
  614. {
  615. for(int i = 0; i < MaxOrders; i++)
  616. {
  617. if(od_sync[i].sim_trade_ticket == -1)
  618. {
  619. od_sync[i].sim_trade_ticket = sim_ticket;
  620. od_sync[i].live_trade_ticket = live_ticket;
  621. Print(" == Sim Ticket = ",sim_ticket," Live Ticket = ",live_ticket," Is Added to Structure === ");
  622. break;
  623. }
  624. }
  625. }
  626. //+------------------------------------------------------------------+
  627. //| |
  628. //+------------------------------------------------------------------+
  629. void checkTPSLHit()
  630. {
  631. if(GlobalVariableGet(global) == 0)
  632. {
  633. double bid = SymbolInfoDouble(_Symbol, SYMBOL_BID);
  634. double ask = SymbolInfoDouble(_Symbol, SYMBOL_ASK);
  635. for(int i = 0; i < MaxOrders; i++)
  636. {
  637. if(od[i].trade_ticket != -1 && od[i].trade_close_price == 0)
  638. {
  639. int ticket = od[i].trade_ticket;
  640. int type = od[i].trade_type;
  641. double sl = od[i].trade_sl;
  642. double tp = od[i].trade_tp;
  643. double closePrice = 0;
  644. // ----------------------------------------------
  645. // BUY ORDER CHECK
  646. // ----------------------------------------------
  647. if(type == 0)
  648. {
  649. // TP hit → Bid >= TP
  650. if(bid >= tp && tp > 0)
  651. {
  652. closePrice = bid;
  653. Print(" ======== Buy Trade TP Hit ======= ",ticket);
  654. }
  655. // SL hit → Bid <= SL
  656. if(bid <= sl && sl > 0)
  657. {
  658. closePrice = bid;
  659. Print(" ======== Buy Trade SL Hit ======= ",ticket);
  660. }
  661. }
  662. // ----------------------------------------------
  663. // SELL ORDER CHECK
  664. // ----------------------------------------------
  665. if(type == 1)
  666. {
  667. // TP hit → Ask <= TP (price goes DOWN)
  668. if(ask <= tp && tp > 0)
  669. {
  670. closePrice = ask;
  671. Print(" ======== Sell Trade TP Hit ======= ",ticket);
  672. }
  673. // SL hit → Ask >= SL
  674. if(ask >= sl && sl > 0)
  675. {
  676. closePrice = ask;
  677. Print(" ======== Sell Trade SL Hit ======= ",ticket);
  678. }
  679. }
  680. // ----------------------------------------------
  681. // IF ANYTHING TRIGGERED → CLOSE TRADE
  682. // ----------------------------------------------
  683. if(closePrice > 0)
  684. {
  685. od[i].trade_close_price = closePrice;
  686. od[i].trade_close_time = TimeCurrent();
  687. 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();
  688. od[i].trade_profit += tpinDollar(od[i].trade_lot, tpdifference);
  689. Print("======= TRADE CLOSED of ticket =======",ticket);
  690. Print("Index: ", i,
  691. " | Ticket: ", ticket,
  692. " | Type: ", type,
  693. " | ClosePrice: ", closePrice,
  694. " | Time: ", od[i].trade_close_time,
  695. " | Profit: ", od[i].trade_profit);
  696. DrawVirtualBuyClose(closePrice);
  697. datetime t1 = od[i].trade_open_time;
  698. double price1 = od[i].trade_open_price;
  699. datetime t2 = od[i].trade_close_time;
  700. double price2 = od[i].trade_close_price;
  701. // DrawDottedTrendline("Ticket "+string(ticket), t1, price1, t2, price2, clrGreen);
  702. tpSlHit = false; // make these zero so new trade place's
  703. datetime openTime = od[i].trade_open_time;
  704. double openPrice = od[i].trade_open_price;
  705. datetime closeTime = od[i].trade_close_time;
  706. double closePrice = od[i].trade_close_price;
  707. long dealType = od[i].trade_type;
  708. string lineName = "TradeLine_" + (string)od[i].trade_ticket;
  709. createTrendLine(lineName, openTime, openPrice, closeTime, closePrice, dealType, od[i].trade_profit);
  710. PrintFormat("Trend line created for closed trade #%I64u | Profit: %.2f", od[i].trade_ticket, od[i].trade_profit);
  711. // string line = MakeTradeString(
  712. // od[i].trade_ticket,
  713. // od[i].trade_type,
  714. // od[i].trade_magic_no,
  715. // od[i].trade_open_price,
  716. // od[i].trade_close_price,
  717. // od[i].trade_open_time,
  718. // od[i].trade_close_time,
  719. // od[i].trade_sl,
  720. // od[i].trade_tp,
  721. // od[i].trade_lot,
  722. // od[i].trade_profit
  723. // );
  724. //
  725. // writeDatainFile(line);
  726. writeAllDataToFile();
  727. }
  728. }
  729. }
  730. }
  731. }
  732. //+------------------------------------------------------------------+
  733. //| |
  734. //+------------------------------------------------------------------+
  735. void closeAllVirtualTrades()
  736. {
  737. if(GlobalVariableGet(global) == 0)
  738. {
  739. double bid = SymbolInfoDouble(_Symbol, SYMBOL_BID);
  740. double ask = SymbolInfoDouble(_Symbol, SYMBOL_ASK);
  741. for(int i = 0; i < MaxOrders; i++)
  742. {
  743. if(od[i].trade_ticket != -1 && od[i].trade_close_price == 0)
  744. {
  745. int ticket = od[i].trade_ticket;
  746. int type = od[i].trade_type;
  747. double sl = od[i].trade_sl;
  748. double tp = od[i].trade_tp;
  749. double closePrice = 0;
  750. // ----------------------------------------------
  751. // BUY ORDER CHECK
  752. // ----------------------------------------------
  753. if(type == 0)
  754. {
  755. closePrice = bid;
  756. Print(" ======== Buy Trade Closed By close all virtual Trades ======= ",ticket);
  757. }
  758. // ----------------------------------------------
  759. // SELL ORDER CHECK
  760. // ----------------------------------------------
  761. if(type == 1)
  762. {
  763. closePrice = ask;
  764. Print(" ======== Sell Trade Closed By close all virtual Trades ======= ",ticket);
  765. }
  766. // ----------------------------------------------
  767. // IF ANYTHING TRIGGERED → CLOSE TRADE
  768. // ----------------------------------------------
  769. if(closePrice > 0)
  770. {
  771. od[i].trade_close_price = closePrice;
  772. od[i].trade_close_time = TimeCurrent();
  773. 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();
  774. od[i].trade_profit += tpinDollar(od[i].trade_lot, tpdifference);
  775. Print("======= TRADE CLOSED of ticket =======",ticket);
  776. Print("Index: ", i,
  777. " | Ticket: ", ticket,
  778. " | Type: ", type,
  779. " | ClosePrice: ", closePrice,
  780. " | Time: ", od[i].trade_close_time,
  781. " | Profit: ", od[i].trade_profit);
  782. DrawVirtualBuyClose(closePrice);
  783. datetime t1 = od[i].trade_open_time;
  784. double price1 = od[i].trade_open_price;
  785. datetime t2 = od[i].trade_close_time;
  786. double price2 = od[i].trade_close_price;
  787. DrawDottedTrendline("Ticket "+string(ticket), t1, price1, t2, price2, clrGreen);
  788. tpSlHit = false; // make these zero so new trade place's
  789. writeAllDataToFile();
  790. }
  791. }
  792. }
  793. }
  794. }
  795. //+------------------------------------------------------------------+
  796. //| |
  797. //+------------------------------------------------------------------+
  798. double tpinDollar(double lotSize, double distance)
  799. {
  800. double pipvalue = NormalizeDouble(((SymbolInfoDouble(Symbol(),SYMBOL_TRADE_TICK_VALUE)/(SymbolInfoDouble(Symbol(),SYMBOL_TRADE_TICK_SIZE)/Point()))*10),2);
  801. pipvalue = pipvalue / 10;
  802. double dollar = lotSize * distance * pipvalue;
  803. return NormalizeDouble(dollar,2);
  804. }
  805. //+------------------------------------------------------------------+
  806. //| |
  807. //+------------------------------------------------------------------+
  808. bool writeDatainFile(string str)
  809. {
  810. if(GlobalVariableGet(global) == 0)
  811. {
  812. int filehandle = FileOpen(filename,FILE_WRITE|FILE_CSV|FILE_COMMON|FILE_END,",");
  813. if(filehandle != INVALID_HANDLE)
  814. {
  815. GlobalVariableSet(global,1);
  816. FileSeek(filehandle, 0, SEEK_END);
  817. FileWrite(filehandle,str);
  818. Print(str);
  819. FileClose(filehandle);
  820. GlobalVariableSet(global,0);
  821. return true;
  822. }
  823. }
  824. return false;
  825. }
  826. //+------------------------------------------------------------------+
  827. //| |
  828. //+------------------------------------------------------------------+
  829. string MakeTradeString(int ticket, int type, int magic,
  830. double open_price, double close_price,
  831. datetime open_time, datetime close_time,
  832. double sl, double tp, double lotSize, double profit)
  833. {
  834. string str = StringFormat("%d,%d,%d,%.5f,%.5f,%s,%s,%.5f,%.5f,%.2f,%.2f",
  835. ticket,
  836. type,
  837. magic,
  838. open_price,
  839. close_price,
  840. TimeToString(open_time, TIME_DATE|TIME_SECONDS),
  841. TimeToString(close_time, TIME_DATE|TIME_SECONDS),
  842. sl,
  843. tp,
  844. lotSize,
  845. profit);
  846. return str;
  847. }
  848. //+------------------------------------------------------------------+
  849. //| |
  850. //+------------------------------------------------------------------+
  851. void setStart_EndTime(bool onInit,string start,string end,datetime & sessionStart,datetime & sessionEnd)
  852. {
  853. int newYorkStartHour = 0, newYorkStartMin = 0, newYorkEndHour = 0, newYorkEndMin = 0;
  854. datetime newYorkStartTrading,newYorkEndTrading;
  855. string time[];
  856. StringSplit(start,':',time);
  857. newYorkStartHour = (int)StringToInteger(time[0]);
  858. newYorkStartMin = (int)StringToInteger(time[1]);
  859. EventSetMillisecondTimer(500);
  860. time[0] = "";
  861. time[1] = "";
  862. StringSplit(end,':',time);
  863. newYorkEndHour = (int)StringToInteger(time[0]);
  864. newYorkEndMin = (int)StringToInteger(time[1]);
  865. // Print(" Start Time Hour: ",newYorkStartHour," Start Time Min: ",newYorkStartMin);
  866. // Print(" End Time Hour: ",newYorkEndHour," End Time Min: ",newYorkEndMin);
  867. datetime startDateTime;
  868. MqlDateTime st;
  869. TimeCurrent(st); // get current date
  870. st.hour = newYorkStartHour;
  871. st.min = newYorkStartMin;
  872. st.sec = 0;
  873. startDateTime = StructToTime(st);
  874. datetime endDateTime;
  875. MqlDateTime et;
  876. TimeCurrent(et); // get current date
  877. et.hour = newYorkEndHour;
  878. et.min = newYorkEndMin;
  879. et.sec = 0;
  880. endDateTime = StructToTime(et);
  881. MqlDateTime sdate,edate;
  882. datetime start_Time = 0, end_Time = 0;
  883. if(startDateTime > endDateTime)
  884. {
  885. if(onInit)
  886. {
  887. start_Time = iTime(Symbol(),PERIOD_D1,1);
  888. end_Time = iTime(Symbol(),PERIOD_D1,0);
  889. }
  890. else
  891. {
  892. start_Time = sessionStart;
  893. end_Time = sessionEnd;
  894. if(TimeCurrent() >= sessionEnd && sessionEnd != 0)
  895. {
  896. start_Time = iTime(Symbol(),PERIOD_D1,0);
  897. end_Time = start_Time + 86400;
  898. }
  899. }
  900. }
  901. else
  902. {
  903. start_Time = iTime(Symbol(),PERIOD_D1,0);
  904. end_Time = iTime(Symbol(),PERIOD_D1,0);
  905. }
  906. if(TimeToStruct(end_Time,edate))
  907. {
  908. edate.hour = newYorkEndHour;
  909. edate.min = newYorkEndMin;
  910. edate.sec = 0;
  911. }
  912. else
  913. Print("Error in Converting Time: ",GetLastError());
  914. newYorkEndTrading = StructToTime(edate);
  915. if(TimeToStruct(start_Time,sdate))
  916. {
  917. sdate.hour = newYorkStartHour;
  918. sdate.min = newYorkStartMin;
  919. sdate.sec = 0;
  920. }
  921. else
  922. Print("Error in Converting Time: ",GetLastError());
  923. newYorkStartTrading = StructToTime(sdate);
  924. sessionStart = newYorkStartTrading;
  925. sessionEnd = newYorkEndTrading;
  926. }
  927. //+------------------------------------------------------------------+
  928. //| |
  929. //+------------------------------------------------------------------+
  930. void setStart_EndTime_modify(bool onInit,string start,string end,datetime & sessionStart,datetime & sessionEnd)
  931. {
  932. int newYorkStartHour = 0, newYorkStartMin = 0, newYorkEndHour = 0, newYorkEndMin = 0;
  933. datetime newYorkStartTrading,newYorkEndTrading;
  934. string time[];
  935. StringSplit(start,':',time);
  936. newYorkStartHour = (int)StringToInteger(time[0]);
  937. newYorkStartMin = (int)StringToInteger(time[1]);
  938. time[0] = "";
  939. time[1] = "";
  940. StringSplit(end,':',time);
  941. newYorkEndHour = (int)StringToInteger(time[0]);
  942. newYorkEndMin = (int)StringToInteger(time[1]);
  943. // Print(" Start Time Hour: ",newYorkStartHour," Start Time Min: ",newYorkStartMin);
  944. // Print(" End Time Hour: ",newYorkEndHour," End Time Min: ",newYorkEndMin);
  945. datetime startDateTime;
  946. MqlDateTime st;
  947. TimeCurrent(st); // get current date
  948. st.hour = newYorkStartHour;
  949. st.min = newYorkStartMin;
  950. st.sec = 0;
  951. startDateTime = StructToTime(st);
  952. datetime endDateTime;
  953. MqlDateTime et;
  954. TimeCurrent(et); // get current date
  955. et.hour = newYorkEndHour;
  956. et.min = newYorkEndMin;
  957. et.sec = 0;
  958. endDateTime = StructToTime(et);
  959. MqlDateTime sdate,edate;
  960. datetime start_Time = 0, end_Time = 0;
  961. if(startDateTime > endDateTime)
  962. {
  963. start_Time = iTime(Symbol(),PERIOD_D1,1);
  964. end_Time = iTime(Symbol(),PERIOD_D1,0);
  965. }
  966. else
  967. {
  968. start_Time = iTime(Symbol(),PERIOD_D1,0);
  969. end_Time = iTime(Symbol(),PERIOD_D1,0);
  970. }
  971. if(TimeToStruct(end_Time,edate))
  972. {
  973. edate.hour = newYorkEndHour;
  974. edate.min = newYorkEndMin;
  975. edate.sec = 0;
  976. }
  977. else
  978. Print("Error in Converting Time: ",GetLastError());
  979. newYorkEndTrading = StructToTime(edate);
  980. if(TimeToStruct(start_Time,sdate))
  981. {
  982. sdate.hour = newYorkStartHour;
  983. sdate.min = newYorkStartMin;
  984. sdate.sec = 0;
  985. }
  986. else
  987. Print("Error in Converting Time: ",GetLastError());
  988. newYorkStartTrading = StructToTime(sdate);
  989. sessionStart = newYorkStartTrading;
  990. sessionEnd = newYorkEndTrading;
  991. }
  992. //+------------------------------------------------------------------+
  993. //| Check Virtual TP/SL for all positions |
  994. //+------------------------------------------------------------------+
  995. //void CheckVirtualGlobalTpSl()
  996. // {
  997. //
  998. // double bid = SymbolInfoDouble(_Symbol, SYMBOL_BID);
  999. // double ask = SymbolInfoDouble(_Symbol, SYMBOL_ASK);
  1000. //
  1001. // for(int i=PositionsTotal()-1; i >=0 ; i--)
  1002. // {
  1003. // ulong ticket = PositionGetTicket(i);
  1004. // if(PositionSelectByTicket(ticket))
  1005. // {
  1006. // if(PositionGetInteger(POSITION_MAGIC) == magicNo &&
  1007. // PositionGetString(POSITION_SYMBOL) == _Symbol)
  1008. // {
  1009. // if(PositionGetInteger(POSITION_TYPE) == POSITION_TYPE_BUY)
  1010. // {
  1011. // double tp_price = PositionGetDouble(POSITION_PRICE_OPEN) + glTp * 10 * SymbolInfoDouble(_Symbol, SYMBOL_POINT);
  1012. // double sl_price = PositionGetDouble(POSITION_PRICE_OPEN) - glSl * 10 * SymbolInfoDouble(_Symbol, SYMBOL_POINT);
  1013. //
  1014. // if(bid >= tp_price || bid <= sl_price)
  1015. // {
  1016. // closeAllActiveOrders();
  1017. // return;
  1018. // }
  1019. // }
  1020. // if(PositionGetInteger(POSITION_TYPE) == POSITION_TYPE_SELL)
  1021. // {
  1022. // double tp_price = PositionGetDouble(POSITION_PRICE_OPEN) - glTp * 10 * SymbolInfoDouble(_Symbol, SYMBOL_POINT);
  1023. // double sl_price = PositionGetDouble(POSITION_PRICE_OPEN) + glSl * 10 * SymbolInfoDouble(_Symbol, SYMBOL_POINT);
  1024. //
  1025. // if(ask <= tp_price || ask >= sl_price)
  1026. // {
  1027. // closeAllActiveOrders();
  1028. // return;
  1029. // }
  1030. // }
  1031. // }
  1032. // }
  1033. // }
  1034. // }
  1035. //+------------------------------------------------------------------+
  1036. //| |
  1037. //+------------------------------------------------------------------+
  1038. void CheckDailyDrawdown()
  1039. {
  1040. if(!UseDailyDrawdownLimit)
  1041. return;
  1042. double equity = AccountInfoDouble(ACCOUNT_EQUITY);
  1043. double drawdown = g_dailyStartBalance - equity;
  1044. if(drawdown >= DailyDrawdownAmount)
  1045. {
  1046. enableTradingDaily = false;
  1047. Print("Daily Drawdown Limit Hit: ", drawdown, " >= ", DailyDrawdownAmount);
  1048. closeAllActiveOrders();
  1049. closeAllVirtualTrades();
  1050. }
  1051. }
  1052. //+------------------------------------------------------------------+
  1053. //| |
  1054. //+------------------------------------------------------------------+
  1055. void markClosedOrder(datetime eaTime)
  1056. {
  1057. HistorySelect(eaTime, TimeCurrent());
  1058. for(int i = HistoryDealsTotal() - 1; i >= 0; i--)
  1059. {
  1060. ulong dealTicket = HistoryDealGetTicket(i);
  1061. long dealMagic = HistoryDealGetInteger(dealTicket, DEAL_MAGIC);
  1062. if(dealMagic != magicNo && dealMagic != 0)
  1063. continue;
  1064. if(HistoryDealGetString(dealTicket, DEAL_SYMBOL) == Symbol())
  1065. {
  1066. //Print("Condition 2 ",HistoryDealGetInteger(dealTicket, DEAL_ENTRY)," HistoryDealsTotal(): ",HistoryDealsTotal());
  1067. if(HistoryDealGetInteger(dealTicket, DEAL_ENTRY) == DEAL_ENTRY_OUT)
  1068. {
  1069. //Print("deal out close: ",dealTicket);
  1070. long dealType = HistoryDealGetInteger(dealTicket, DEAL_TYPE);
  1071. if(dealType != DEAL_TYPE_BUY && dealType != DEAL_TYPE_SELL)
  1072. continue;
  1073. double profit = HistoryDealGetDouble(dealTicket, DEAL_PROFIT);
  1074. profit = NormalizeDouble(profit, 2);
  1075. string lineName = "TradeLine_" + (string)dealTicket;
  1076. if(ObjectFind(0, lineName) >= 0)
  1077. continue;
  1078. ulong entryDeal = findEntryDeal(dealTicket);
  1079. if(entryDeal == 0)
  1080. continue;
  1081. datetime openTime = (datetime)HistoryDealGetInteger(entryDeal, DEAL_TIME);
  1082. double openPrice = HistoryDealGetDouble(entryDeal, DEAL_PRICE);
  1083. datetime closeTime = (datetime)HistoryDealGetInteger(dealTicket, DEAL_TIME);
  1084. double closePrice = HistoryDealGetDouble(dealTicket, DEAL_PRICE);
  1085. createTrendLine(lineName, openTime, openPrice, closeTime, closePrice, dealType, profit);
  1086. PrintFormat("Trend line created for closed trade #%I64u | Profit: %.2f", dealTicket, profit);
  1087. }
  1088. }
  1089. }
  1090. }
  1091. //+------------------------------------------------------------------+
  1092. //| |
  1093. //+------------------------------------------------------------------+
  1094. void createTrendLine(string name,
  1095. datetime openTime, double openPrice,
  1096. datetime closeTime, double closePrice,
  1097. long dealType, double profit)
  1098. {
  1099. if(ObjectFind(0, name) >= 0)
  1100. return;
  1101. if(!ObjectCreate(0, name, OBJ_TREND, 0, openTime, openPrice, closeTime, closePrice))
  1102. {
  1103. Print("Error creating trend line: ", GetLastError());
  1104. return;
  1105. }
  1106. ObjectSetInteger(0, name, OBJPROP_WIDTH, tradeLineThickness);
  1107. ObjectSetInteger(0, name, OBJPROP_STYLE, STYLE_SOLID);
  1108. ObjectSetInteger(0, name, OBJPROP_RAY, false);
  1109. color lineColor = (dealType == DEAL_TYPE_BUY) ? clrRed : clrBlue;
  1110. ObjectSetInteger(0, name, OBJPROP_COLOR, lineColor);
  1111. createProfitLabel(name + "_label", openTime, openPrice, closeTime, closePrice, dealType, profit);
  1112. }
  1113. //+------------------------------------------------------------------+
  1114. //| |
  1115. //+------------------------------------------------------------------+
  1116. void createProfitLabel(string name,
  1117. datetime openTime, double openPrice,
  1118. datetime closeTime, double closePrice,
  1119. long dealType, double profit)
  1120. {
  1121. if(ObjectFind(0, name) >= 0)
  1122. return;
  1123. datetime middleTime = openTime + (closeTime - openTime) / 2;
  1124. double midPrice = (openPrice + closePrice) / 2;
  1125. if(!ObjectCreate(0, name, OBJ_TEXT, 0, middleTime, midPrice))
  1126. {
  1127. Print("Error creating profit label: ", GetLastError());
  1128. return;
  1129. }
  1130. string profitText = "$" + DoubleToString(profit, 2);
  1131. ObjectSetString(0, name, OBJPROP_TEXT, profitText);
  1132. ObjectSetInteger(0, name, OBJPROP_FONTSIZE, dollarFontSize);
  1133. ObjectSetInteger(0, name, OBJPROP_COLOR, dollarFontColor);
  1134. ObjectSetInteger(0, name, OBJPROP_ANCHOR, ANCHOR_TOP);
  1135. ObjectSetInteger(0, name, OBJPROP_SELECTABLE, false);
  1136. }
  1137. //+------------------------------------------------------------------+
  1138. //| |
  1139. //+------------------------------------------------------------------+
  1140. ulong findEntryDeal(ulong closeDeal)
  1141. {
  1142. string symbol = HistoryDealGetString(closeDeal, DEAL_SYMBOL);
  1143. long positionID = HistoryDealGetInteger(closeDeal, DEAL_POSITION_ID);
  1144. int dealOutCount = 0;
  1145. for(int i = HistoryDealsTotal() - 1; i >= 0; i--)
  1146. {
  1147. ulong deal = HistoryDealGetTicket(i);
  1148. if(HistoryDealGetInteger(deal, DEAL_POSITION_ID) == positionID)
  1149. {
  1150. if(HistoryDealGetInteger(deal, DEAL_ENTRY) == DEAL_ENTRY_OUT)
  1151. {
  1152. dealOutCount++;
  1153. }
  1154. }
  1155. }
  1156. if(dealOutCount < 2)
  1157. {
  1158. for(int i = HistoryDealsTotal() - 1; i >= 0; i--)
  1159. {
  1160. ulong deal = HistoryDealGetTicket(i);
  1161. if(HistoryDealGetInteger(deal, DEAL_POSITION_ID) == positionID &&
  1162. HistoryDealGetInteger(deal, DEAL_ENTRY) == DEAL_ENTRY_IN &&
  1163. HistoryDealGetString(deal, DEAL_SYMBOL) == symbol)
  1164. return deal;
  1165. //Print("Deal: ", deal);
  1166. }
  1167. }
  1168. else
  1169. {
  1170. for(int i = 0; i < HistoryDealsTotal(); i++)
  1171. {
  1172. ulong deal = HistoryDealGetTicket(i);
  1173. if(HistoryDealGetInteger(deal, DEAL_POSITION_ID) == positionID &&
  1174. HistoryDealGetInteger(deal, DEAL_ENTRY) == DEAL_ENTRY_OUT)
  1175. {
  1176. return deal;
  1177. }
  1178. //Print("Deal: ", deal);
  1179. }
  1180. }
  1181. return 0;
  1182. }
  1183. //+------------------------------------------------------------------+
  1184. //| |
  1185. //+------------------------------------------------------------------+
  1186. void DrawArrow(string name, datetime time, double price, color clr, int arrow)
  1187. {
  1188. if(ObjectFind(0, name) == -1)
  1189. {
  1190. ObjectCreate(0, name, OBJ_ARROW, 0, time, price);
  1191. ObjectSetInteger(0, name, OBJPROP_COLOR, clr);
  1192. ObjectSetInteger(0, name, OBJPROP_WIDTH, 1);
  1193. ObjectSetInteger(0, name, OBJPROP_ARROWCODE, arrow);
  1194. }
  1195. }
  1196. //+------------------------------------------------------------------+
  1197. //| |
  1198. //+------------------------------------------------------------------+
  1199. void DrawVirtualBuyOpen(double openPrice)
  1200. {
  1201. datetime t = TimeCurrent();
  1202. string name = "VBUY_OPEN_" + IntegerToString(t);
  1203. // DrawArrow(name, t, openPrice, clrLime, 233);
  1204. ObjectCreate(0,name,OBJ_ARROW_BUY,0,TimeCurrent(),openPrice);
  1205. }
  1206. //+------------------------------------------------------------------+
  1207. //| |
  1208. //+------------------------------------------------------------------+
  1209. void DrawVirtualBuyClose(double closePrice)
  1210. {
  1211. datetime t = TimeCurrent();
  1212. string name = "VBUY_CLOSE_" + IntegerToString(t);
  1213. // DrawArrow(name, t, closePrice, clrRed, 234);
  1214. ObjectCreate(0,name,OBJ_ARROW_SELL,0,TimeCurrent(),closePrice);
  1215. }
  1216. //+------------------------------------------------------------------+
  1217. //| |
  1218. //+------------------------------------------------------------------+
  1219. void DrawDottedTrendline(string name, datetime time1, double price1, datetime time2, double price2, color clr)
  1220. {
  1221. // Delete if already exists
  1222. if(ObjectFind(0, name) != -1)
  1223. ObjectDelete(0, name);
  1224. // Create the trendline
  1225. if(!ObjectCreate(0, name, OBJ_TREND, 0, time1, price1, time2, price2))
  1226. Print("Error creating trendline: ", GetLastError());
  1227. // Set properties
  1228. ObjectSetInteger(0, name, OBJPROP_COLOR, clr);
  1229. ObjectSetInteger(0, name, OBJPROP_STYLE, STYLE_DOT); // Dotted line
  1230. ObjectSetInteger(0, name, OBJPROP_WIDTH, 1); // Line width
  1231. }
  1232. //+------------------------------------------------------------------+
  1233. //| |
  1234. //+------------------------------------------------------------------+
  1235. int orderCount()
  1236. {
  1237. int index = 0;
  1238. if(GlobalVariableGet(global) == 0)
  1239. {
  1240. GlobalVariableSet(global,1);
  1241. int handle = FileOpen(filename, FILE_READ | FILE_COMMON);
  1242. if(handle == INVALID_HANDLE)
  1243. {
  1244. Print("EA=> Handler invalid: orderCount() ", filename," ",GetLastError()," eaType: ",eaType);
  1245. return -1;
  1246. }
  1247. while(!FileIsEnding(handle))
  1248. {
  1249. string line = FileReadString(handle);
  1250. string parts[];
  1251. int count = StringSplit(line, ',', parts);
  1252. int ticket = (int)StringToInteger(parts[0]);
  1253. int type = (int)StringToInteger(parts[1]);
  1254. int magic = (int)StringToInteger(parts[2]);
  1255. double open_price = StringToDouble(parts[3]);
  1256. double close_price = StringToDouble(parts[4]);
  1257. datetime open_time = StringToTime(parts[5]);
  1258. datetime close_time = StringToTime(parts[6]);
  1259. double sl = StringToDouble(parts[7]);
  1260. double tp = StringToDouble(parts[8]);
  1261. double lotS = StringToDouble(parts[9]);
  1262. double profit = StringToDouble(parts[10]);
  1263. index++;
  1264. }
  1265. FileClose(handle);
  1266. GlobalVariableSet(global,0);
  1267. }
  1268. return index;
  1269. }
  1270. //+------------------------------------------------------------------+
  1271. //| |
  1272. //+------------------------------------------------------------------+
  1273. int getTicketByNumber(int id,double & buySl,double & buyTp)
  1274. {
  1275. int index = -1;
  1276. if(GlobalVariableGet(global) == 0)
  1277. {
  1278. GlobalVariableSet(global,1);
  1279. int handle = FileOpen(filename, FILE_READ | FILE_COMMON);
  1280. if(handle == INVALID_HANDLE)
  1281. {
  1282. Print("EA=> Handler invalid: getTicketByNumber() ", filename," error: ",GetLastError()," eaType: ",eaType);
  1283. return 0;
  1284. }
  1285. while(!FileIsEnding(handle))
  1286. {
  1287. string line = FileReadString(handle);
  1288. // Skip empty line
  1289. if(StringLen(line) < 2)
  1290. continue;
  1291. string parts[];
  1292. int count = StringSplit(line, ',', parts);
  1293. int ticket = (int)StringToInteger(parts[0]);
  1294. int type = (int)StringToInteger(parts[1]);
  1295. int magic = (int)StringToInteger(parts[2]);
  1296. double open_price = StringToDouble(parts[3]);
  1297. double close_price = StringToDouble(parts[4]);
  1298. datetime open_time = StringToTime(parts[5]);
  1299. datetime close_time = StringToTime(parts[6]);
  1300. double sl = StringToDouble(parts[7]);
  1301. double tp = StringToDouble(parts[8]);
  1302. double lotS = StringToDouble(parts[9]);
  1303. double profit = StringToDouble(parts[10]);
  1304. if(id == ticket)
  1305. {
  1306. buySl = sl;
  1307. buyTp = tp;
  1308. index = id;
  1309. }
  1310. }
  1311. FileClose(handle);
  1312. GlobalVariableSet(global,0);
  1313. }
  1314. return index;
  1315. }
  1316. //+------------------------------------------------------------------+
  1317. //| |
  1318. //+------------------------------------------------------------------+
  1319. void checkVirtualTicketClosed() // check if virtual trade closed so close Active Trade as well
  1320. {
  1321. if(GlobalVariableGet(global) == 0)
  1322. {
  1323. GlobalVariableSet(global,1);
  1324. int handle = FileOpen(filename, FILE_READ | FILE_COMMON);
  1325. if(handle == INVALID_HANDLE)
  1326. {
  1327. Print("EA=> Handler invalid: checkVirtualTicketClosed() ", filename," error: ",GetLastError()," eaType: ",eaType);
  1328. return;
  1329. }
  1330. while(!FileIsEnding(handle))
  1331. {
  1332. string line = FileReadString(handle);
  1333. string parts[];
  1334. int count = StringSplit(line, ',', parts);
  1335. int ticket = (int)StringToInteger(parts[0]);
  1336. int type = (int)StringToInteger(parts[1]);
  1337. int magic = (int)StringToInteger(parts[2]);
  1338. double open_price = StringToDouble(parts[3]);
  1339. double close_price = StringToDouble(parts[4]);
  1340. datetime open_time = StringToTime(parts[5]);
  1341. datetime close_time = StringToTime(parts[6]);
  1342. double sl = StringToDouble(parts[7]);
  1343. double tp = StringToDouble(parts[8]);
  1344. double lotS = StringToDouble(parts[9]);
  1345. double profit = StringToDouble(parts[10]);
  1346. for(int i = 0; i < MaxOrders; i++)
  1347. {
  1348. if(od_sync[i].sim_trade_ticket != -1)
  1349. {
  1350. if(od_sync[i].sim_trade_ticket == ticket && close_time > 0)
  1351. {
  1352. if(PositionSelectByTicket(od_sync[i].live_trade_ticket))
  1353. {
  1354. Print(" Virtual Trade is Closed so Remove the Live Trade As well "," Virtual Ticket = ",od_sync[i].sim_trade_ticket," Live Ticket = ",od_sync[i].live_trade_ticket);
  1355. if(trade.PositionClose(od_sync[i].live_trade_ticket))
  1356. {
  1357. Print("Position closed ", od_sync[i].live_trade_ticket);
  1358. od_sync[i].sim_trade_ticket = -1;
  1359. od_sync[i].sim_trade_ticket = -1;
  1360. }
  1361. else
  1362. {
  1363. Print("Cannot close order: ",GetLastError());
  1364. }
  1365. }
  1366. }
  1367. }
  1368. }
  1369. }
  1370. FileClose(handle);
  1371. GlobalVariableSet(global,0);
  1372. }
  1373. }
  1374. //+------------------------------------------------------------------+
  1375. //| |
  1376. //+------------------------------------------------------------------+
  1377. void deleteObjects()
  1378. {
  1379. int total = ObjectsTotal(0);
  1380. for(int i = total - 1; i >= 0; i--)
  1381. {
  1382. string name = ObjectName(0, i);
  1383. if(StringFind(name, "VBUY_OPEN_") >= 0 || StringFind(name, "VBUY_CLOSE_") >= 0 || StringFind(name, "Ticket ") >= 0)
  1384. {
  1385. ObjectDelete(0, name);
  1386. }
  1387. }
  1388. }
  1389. //+------------------------------------------------------------------+
  1390. //| Create Bottom Right Labels |
  1391. //+------------------------------------------------------------------+
  1392. void CreateInfoLabels(double balance,
  1393. int magic,
  1394. int maPeriod,
  1395. bool useMA,
  1396. bool drawdownReached)
  1397. {
  1398. int corner = CORNER_RIGHT_LOWER;
  1399. int xOffset = 200;
  1400. int yStart = 120; // IMPORTANT
  1401. int yStep = 18;
  1402. ObjectsDeleteAll(0,-1,-1);
  1403. if(CopyTallyTrade)
  1404. {
  1405. string names[5] =
  1406. {
  1407. "lbl_balance",
  1408. "lbl_magic",
  1409. "lbl_ma",
  1410. "lbl_use_ma",
  1411. "lbl_drawdown"
  1412. };
  1413. string texts[5];
  1414. texts[0] = "Balance = " + DoubleToString(balance, 2);
  1415. texts[1] = "Magic # = " + IntegerToString(magic);
  1416. texts[2] = "Moving Average = " + IntegerToString(maPeriod);
  1417. texts[3] = "Use Moving Average = " + (useMA ? "TRUE" : "FALSE");
  1418. texts[4] = "Drawdown Reached = " + (drawdownReached ? "YES" : "NO");
  1419. for(int i = 0; i < 5; i++)
  1420. {
  1421. if(ObjectFind(0, names[i]) == -1)
  1422. {
  1423. ObjectCreate(0, names[i], OBJ_LABEL, 0, 0, 0);
  1424. ObjectSetInteger(0, names[i], OBJPROP_CORNER, corner);
  1425. ObjectSetInteger(0, names[i], OBJPROP_XDISTANCE, xOffset);
  1426. ObjectSetInteger(0, names[i], OBJPROP_YDISTANCE, yStart - i * yStep);
  1427. ObjectSetInteger(0, names[i], OBJPROP_FONTSIZE, 9);
  1428. ObjectSetInteger(0, names[i], OBJPROP_COLOR, clrWhite);
  1429. ObjectSetString(0, names[i], OBJPROP_FONT, "Arial");
  1430. }
  1431. ObjectSetString(0, names[i], OBJPROP_TEXT, texts[i]);
  1432. }
  1433. }
  1434. else
  1435. {
  1436. string names[4] =
  1437. {
  1438. "lbl_balance",
  1439. "lbl_ma",
  1440. "lbl_use_ma",
  1441. "lbl_drawdown"
  1442. };
  1443. string texts[4];
  1444. texts[0] = "Balance = " + DoubleToString(balance, 2);
  1445. texts[1] = "Moving Average = " + IntegerToString(maPeriod);
  1446. texts[2] = "Use Moving Average = " + (useMA ? "TRUE" : "FALSE");
  1447. texts[3] = "Drawdown Reached = " + (drawdownReached ? "YES" : "NO");
  1448. for(int i = 0; i < 4; i++)
  1449. {
  1450. if(ObjectFind(0, names[i]) == -1)
  1451. {
  1452. ObjectCreate(0, names[i], OBJ_LABEL, 0, 0, 0);
  1453. ObjectSetInteger(0, names[i], OBJPROP_CORNER, corner);
  1454. ObjectSetInteger(0, names[i], OBJPROP_XDISTANCE, 0);
  1455. ObjectSetInteger(0, names[i], OBJPROP_YDISTANCE, yStart - i * yStep);
  1456. ObjectSetInteger(0, names[i], OBJPROP_FONTSIZE, 10);
  1457. ObjectSetInteger(0, names[i], OBJPROP_COLOR, clrWhite);
  1458. ObjectSetString(0, names[i], OBJPROP_FONT, "Arial");
  1459. }
  1460. ObjectSetString(0, names[i], OBJPROP_TEXT, texts[i]);
  1461. }
  1462. }
  1463. }
  1464. //+------------------------------------------------------------------+