1 October 2021

This snippet is of a code that will close all trades at the end of the day. The percise time can be modified to your preferations.

Source code viewer
  1. #include <Trade\PositionInfo.mqh>
  2. #include <Trade\Trade.mqh>
  3. CPositionInfo position;
  4. CTrade trade;
  5.  
  6. input bool CloseTradesDayEnd = true; // Close all trades at the end of the day
  7. input int CloseTradesDayEndTime = 2357; // GMT Time for close all trades at the end of the day (hmm)
  8.  
  9. datetime gmtTimeCurrent;
  10.  
  11. // OnTick() function content:
  12.  
  13. // TimeGMT
  14. gmtTimeCurrent = TimeGMT();
  15. MqlDateTime gmtTimeCurrentStruct;
  16. TimeToStruct(gmtTimeCurrent, gmtTimeCurrentStruct);
  17. int hoursAndMinutes = (gmtTimeCurrentStruct.hour * 100) + gmtTimeCurrentStruct.min;
  18.  
  19. // Close trades at the end of the day.
  20. uint PositionsCount = PositionsTotal();
  21. if(CloseTradesDayEnd && PositionsCount > 0 && hoursAndMinutes == CloseTradesDayEndTime)
  22. {
  23. for(int i = PositionsCount - 1; i >= 0; i--)
  24. {
  25. if(position.SelectByIndex(i))
  26. {
  27. if(position.Symbol() == Symbol())
  28. {
  29. trade.PositionClose(position.Ticket());
  30. }
  31. }
  32. }
  33. }
Programming Language: MQL5