我很难弄清楚哪个交易时段是特定的。
有四个可能的会话,显示在这张来自forexfactory.com的图片中
我有这个方法,我需要检查是当前时间是在指定的交易时段。

public bool IsTradingSession(TradingSession tradingSession, DateTime currentTime)
{
    //currentTime is in local time.


    //Regular session is 5PM - next day 5PM, this is the session in the picture.
    //Irregular sessions also occur for example late open (3AM - same day 5PM)  or early close (5PM - next day 11AM)
    DateTime sessionStart = Exchange.ToLocalTime(Exchange.CurrentSessionOpen);
    DateTime sessionEnd = Exchange.ToLocalTime(Exchange.CurrentSessionClose);

    if(tradingSession == TradingSession.Sydney)
        return ....... ? true : false;
    if(tradingSession == TradingSession.Tokyo)
        return ....... ? true : false;
    if(tradingSession == TradingSession.London)
        return ....... ? true : false;
    if (tradingSession == TradingSession.NewYork)
        return ....... ? true : false;

    return false;
}

使用
    bool isSydneySession = IsTradingSession(TradingSession.Sydney, CurrentTime);
    bool isTokyoSession = IsTradingSession(TradingSession.Tokyo, CurrentTime);
    bool isLondonSession = IsTradingSession(TradingSession.London, CurrentTime);
    bool isNewYorkSession = IsTradingSession(TradingSession.NewYork, CurrentTime);

谢谢你

最佳答案

我建议为每个交易会话编写一个简单的函数,该函数接受一个日期时间并返回一个bool,指示该时间是否打开。

var sydneyOpen = new TimeSpan(17, 0, 0);
var sydneyClose = new TimeSpan(2, 0, 0);
Func<DateTime, bool> isOpenInSydney = d =>
    (d.TimeOfDay > sydneyOpen || d.TimeOfDay < sydneyClose);

// same for other markets, write a function to check against two times

然后将它们放入这样的Dictionary<TradingSession, Func>中进行泛型检索…
var marketHours = new Dictionary<TradingSession, Func<DateTime, bool>>();
marketHours.Add(TradingSession.Sydney, isOpenInSydney);
// add other markets...

然后,您现有的方法只为给定的TradingSession选择适当的函数并应用它。
public bool IsTradingSession(TradingSession tradingSession, DateTime currentTime)
{
    var functionForSession = marketHours[tradingSession];
    return functionForSession(currentTime);
}

我认为只要应用程序只在一个时区运行,您就不需要这里的UTC时间,但夏令时可能会导致问题。
一个很好的方法来解释两天而不是一天的交易时段的问题,就是编写一个助手,精确地考虑它是否是“跨天”交易时段,并为您应用不同的规则:
private bool IsBetween(DateTime now, TimeSpan open, TimeSpan close)
{
    var nowTime = now.TimeOfDay;
    return (open < close
        // if open is before close, then now must be between them
        ? (nowTime > open && nowTime < close)
        // otherwise now must be *either* after open or before close
        : (nowTime > open || nowTime < close));
}

然后
var sydneyOpen = new TimeSpan(17, 0, 0);
var sydneyClose = new TimeSpan(2, 0, 0);
Func<DateTime, bool> isOpenInSydney = d => IsBetween(d, sydneyOpen, sydneyClose);

09-04 17:45
查看更多