I am creating an application which tells me how much time left for forex market to open or close.
For instance, if New York market just got close, now I want to know how much time is left for New York market to open again. And some goes for its closing time when it is open.
I can use timer to decrement the remaining time but the problem is I can't get an absolute subtracted remaining time value. Not even with TimeSpan.Subtract or DateTime.Subtract.
EDIT: I am using this code to tell me market is open
if ((IsTimeOfDayBetween(DateTime.UtcNow, new TimeSpan(8, 0, 0), new TimeSpan(16, 0, 0))) == true)
{
textBox1.Background = new SolidColorBrush(Colors.Green);
}
But after it has closed, I want remaining time left for it to open again, display in a text block.
You can try something like this, using the function "IsTimeOfDayBetween" you already have:
// global variables
TimeSpan dayStart = new TimeSpan(0, 0, 0);
TimeSpan dayEnds = new TimeSpan(23, 59, 59);
// you have a timer(loop) every sencond, so you can have this two variables change depending on what market you are tracking, in this example NY
TimeSpan NyOpens = new TimeSpan(8, 0, 0);
TimeSpan NyClose = new TimeSpan(16, 0, 0);
// variable to store the result
TimeSpan tillOpenClose;
if ((IsTimeOfDayBetween(DateTime.UtcNow, NyOpens, NyClose)) == true)
{
textBox1.Background = new SolidColorBrush(Colors.Green);
// its open, you want time till close
// validate close time is greater than open time
if ( NyClose.CompareTo(NyOpens) > 0)
tillOpenClose = NyClose.Subtract(DateTime.UtcNow.TimeOfDay);
else
tillOpenClose = ((dayEnds.Subtract(DateTime.UtcNow.AddSeconds(-1).TimeOfDay)).Add(NyClose)); // if the market closes at and earlier time, then the time till close, is the remaing time of this day, plus the time till close of the new day
}
else if ((IsTimeOfDayBetween(DateTime.UtcNow, dayStart, NyOpens)) == true) // if time is between start of day and open time
tillOpenClose = NyOpens.Subtract(DateTime.UtcNow.TimeOfDay);
else // it is between closetime and end of day
tillOpenClose = ((dayEnds.Subtract(DateTime.UtcNow.AddSeconds(-1).TimeOfDay)).Add(NyOpens)); // part remaining for this day plus new day, the extra second is to compensate the "dayEnds"
Console.WriteLine(tillOpenClose.ToString(@"hh\:mm\:ss"));
And the "IsTimeOfDayBetween" function should be something like this:
if (open.CompareTo(close) > 0) // if open time is greater (e.g. open: (20,0,0) close: (4,0,0))
{
if (timeNow.TimeOfDay.CompareTo(open) >= 0 || timeNow.TimeOfDay.CompareTo(close) <= 0)
return true;
}
else
{
if (timeNow.TimeOfDay.CompareTo(open) >= 0 && timeNow.TimeOfDay.CompareTo(close) <= 0)
return true;
}
return false;
EDIT: Changed the time till close, sorry about that
EDIT2: Adjusted for closing times earlier than open time