Ingen beskrivning

Pulse EA v1.mq5 129KB

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