Нема описа

Pulse EA.mq5 124KB

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