Possibly market_close_hour is wrong: your DAX contract runs from 6 UTC until 20, meaning the last bar of the day on (e.g.) hourly chart is the 19h bar. Returned value of iBarShift (quoting documentation): If there is no bar for the specified time (history "gap"), the function will return -1 or the nearest bar index (depending on exact parameter).
However, I have no clue why you get wrong values once and then correct values when you run the same script again. Did you run it on different timeframes?
Not compiled or tested
datetime previous_midnight; datetime today_midnight=TimeCurrent()-(TimeCurrent()%(PERIOD_D1*60)); int day_number=TimeDayOfWeek(today_midnight); if(day_number>1) previous_midnight=today_midnight-(PERIOD_D1*60); else previous_midnight=today_midnight-(PERIOD_D1*60*(day_number+2)); startbar1 = iBarShift(NULL, 0,(previous_midnight+market_open_hour*60*60+market_open_min*60)); endbar1 = iBarShift(NULL, 0,(previous_midnight+(market_close_hour*60*60+market_close_min*60))); high_pre_day = High[iHighest(NULL, 0, MODE_HIGH, startbar1 - endbar1 + 1, endbar1)]; low_pre_day = Low[iLowest(NULL, 0, MODE_LOW, startbar1 - endbar1 + 1, endbar1)];
It is most likely that you are getting the incorrect result because D1 data is updating the first time that you run the script. The 2nd time, D1 has updated.
The above suggestion uses the data from the current chart, so avoids this issue.
I have written it so that Sunday candles will be ignored. If you want to include Sunday, then it will need to be modified slightly.

- Free trading apps
- Over 8,000 signals for copying
- Economic news for exploring financial markets
You agree to website policy and terms of use
Hello,
i want to calculate the high and low of the previous day between 6.00 in the morning and 20.00 in the evening. I wrote a script to do that.
But when i´m running the script for the 1st time, the alert shows the low of preday by 11434. That´s a false result. When i run the same script 2 minutes later, i get the correct result of low preday 11517. I don´t understand this. Is something wrong with my code?
Here is the code:
Thanks a lot
Michael