Ei kuvausta

line_level_ea.mq5 33KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434
  1. //+------------------------------------------------------------------+
  2. //| line_level_ea.mq5 |
  3. //| Copyright 2025, MQL Development |
  4. //| https://www.mqldevelopment.com/ |
  5. //+------------------------------------------------------------------+
  6. #property copyright "Copyright 2025, MQL Development"
  7. #property link "https://www.mqldevelopment.com/"
  8. #property version "1.00"
  9. #include <Trade\Trade.mqh>
  10. CTrade trade;
  11. enum tradeType
  12. {
  13. buyTrades, // Buy
  14. sellTrades, // Sell
  15. };
  16. input string string_0 = "<><><><><><> General SETTINGS <><><><><><>"; //__
  17. input int magic_no = 333; // Magic no
  18. input tradeType selectSide = buyTrades; // Select Side
  19. input double lot_size = 0.1; // Lot Size
  20. input double lot_multiplier = 2; // Lot Multiplier on Loss Trade
  21. input double levels_distence = 10; // Levels Distance in Dollars
  22. input double stoploss = 10; // Fixed Stop Loss in Pips
  23. input double takeprofit = 10; // Fixed Take Profit in Pips
  24. input bool countinueCycleAfterProfit = true; // Continue Trading After Profit
  25. input string time_setting = "<><><><><> Time Filter Settings <><><><><>"; //_
  26. input bool EnableTimeFilter = false; // Enable Time Filter
  27. input string startTime = "03:00"; // Start Time Session
  28. input string endTime = "09:00"; // End Time Session
  29. // Global Variables
  30. double above_level = 0, below_level = 0;
  31. static double tickCurrentBid = 0, tickCurrentAsk = 0;
  32. double tickPreviousBid = 0, tickPreviousAsk = 0;
  33. datetime startTradingTime = 0, endTradingTime = 0;
  34. string sep = ":"; // A separator as a character
  35. ushort u_sep; // The code of the separator character
  36. string result1[];
  37. datetime ea_start_time = 0;
  38. bool tradeNow = true;
  39. bool printingDisplay = true;
  40. //+------------------------------------------------------------------+
  41. //| Expert initialization function |
  42. //+------------------------------------------------------------------+
  43. int OnInit()
  44. {
  45. //---
  46. // Fill Values above and below levels
  47. trade.SetExpertMagicNumber(magic_no);
  48. trade.SetDeviationInPoints(10);
  49. trade.SetTypeFilling(ORDER_FILLING_IOC);
  50. trade.LogLevel(LOG_LEVEL_ALL);
  51. trade.SetAsyncMode(false);
  52. ea_start_time = TimeCurrent();
  53. double currentPrice = iClose(Symbol(), PERIOD_CURRENT, 0);
  54. getNearestLevels(currentPrice, levels_distence, below_level, above_level);
  55. //---
  56. return(INIT_SUCCEEDED);
  57. }
  58. //+------------------------------------------------------------------+
  59. //| Expert deinitialization function |
  60. //+------------------------------------------------------------------+
  61. void OnDeinit(const int reason)
  62. {
  63. //---
  64. }
  65. //+------------------------------------------------------------------+
  66. //| Expert tick function |
  67. //+------------------------------------------------------------------+
  68. void OnTick()
  69. {
  70. //---
  71. double Ask = SymbolInfoDouble(Symbol(),SYMBOL_ASK);
  72. double Bid = SymbolInfoDouble(Symbol(),SYMBOL_BID);
  73. tickPreviousBid = tickCurrentBid;
  74. tickCurrentBid = Bid;
  75. tickPreviousAsk = tickCurrentAsk;
  76. tickCurrentAsk = Ask;
  77. timeConversion();
  78. // Comment(" Below Value is: ", below_level, " Above Value: ", above_level, " Previous Tick: ", tickPreviousAsk, " Tick Current Ask: ", tickCurrentAsk);
  79. double lastLot = 0;
  80. if(!countinueCycleAfterProfit)
  81. if(selectLatestTicket(lastLot) > 0)
  82. {
  83. tradeNow = false;
  84. }
  85. // Comment(" Trades Count: ", orderCount(), " Latest Ticket: ", lastTicket, " Below Value is: ", below_level, " Above Value: ", above_level);
  86. if(orderCount() == 0)
  87. {
  88. double latestClosePrice = getClosePriceByTicket();
  89. if(latestClosePrice > 0)
  90. {
  91. getNearestLevels(latestClosePrice, levels_distence, below_level, above_level);
  92. if(printingDisplay)
  93. {
  94. Print(" ---------------------------------- Resetting Level no trade open. Setting new Levels using last ticket close price: ", latestClosePrice, " ------------------------------------------------ ");
  95. Print(" Current Price: ", latestClosePrice, " Below Value is: ", below_level, " Above Value: ", above_level);
  96. printingDisplay = false;
  97. }
  98. }
  99. }
  100. if(tradeNow)
  101. if((EnableTimeFilter && TimeCurrent() >= startTradingTime && TimeCurrent() < endTradingTime) || !EnableTimeFilter)
  102. {
  103. if(above_level == 0 && below_level == 0)
  104. {
  105. double currentPrice = iClose(Symbol(), PERIOD_CURRENT, 0);
  106. getNearestLevels(currentPrice, levels_distence, below_level, above_level);
  107. Print(" Price Levels Updated on New Session Start. ");
  108. }
  109. if(selectSide == buyTrades) // Buy trade case
  110. {
  111. if(((tickPreviousAsk < above_level) && (tickCurrentAsk >= above_level)) ||
  112. ((tickPreviousAsk > below_level) && (tickCurrentAsk <= below_level)))
  113. {
  114. placeBuyTrade();
  115. Print(" ----------------------------- Buy Trade Executed and Levels Updated -----------------------------------------------------");
  116. double currentPrice = 0;
  117. if((tickPreviousAsk < above_level) && (tickCurrentAsk >= above_level))
  118. {
  119. currentPrice = above_level;
  120. }
  121. else
  122. if(((tickPreviousAsk > below_level) && (tickCurrentAsk <= below_level)))
  123. {
  124. currentPrice = below_level;
  125. }
  126. getNearestLevels(currentPrice, levels_distence, below_level, above_level);
  127. Print(" Current Price: ", currentPrice, " Below Value is: ", below_level, " Above Value: ", above_level);
  128. }
  129. }
  130. if(selectSide == sellTrades)
  131. {
  132. if(((tickPreviousBid < above_level) && (tickCurrentBid >= above_level)) ||
  133. ((tickPreviousBid > below_level) && (tickCurrentBid <= below_level)))
  134. {
  135. placeSellTrade();
  136. Print(" ----------------------------- Sell Trade Executed and Levels Updated -----------------------------------------------------");
  137. double currentPrice = 0;
  138. if((tickPreviousBid < above_level) && (tickCurrentBid >= above_level))
  139. {
  140. currentPrice = above_level;
  141. }
  142. else
  143. if(((tickPreviousBid > below_level) && (tickCurrentBid <= below_level)))
  144. {
  145. currentPrice = below_level;
  146. }
  147. getNearestLevels(currentPrice, levels_distence, below_level, above_level);
  148. Print(" Current Price: ", currentPrice, " Below Value: ", below_level, " Above Value: ", above_level);
  149. }
  150. }
  151. }
  152. else
  153. {
  154. below_level = 0;
  155. above_level = 0;
  156. }
  157. }
  158. //+------------------------------------------------------------------+
  159. //| |
  160. //+------------------------------------------------------------------+
  161. double calculateBaseLevel(double price, double step)
  162. {
  163. return step * MathFloor(price / step);
  164. }
  165. //+------------------------------------------------------------------+
  166. //| |
  167. //+------------------------------------------------------------------+
  168. void getNearestLevels(double currentPrice, double step,
  169. double &LowerLevel, double &UpperLevel)
  170. {
  171. double epsilon = 0.000001;
  172. // Compute the anchor as the nearest multiple of step.
  173. double anchor = MathRound(currentPrice / step) * step;
  174. double diff = fabs(currentPrice - anchor);
  175. // If currentPrice exactly equals the anchor, use symmetric levels.
  176. if(diff < epsilon)
  177. {
  178. LowerLevel = anchor - step;
  179. UpperLevel = anchor + step;
  180. return;
  181. }
  182. // Special handling for step == 10: use non–symmetric levels.
  183. if(step == 10)
  184. {
  185. if(currentPrice > anchor)
  186. {
  187. LowerLevel = anchor;
  188. UpperLevel = anchor + step;
  189. }
  190. else // currentPrice < anchor
  191. {
  192. LowerLevel = anchor - step;
  193. UpperLevel = anchor;
  194. }
  195. return;
  196. }
  197. // For all other steps, use the ratio threshold logic.
  198. double ratio = diff / step;
  199. double threshold = 0.45; // Adjusted threshold
  200. if(currentPrice > anchor)
  201. {
  202. if(ratio > threshold)
  203. {
  204. LowerLevel = anchor - step;
  205. UpperLevel = anchor + step;
  206. }
  207. else
  208. {
  209. LowerLevel = anchor;
  210. UpperLevel = anchor + step;
  211. }
  212. }
  213. else // currentPrice < anchor
  214. {
  215. if(ratio > threshold)
  216. {
  217. LowerLevel = anchor - step;
  218. UpperLevel = anchor + step;
  219. }
  220. else
  221. {
  222. LowerLevel = anchor - step;
  223. UpperLevel = anchor;
  224. }
  225. }
  226. }
  227. //+------------------------------------------------------------------+
  228. //| |
  229. //+------------------------------------------------------------------+
  230. void placeBuyTrade()
  231. {
  232. double buySL = 0, buyTp=0;
  233. //openPrice = SymbolInfoDouble(Symbol(),SYMBOL_ASK);
  234. double Ask = SymbolInfoDouble(Symbol(),SYMBOL_ASK);
  235. double Bid = SymbolInfoDouble(Symbol(),SYMBOL_BID);
  236. if(stoploss != 0)
  237. {
  238. buySL = Ask - (stoploss * 10 * Point());
  239. }
  240. if(takeprofit != 0)
  241. {
  242. buyTp = Ask + (takeprofit * 10 * Point());
  243. }
  244. double lot = 0;
  245. double lastLot = 0;
  246. if(selectLatestTicket(lastLot) < 0)
  247. {
  248. lot = lastLot * lot_multiplier;
  249. }
  250. else
  251. {
  252. lot = lot_size;
  253. }
  254. if(trade.PositionOpen(Symbol(),ORDER_TYPE_BUY,NormalizeDouble(lot, 2),Ask,buySL,buyTp,"Buy Trade Placed"))
  255. {
  256. Print("Buy Trade Placed: ", trade.ResultOrder());
  257. printingDisplay = true;
  258. }
  259. else
  260. {
  261. Print("Error in placing Buy: "+Symbol()+" ",GetLastError());
  262. }
  263. }
  264. //+------------------------------------------------------------------+
  265. //| |
  266. //+------------------------------------------------------------------+
  267. void placeSellTrade()
  268. {
  269. double sellSL = 0, sellTp = 0;
  270. //openPrice = SymbolInfoDouble(Symbol(),SYMBOL_BID);
  271. double Ask = SymbolInfoDouble(Symbol(),SYMBOL_ASK);
  272. double Bid = SymbolInfoDouble(Symbol(),SYMBOL_BID);
  273. if(stoploss != 0)
  274. {
  275. sellSL = Bid + (stoploss * 10 * Point());
  276. }
  277. if(takeprofit != 0)
  278. {
  279. sellTp = Bid - (takeprofit * 10 * Point());
  280. }
  281. double lot = 0;
  282. double lastLot = 0;
  283. if(selectLatestTicket(lastLot) < 0)
  284. {
  285. lot = lastLot * lot_multiplier;
  286. }
  287. else
  288. {
  289. lot = lot_size;
  290. }
  291. if(trade.PositionOpen(Symbol(),ORDER_TYPE_SELL,NormalizeDouble(lot, 2),Bid,sellSL,sellTp,"Sell Trade Placed"))
  292. {
  293. Print("Sell Trade PLaced: ", trade.ResultOrder());
  294. printingDisplay = true;
  295. }
  296. else
  297. {
  298. Print("Error in placing Sell: "+Symbol()+" ",GetLastError());
  299. }
  300. }
  301. //+------------------------------------------------------------------+
  302. //| |
  303. //+------------------------------------------------------------------+
  304. void timeConversion()
  305. {
  306. MqlDateTime date, date1;
  307. TimeToStruct(iTime(Symbol(),PERIOD_CURRENT,0),date);
  308. u_sep=StringGetCharacter(sep,0);
  309. StringSplit(startTime,u_sep,result1);
  310. date.hour = (int)StringToInteger(result1[0]);
  311. date.min = (int)StringToInteger(result1[1]);
  312. startTradingTime = StructToTime(date);
  313. TimeToStruct(iTime(Symbol(),PERIOD_CURRENT,0),date1);
  314. StringSplit(endTime,u_sep,result1);
  315. date.hour = (int)StringToInteger(result1[0]);
  316. date.min = (int)StringToInteger(result1[1]);
  317. endTradingTime = StructToTime(date);
  318. }
  319. //+------------------------------------------------------------------+
  320. //| |
  321. //+------------------------------------------------------------------+
  322. double selectLatestTicket(double &lastOrderLot)
  323. {
  324. int count = 0;
  325. ulong ticket_deal_Out=0, ticket_deal_In = 0;
  326. datetime latestCloseTime = 0;
  327. double orderProfit = 0;
  328. ulong latestTicket = 0;
  329. if(HistorySelect(ea_start_time, TimeCurrent()))
  330. {
  331. int total = HistoryDealsTotal();
  332. for(int i = total-1; i >= 0 ; i--)
  333. {
  334. ticket_deal_Out = HistoryDealGetTicket(i);
  335. if((HistoryDealGetInteger(ticket_deal_Out,DEAL_MAGIC) == magic_no) && HistoryDealGetInteger(ticket_deal_Out,DEAL_ENTRY) == DEAL_ENTRY_OUT
  336. && HistoryDealGetString(ticket_deal_Out,DEAL_SYMBOL) == Symbol()) // here is the problem solved after break
  337. {
  338. datetime orderCloseTime = (datetime) HistoryDealGetInteger(ticket_deal_Out, DEAL_TIME);
  339. if(orderCloseTime > latestCloseTime)
  340. {
  341. latestCloseTime = (datetime) HistoryDealGetInteger(ticket_deal_Out, DEAL_TIME);
  342. orderProfit = HistoryDealGetDouble(ticket_deal_Out, DEAL_PROFIT);
  343. latestTicket = ticket_deal_Out;
  344. lastOrderLot = HistoryDealGetDouble(ticket_deal_Out, DEAL_VOLUME);
  345. // Print(" Last order Lot: ", lastOrderLot);
  346. }
  347. }
  348. }
  349. }
  350. // Print(" Latest Selected Ticket: ", latestTicket, " Order Close Time: ", latestCloseTime, " Ticket Profit: ", orderProfit);
  351. return orderProfit;
  352. }
  353. //+------------------------------------------------------------------+
  354. //| |
  355. //+------------------------------------------------------------------+
  356. double getClosePriceByTicket()
  357. {
  358. ulong ticket_deal_Out=0, ticket_deal_In = 0;
  359. datetime latestCloseTime = 0;
  360. double orderClosePrice = 0;
  361. ulong latestTicket = 0;
  362. if(HistorySelect(ea_start_time, TimeCurrent()))
  363. {
  364. int total = HistoryDealsTotal();
  365. for(int i = total-1; i >= 0 ; i--)
  366. {
  367. ticket_deal_Out = HistoryDealGetTicket(i);
  368. if((HistoryDealGetInteger(ticket_deal_Out,DEAL_MAGIC) == magic_no) && HistoryDealGetInteger(ticket_deal_Out,DEAL_ENTRY) == DEAL_ENTRY_OUT
  369. && HistoryDealGetString(ticket_deal_Out,DEAL_SYMBOL) == Symbol()) // here is the problem solved after break
  370. {
  371. datetime orderCloseTime = (datetime) HistoryDealGetInteger(ticket_deal_Out, DEAL_TIME);
  372. if(orderCloseTime > latestCloseTime)
  373. {
  374. orderClosePrice = HistoryDealGetDouble(ticket_deal_Out, DEAL_PRICE);
  375. }
  376. }
  377. }
  378. }
  379. return orderClosePrice;
  380. }
  381. //+------------------------------------------------------------------+
  382. //| |
  383. //+------------------------------------------------------------------+
  384. int orderCount()
  385. {
  386. int count = 0;
  387. for(int i= PositionsTotal()-1; i>=0; i--)
  388. {
  389. ulong ticket = PositionGetTicket(i);
  390. if(PositionSelectByTicket(ticket))
  391. {
  392. if(PositionGetInteger(POSITION_MAGIC) == magic_no && PositionGetString(POSITION_SYMBOL) == Symbol())
  393. {
  394. // if(PositionGetInteger(POSITION_TYPE) == type)
  395. {
  396. count++;
  397. }
  398. }
  399. }
  400. }
  401. return count;
  402. }
  403. //+------------------------------------------------------------------+
  404. //| |
  405. //+------------------------------------------------------------------+
  406. //+------------------------------------------------------------------+