Ei kuvausta

line_level_ea.mq5 33KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426
  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. ulong lastTicket = 0;
  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 && lastTicket > 0)
  87. {
  88. double latestClosePrice = getClosePriceByTicket(lastTicket);
  89. getNearestLevels(latestClosePrice, levels_distence, below_level, above_level);
  90. Print(" ---------------------------------- Resetting Level no trade open. Setting new Levels using last ticket close price: ", latestClosePrice, " ------------------------------------------------ ");
  91. Print(" Current Price: ", latestClosePrice, " Below Value is: ", below_level, " Above Value: ", above_level);
  92. lastTicket = 0;
  93. }
  94. if(tradeNow)
  95. if((EnableTimeFilter && TimeCurrent() >= startTradingTime && TimeCurrent() < endTradingTime) || !EnableTimeFilter)
  96. {
  97. if(above_level == 0 && below_level == 0)
  98. {
  99. double currentPrice = iClose(Symbol(), PERIOD_CURRENT, 0);
  100. getNearestLevels(currentPrice, levels_distence, below_level, above_level);
  101. Print(" Price Levels Updated on New Session Start. ");
  102. }
  103. if(selectSide == buyTrades) // Buy trade case
  104. {
  105. if(((tickPreviousAsk < above_level) && (tickCurrentAsk >= above_level)) ||
  106. ((tickPreviousAsk > below_level) && (tickCurrentAsk <= below_level)))
  107. {
  108. placeBuyTrade();
  109. Print(" ----------------------------- Buy Trade Executed and Levels Updated -----------------------------------------------------");
  110. double currentPrice = 0;
  111. if((tickPreviousAsk < above_level) && (tickCurrentAsk >= above_level))
  112. {
  113. currentPrice = above_level;
  114. }
  115. else
  116. if(((tickPreviousAsk > below_level) && (tickCurrentAsk <= below_level)))
  117. {
  118. currentPrice = below_level;
  119. }
  120. getNearestLevels(currentPrice, levels_distence, below_level, above_level);
  121. Print(" Current Price: ", currentPrice, " Below Value is: ", below_level, " Above Value: ", above_level);
  122. }
  123. }
  124. if(selectSide == sellTrades)
  125. {
  126. if(((tickPreviousBid < above_level) && (tickCurrentBid >= above_level)) ||
  127. ((tickPreviousBid > below_level) && (tickCurrentBid <= below_level)))
  128. {
  129. placeSellTrade();
  130. Print(" ----------------------------- Sell Trade Executed and Levels Updated -----------------------------------------------------");
  131. double currentPrice = 0;
  132. if((tickPreviousBid < above_level) && (tickCurrentBid >= above_level))
  133. {
  134. currentPrice = above_level;
  135. }
  136. else
  137. if(((tickPreviousBid > below_level) && (tickCurrentBid <= below_level)))
  138. {
  139. currentPrice = below_level;
  140. }
  141. getNearestLevels(currentPrice, levels_distence, below_level, above_level);
  142. Print(" Current Price: ", currentPrice, " Below Value: ", below_level, " Above Value: ", above_level);
  143. }
  144. }
  145. }
  146. else
  147. {
  148. below_level = 0;
  149. above_level = 0;
  150. }
  151. }
  152. //+------------------------------------------------------------------+
  153. //| |
  154. //+------------------------------------------------------------------+
  155. double calculateBaseLevel(double price, double step)
  156. {
  157. return step * MathFloor(price / step);
  158. }
  159. //+------------------------------------------------------------------+
  160. //| |
  161. //+------------------------------------------------------------------+
  162. void getNearestLevels(double currentPrice, double step,
  163. double &LowerLevel, double &UpperLevel)
  164. {
  165. double epsilon = 0.000001;
  166. // Compute the anchor as the nearest multiple of step.
  167. double anchor = MathRound(currentPrice / step) * step;
  168. double diff = fabs(currentPrice - anchor);
  169. // If currentPrice exactly equals the anchor, use symmetric levels.
  170. if(diff < epsilon)
  171. {
  172. LowerLevel = anchor - step;
  173. UpperLevel = anchor + step;
  174. return;
  175. }
  176. // Special handling for step == 10: use non–symmetric levels.
  177. if(step == 10)
  178. {
  179. if(currentPrice > anchor)
  180. {
  181. LowerLevel = anchor;
  182. UpperLevel = anchor + step;
  183. }
  184. else // currentPrice < anchor
  185. {
  186. LowerLevel = anchor - step;
  187. UpperLevel = anchor;
  188. }
  189. return;
  190. }
  191. // For all other steps, use the ratio threshold logic.
  192. double ratio = diff / step;
  193. double threshold = 0.45; // Adjusted threshold
  194. if(currentPrice > anchor)
  195. {
  196. if(ratio > threshold)
  197. {
  198. LowerLevel = anchor - step;
  199. UpperLevel = anchor + step;
  200. }
  201. else
  202. {
  203. LowerLevel = anchor;
  204. UpperLevel = anchor + step;
  205. }
  206. }
  207. else // currentPrice < anchor
  208. {
  209. if(ratio > threshold)
  210. {
  211. LowerLevel = anchor - step;
  212. UpperLevel = anchor + step;
  213. }
  214. else
  215. {
  216. LowerLevel = anchor - step;
  217. UpperLevel = anchor;
  218. }
  219. }
  220. }
  221. //+------------------------------------------------------------------+
  222. //| |
  223. //+------------------------------------------------------------------+
  224. void placeBuyTrade()
  225. {
  226. double buySL = 0, buyTp=0;
  227. //openPrice = SymbolInfoDouble(Symbol(),SYMBOL_ASK);
  228. double Ask = SymbolInfoDouble(Symbol(),SYMBOL_ASK);
  229. double Bid = SymbolInfoDouble(Symbol(),SYMBOL_BID);
  230. if(stoploss != 0)
  231. {
  232. buySL = Ask - (stoploss * 10 * Point());
  233. }
  234. if(takeprofit != 0)
  235. {
  236. buyTp = Ask + (takeprofit * 10 * Point());
  237. }
  238. double lot = 0;
  239. double lastLot = 0;
  240. if(selectLatestTicket(lastLot) < 0)
  241. {
  242. lot = lastLot * lot_multiplier;
  243. }
  244. else
  245. {
  246. lot = lot_size;
  247. }
  248. if(trade.PositionOpen(Symbol(),ORDER_TYPE_BUY,NormalizeDouble(lot, 2),Ask,buySL,buyTp,"Buy Trade Placed"))
  249. {
  250. Print("Buy Trade Placed: ", trade.ResultOrder());
  251. lastTicket = trade.ResultOrder();
  252. }
  253. else
  254. {
  255. Print("Error in placing Buy: "+Symbol()+" ",GetLastError());
  256. }
  257. }
  258. //+------------------------------------------------------------------+
  259. //| |
  260. //+------------------------------------------------------------------+
  261. void placeSellTrade()
  262. {
  263. double sellSL = 0, sellTp = 0;
  264. //openPrice = SymbolInfoDouble(Symbol(),SYMBOL_BID);
  265. double Ask = SymbolInfoDouble(Symbol(),SYMBOL_ASK);
  266. double Bid = SymbolInfoDouble(Symbol(),SYMBOL_BID);
  267. if(stoploss != 0)
  268. {
  269. sellSL = Bid + (stoploss * 10 * Point());
  270. }
  271. if(takeprofit != 0)
  272. {
  273. sellTp = Bid - (takeprofit * 10 * Point());
  274. }
  275. double lot = 0;
  276. double lastLot = 0;
  277. if(selectLatestTicket(lastLot) < 0)
  278. {
  279. lot = lastLot * lot_multiplier;
  280. }
  281. else
  282. {
  283. lot = lot_size;
  284. }
  285. if(trade.PositionOpen(Symbol(),ORDER_TYPE_SELL,NormalizeDouble(lot, 2),Bid,sellSL,sellTp,"Sell Trade Placed"))
  286. {
  287. Print("Sell Trade PLaced: ", trade.ResultOrder());
  288. lastTicket = trade.ResultOrder();
  289. }
  290. else
  291. {
  292. Print("Error in placing Sell: "+Symbol()+" ",GetLastError());
  293. }
  294. }
  295. //+------------------------------------------------------------------+
  296. //| |
  297. //+------------------------------------------------------------------+
  298. void timeConversion()
  299. {
  300. MqlDateTime date, date1;
  301. TimeToStruct(iTime(Symbol(),PERIOD_CURRENT,0),date);
  302. u_sep=StringGetCharacter(sep,0);
  303. StringSplit(startTime,u_sep,result1);
  304. date.hour = (int)StringToInteger(result1[0]);
  305. date.min = (int)StringToInteger(result1[1]);
  306. startTradingTime = StructToTime(date);
  307. TimeToStruct(iTime(Symbol(),PERIOD_CURRENT,0),date1);
  308. StringSplit(endTime,u_sep,result1);
  309. date.hour = (int)StringToInteger(result1[0]);
  310. date.min = (int)StringToInteger(result1[1]);
  311. endTradingTime = StructToTime(date);
  312. }
  313. //+------------------------------------------------------------------+
  314. //| |
  315. //+------------------------------------------------------------------+
  316. double selectLatestTicket(double &lastOrderLot)
  317. {
  318. int count = 0;
  319. ulong ticket_deal_Out=0, ticket_deal_In = 0;
  320. datetime latestCloseTime = 0;
  321. double orderProfit = 0;
  322. ulong latestTicket = 0;
  323. if(HistorySelect(ea_start_time, TimeCurrent()))
  324. {
  325. int total = HistoryDealsTotal();
  326. for(int i = total-1; i >= 0 ; i--)
  327. {
  328. ticket_deal_Out = HistoryDealGetTicket(i);
  329. if((HistoryDealGetInteger(ticket_deal_Out,DEAL_MAGIC) == magic_no) && HistoryDealGetInteger(ticket_deal_Out,DEAL_ENTRY) == DEAL_ENTRY_OUT
  330. && HistoryDealGetString(ticket_deal_Out,DEAL_SYMBOL) == Symbol()) // here is the problem solved after break
  331. {
  332. datetime orderCloseTime = (datetime) HistoryDealGetInteger(ticket_deal_Out, DEAL_TIME);
  333. if(orderCloseTime > latestCloseTime)
  334. {
  335. latestCloseTime = (datetime) HistoryDealGetInteger(ticket_deal_Out, DEAL_TIME);
  336. orderProfit = HistoryDealGetDouble(ticket_deal_Out, DEAL_PROFIT);
  337. latestTicket = ticket_deal_Out;
  338. lastOrderLot = HistoryDealGetDouble(ticket_deal_Out, DEAL_VOLUME);
  339. // Print(" Last order Lot: ", lastOrderLot);
  340. }
  341. }
  342. }
  343. }
  344. // Print(" Latest Selected Ticket: ", latestTicket, " Order Close Time: ", latestCloseTime, " Ticket Profit: ", orderProfit);
  345. return orderProfit;
  346. }
  347. //+------------------------------------------------------------------+
  348. //| |
  349. //+------------------------------------------------------------------+
  350. double getClosePriceByTicket(ulong ticket)
  351. {
  352. int count = 0;
  353. ulong ticket_deal_Out=0, ticket_deal_In = 0;
  354. datetime latestCloseTime = 0;
  355. double orderProfit = 0;
  356. ulong latestTicket = 0;
  357. if(HistorySelect(ea_start_time, TimeCurrent()))
  358. {
  359. int total = HistoryDealsTotal();
  360. for(int i = total-1; i >= 0 ; i--)
  361. {
  362. ticket_deal_Out = HistoryDealGetTicket(i);
  363. if((HistoryDealGetInteger(ticket_deal_Out,DEAL_POSITION_ID) == ticket) && (HistoryDealGetInteger(ticket_deal_Out,DEAL_MAGIC) == magic_no) && HistoryDealGetInteger(ticket_deal_Out,DEAL_ENTRY) == DEAL_ENTRY_OUT
  364. && HistoryDealGetString(ticket_deal_Out,DEAL_SYMBOL) == Symbol()) // here is the problem solved after break
  365. {
  366. return HistoryDealGetDouble(ticket_deal_Out, DEAL_PRICE);
  367. }
  368. }
  369. }
  370. // Print(" Latest Selected Ticket: ", latestTicket, " Order Close Time: ", latestCloseTime, " Ticket Profit: ", orderProfit);
  371. return 0;
  372. }
  373. //+------------------------------------------------------------------+
  374. //| |
  375. //+------------------------------------------------------------------+
  376. int orderCount()
  377. {
  378. int count = 0;
  379. for(int i= PositionsTotal()-1; i>=0; i--)
  380. {
  381. ulong ticket = PositionGetTicket(i);
  382. if(PositionSelectByTicket(ticket))
  383. {
  384. if(PositionGetInteger(POSITION_MAGIC) == magic_no && PositionGetString(POSITION_SYMBOL) == Symbol())
  385. {
  386. // if(PositionGetInteger(POSITION_TYPE) == type)
  387. {
  388. count++;
  389. }
  390. }
  391. }
  392. }
  393. return count;
  394. }
  395. //+------------------------------------------------------------------+
  396. //| |
  397. //+------------------------------------------------------------------+
  398. //+------------------------------------------------------------------+