How to change chart time frame with code?

 

When an Expert Advisor is attached to a chart, the time frame is manually applied by clicking M1, M5, H1, etc. This time frame controls how often the EA receives a market tick which then runs all the code in the start() method.

How can I programmatically change the time frame from D1 to H4 to H1 to M30 to M15 to M5 to M1?

The underlying requirement is that the EA only wants to trade once a week at a particular time. As the weekday and clock time approaches, changing the time frame would allow waking up the start() method more and more often until the moment arrives.

 

If the EA is attached on let say M5, it will received exactly the same amount of ticks than the D1 chart. The start() function will execute each tick regardless the TF where the EA is attached.

However, if you want to limit some part of your code, you may use something like this:

First declare this:

datetime timeprev=0;

Then in start() function:

if(timeprev!=iTime(Symbol(),PERIOD_D1,0)) { ... YOUR CODE HERE ... timeprev = iTime(Symbol(),PERIOD_D1,0); }

Your code will be executed only once D1 bar in this example (even on a M5 chart).

Hope that helps.

FerruFx

 

Hello, actually I was looking the same.
And found this function in MQL4


ChartSetSymbolPeriod(0,Symbol(),PERIOD_M5);


above code will change current chart to M5.


Hope this help for those who search the same things

ChartSetSymbolPeriod - Chart Operations - MQL4 Reference
ChartSetSymbolPeriod - Chart Operations - MQL4 Reference
ChartSetSymbolPeriod - Chart Operations - MQL4 Reference
  • docs.mql4.com
ChartSetSymbolPeriod - Chart Operations - MQL4 Reference
Reason: