Skip to content

Instantly share code, notes, and snippets.

@mastercs999
Created January 16, 2018 16:54
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mastercs999/f093bf8dae3df448425730ad8183cfe6 to your computer and use it in GitHub Desktop.
Save mastercs999/f093bf8dae3df448425730ad8183cfe6 to your computer and use it in GitHub Desktop.
Trading hours parsing
using TimeZoneConverter; // https://www.nuget.org/packages/TimeZoneConverter/
public void contractDetails(int reqId, ContractDetails contractDetails)
{
// Parse trading hours
List<DateRange> tradingHours = new List<DateRange>();
if (contractDetails.LiquidHours != null)
foreach (string dateStr in contractDetails.LiquidHours.Split(new char[] { ';' }, StringSplitOptions.RemoveEmptyEntries))
{
// Skip if it is closed this date
if (dateStr.Substring(9) == "CLOSED")
continue;
// Check length
if (dateStr.Length != 18)
throw new Exception("Unknown liquid hours datetime format.");
// Parse, example: 20170515:0930-1600
int year = int.Parse(dateStr.Substring(0, 4));
int month = int.Parse(dateStr.Substring(4, 2));
int day = int.Parse(dateStr.Substring(6, 2));
int hourFrom = int.Parse(dateStr.Substring(9, 2));
int minutesFrom = int.Parse(dateStr.Substring(11, 2));
int hourTo = int.Parse(dateStr.Substring(14, 2));
int minutesTo = int.Parse(dateStr.Substring(16, 2));
// Is it today?
DateTime from = new DateTime(year, month, day, hourFrom, minutesFrom, 0);
DateTime to = new DateTime(year, month, day, hourTo, minutesTo, 0);
// Convert to UTC
TimeZoneInfo sourceTimeZone = TimeZoneInfo.FindSystemTimeZoneById(TZConvert.IanaToWindows(contractDetails.TimeZoneId));
from = TimeZoneInfo.ConvertTimeToUtc(from, sourceTimeZone);
to = TimeZoneInfo.ConvertTimeToUtc(to, sourceTimeZone);
// Save
tradingHours.Add(new DateRange()
{
From = from,
To = to
});
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment