本文整理汇总了C#中Resolution.ToTimeSpan方法的典型用法代码示例。如果您正苦于以下问题:C# Resolution.ToTimeSpan方法的具体用法?C# Resolution.ToTimeSpan怎么用?C# Resolution.ToTimeSpan使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类Resolution
的用法示例。
在下文中一共展示了Resolution.ToTimeSpan方法的8个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: Get
/// <summary>
/// Get historical data enumerable for a single symbol, type and resolution given this start and end time (in UTC).
/// </summary>
/// <param name="symbol">Symbol for the data we're looking for.</param>
/// <param name="resolution">Resolution of the data request</param>
/// <param name="startUtc">Start time of the data in UTC</param>
/// <param name="endUtc">End time of the data in UTC</param>
/// <returns>Enumerable of base data for this symbol</returns>
public IEnumerable<BaseData> Get(Symbol symbol, Resolution resolution, DateTime startUtc, DateTime endUtc)
{
if (resolution != Resolution.Minute && resolution != Resolution.Hour)
throw new NotSupportedException("Resolution not available: " + resolution);
if (symbol.ID.SecurityType != SecurityType.Equity)
throw new NotSupportedException("SecurityType not available: " + symbol.ID.SecurityType);
if (endUtc < startUtc)
throw new ArgumentException("The end date must be greater or equal than the start date.");
var numberOfDays = (int)(endUtc - startUtc).TotalDays;
var resolutionSeconds = (int)resolution.ToTimeSpan().TotalSeconds;
var endUnixTime = ToUnixTime(endUtc);
// Create the Google formatted URL.
var url = string.Format(UrlPrototype, symbol.Value, resolutionSeconds, numberOfDays, endUnixTime);
// Download the data from Google.
string[] lines;
using (var client = new WebClient())
{
var data = client.DownloadString(url);
lines = data.Split('\n');
}
// First 7 lines are headers
var currentLine = 7;
while (currentLine < lines.Length - 1)
{
var firstPass = true;
// Each day google starts date time at 930am and then
// has 390 minutes over the day. Look for the starter rows "a".
var columns = lines[currentLine].Split(',');
var startTime = FromUnixTime(columns[0].Remove(0, 1).ToInt64());
while (currentLine < lines.Length - 1)
{
var str = lines[currentLine].Split(',');
if (str.Length < 6)
throw new InvalidDataException("Short record: " + str);
// If its the start of a new day, break out of this sub-loop.
var titleRow = str[0][0] == 'a';
if (titleRow && !firstPass)
break;
firstPass = false;
// Build the current datetime, from the row offset
var time = startTime.AddSeconds(resolutionSeconds * (titleRow ? 0 : str[0].ToInt64()));
// Bar: d0, c1, h2, l3, o4, v5
var open = str[4].ToDecimal();
var high = str[2].ToDecimal();
var low = str[3].ToDecimal();
var close = str[1].ToDecimal();
var volume = str[5].ToInt64();
currentLine++;
yield return new TradeBar(time, symbol, open, high, low, close, volume, resolution.ToTimeSpan());
}
}
}
示例2: CreateSubscription
private Subscription CreateSubscription(IResultHandler resultHandler, Security security, DateTime start, DateTime end, Resolution fillForwardResolution, bool userDefined)
{
var config = security.SubscriptionDataConfig;
var tradeableDates = Time.EachTradeableDay(security, start.Date, end.Date);
// ReSharper disable once PossibleMultipleEnumeration
if (!tradeableDates.Any())
{
if (userDefined)
{
_algorithm.Error(string.Format("No data loaded for {0} because there were no tradeable dates for this security.", security.Symbol));
}
return null;
}
// ReSharper disable once PossibleMultipleEnumeration
IEnumerator<BaseData> enumerator = new SubscriptionDataReader(config, security, start, end, resultHandler, tradeableDates, false);
// optionally apply fill forward logic, but never for tick data
if (config.FillDataForward && config.Resolution != Resolution.Tick)
{
enumerator = new FillForwardEnumerator(enumerator, security.Exchange, fillForwardResolution.ToTimeSpan(),
security.IsExtendedMarketHours, end, config.Resolution.ToTimeSpan());
}
// finally apply exchange/user filters
enumerator = SubscriptionFilterEnumerator.WrapForDataFeed(resultHandler, enumerator, security, end);
var subscription = new Subscription(security, enumerator, start, end, userDefined, false);
return subscription;
}
示例3: Get
/// <summary>
/// Get historical data enumerable for a single symbol, type and resolution given this start and end time (in UTC).
/// </summary>
/// <param name="symbol">Symbol for the data we're looking for.</param>
/// <param name="resolution">Resolution of the data request</param>
/// <param name="startUtc">Start time of the data in UTC</param>
/// <param name="endUtc">End time of the data in UTC</param>
/// <returns>Enumerable of base data for this symbol</returns>
public IEnumerable<BaseData> Get(Symbol symbol, Resolution resolution, DateTime startUtc, DateTime endUtc)
{
if (!_instruments.ContainsKey(symbol.Value))
throw new ArgumentException("Invalid symbol requested: " + symbol.Value);
if (symbol.ID.SecurityType != SecurityType.Forex && symbol.ID.SecurityType != SecurityType.Cfd)
throw new NotSupportedException("SecurityType not available: " + symbol.ID.SecurityType);
if (endUtc < startUtc)
throw new ArgumentException("The end date must be greater or equal to the start date.");
// set the starting date
DateTime date = startUtc;
// loop until last date
while (date <= endUtc)
{
// request all ticks for a specific date
var ticks = DownloadTicks(symbol, date);
switch (resolution)
{
case Resolution.Tick:
foreach (var tick in ticks)
{
yield return new Tick(tick.Time, symbol, tick.BidPrice, tick.AskPrice);
}
break;
case Resolution.Second:
case Resolution.Minute:
case Resolution.Hour:
case Resolution.Daily:
foreach (var bar in AggregateTicks(symbol, ticks, resolution.ToTimeSpan()))
{
yield return bar;
}
break;
}
date = date.AddDays(1);
}
}
示例4: Get
//.........这里部分代码省略.........
// create local login properties
var loginProperties = new FXCMLoginProperties(_userName, _password, _terminal, _server);
// log in
_gateway.login(loginProperties);
// initialize session
RequestTradingSessionStatus();
Console.WriteLine("Downloading data from {0} to {1}...", startUtc.ToShortDateString(), endUtc.ToShortDateString());
// download bars
var totalBars = new List<TradeBar>();
// calculate the maximum time span for one request (using 10-second bars)
const int maxBarsPerRequest = 300;
var timeSpanPerRequest = TimeSpan.FromSeconds(maxBarsPerRequest * 10);
var start = startUtc;
var end = startUtc + timeSpanPerRequest;
// request loop
while (start < endUtc.AddDays(1))
{
_currentBars.Clear();
var mdr = new MarketDataRequest();
mdr.setSubscriptionRequestType(SubscriptionRequestTypeFactory.SNAPSHOT);
mdr.setResponseFormat(IFixMsgTypeDefs.__Fields.MSGTYPE_FXCMRESPONSE);
mdr.setFXCMTimingInterval(FXCMTimingIntervalFactory.SEC10);
mdr.setMDEntryTypeSet(MarketDataRequest.MDENTRYTYPESET_ALL);
mdr.setFXCMStartDate(new UTCDate(ToJavaDateUtc(start)));
mdr.setFXCMStartTime(new UTCTimeOnly(ToJavaDateUtc(start)));
mdr.setFXCMEndDate(new UTCDate(ToJavaDateUtc(end)));
mdr.setFXCMEndTime(new UTCTimeOnly(ToJavaDateUtc(end)));
mdr.addRelatedSymbol(_fxcmInstruments[_symbolMapper.GetBrokerageSymbol(symbol)]);
AutoResetEvent autoResetEvent;
lock (_locker)
{
_currentRequest = _gateway.sendMessage(mdr);
autoResetEvent = new AutoResetEvent(false);
_mapRequestsToAutoResetEvents[_currentRequest] = autoResetEvent;
}
if (!autoResetEvent.WaitOne(1000))
{
// no response, continue loop
start = end.AddSeconds(10);
// if saturday, fast-forward to sunday
if (start.DayOfWeek == DayOfWeek.Saturday) start = start.AddDays(1);
end = start + timeSpanPerRequest;
continue;
}
var lastBarTime = _currentBars[_currentBars.Count - 1].Time;
if (lastBarTime < start)
{
// no more data available, exit loop
break;
}
// add bars received
totalBars.AddRange(_currentBars.Where(x => x.Time.Date <= endUtc.Date));
// calculate time span for next request
start = lastBarTime.AddSeconds(10);
end = start + timeSpanPerRequest;
if (start >= DateTime.UtcNow)
{
// data in the future not available, exit loop
break;
}
}
Console.WriteLine("Logging out...");
// log out
_gateway.logout();
// remove the message listeners
_gateway.removeGenericMessageListener(this);
_gateway.removeStatusMessageListener(this);
switch (resolution)
{
case Resolution.Second:
foreach (var bar in totalBars)
yield return bar;
break;
case Resolution.Minute:
case Resolution.Hour:
case Resolution.Daily:
foreach (var bar in AggregateBars(symbol, totalBars, resolution.ToTimeSpan()))
yield return bar;
break;
}
}
示例5: GetDaily
private IEnumerable<BaseData> GetDaily(Symbol symbol, Resolution resolution, DateTime startUtc, DateTime endUtc)
{
var startdate = ((ConvertMonths)startUtc.Month).ToString()
+ @"+" + startUtc.Day.ToString()
+ @"%2C+" + startUtc.Year.ToString();
var enddate = ((ConvertMonths)endUtc.Month).ToString()
+ @"+" + endUtc.Day.ToString()
+ @"%2C+" + endUtc.Year.ToString();
// Create the Google formatted URL.
var url = string.Format(UrlPrototypeDaily, symbol.Value, startdate, enddate);
// Download the data from Google.
string[] lines;
using (var client = new WebClient())
{
var data = client.DownloadString(url);
lines = data.Split('\n');
}
// first line is header
var currentLine = 1;
while (currentLine < lines.Length - 1)
{
// Format: Date,Open,High,Low,Close,Volume
var columns = lines[currentLine].Split(',');
// date format: DD-Mon-YY, e.g. 27-Sep-16
var DMY = columns[0].Split('-');
// date = 20160927
var day = DMY[0].ToInt32();
var month = (int)Enum.Parse(typeof(ConvertMonths), DMY[1]);
var year = (DMY[2].ToInt32() > 70) ? 1900 + DMY[2].ToInt32() : 2000 + DMY[2].ToInt32();
var time = new DateTime(year, month, day, 0, 0, 0);
// occasionally, the columns will have a '-' instead of a proper value
List<Decimal?> ohlc = new List<Decimal?>()
{
columns[1] != "-" ? (Decimal?)columns[1].ToDecimal() : null,
columns[2] != "-" ? (Decimal?)columns[2].ToDecimal() : null,
columns[3] != "-" ? (Decimal?)columns[3].ToDecimal() : null,
columns[4] != "-" ? (Decimal?)columns[4].ToDecimal() : null
};
if (ohlc.Where(val => val == null).Count() > 0)
{
// let's try hard to fix any issues as good as we can
// this code assumes that there is at least 1 good value
if (ohlc[1] == null) ohlc[1] = ohlc.Where(val => val != null).Max();
if (ohlc[2] == null) ohlc[2] = ohlc.Where(val => val != null).Min();
if (ohlc[0] == null) ohlc[0] = ohlc.Where(val => val != null).Average();
if (ohlc[3] == null) ohlc[3] = ohlc.Where(val => val != null).Average();
Log.Error(string.Format("Corrupt bar on {0}: {1},{2},{3},{4}. Saved as {5},{6},{7},{8}.",
columns[0], columns[1], columns[2], columns[3], columns[4],
ohlc[0], ohlc[1], ohlc[2], ohlc[3]));
}
long volume = columns[5].ToInt64();
yield return new TradeBar(time, symbol, (Decimal)ohlc[0], (Decimal)ohlc[1], (Decimal)ohlc[2], (Decimal)ohlc[3], volume, resolution.ToTimeSpan());
currentLine++;
}
}
示例6: CreateConsolidator
private static IDataConsolidator CreateConsolidator(Resolution resolution, TickType tickType, BaseData data, bool sourceIsTick)
{
var securityType = data.Symbol.ID.SecurityType;
switch (securityType)
{
case SecurityType.Base:
case SecurityType.Equity:
case SecurityType.Cfd:
case SecurityType.Forex:
return new TickConsolidator(resolution.ToTimeSpan());
case SecurityType.Option:
if (tickType == TickType.Trade)
{
return sourceIsTick
? new TickConsolidator(resolution.ToTimeSpan())
: (IDataConsolidator) new TradeBarConsolidator(resolution.ToTimeSpan());
}
if (tickType == TickType.Quote)
{
return sourceIsTick
? new TickQuoteBarConsolidator(resolution.ToTimeSpan())
: (IDataConsolidator) new QuoteBarConsolidator(resolution.ToTimeSpan());
}
break;
}
throw new NotImplementedException("Consolidator creation is not defined for " + securityType + " " + tickType);
}
示例7: CreateSubscription
private static Subscription CreateSubscription(IResultHandler resultHandler, Security security, DateTime start, DateTime end, Resolution fillForwardResolution, bool userDefined)
{
var config = security.SubscriptionDataConfig;
var tradeableDates = Time.EachTradeableDay(security, start.Date, end.Date);
var symbolResolutionDate = userDefined ? (DateTime?)null : start;
IEnumerator<BaseData> enumerator = new SubscriptionDataReader(config, security, start, end, resultHandler, tradeableDates, false, symbolResolutionDate);
// optionally apply fill forward logic, but never for tick data
if (config.FillDataForward && config.Resolution != Resolution.Tick)
{
enumerator = new FillForwardEnumerator(enumerator, security.Exchange, fillForwardResolution.ToTimeSpan(),
security.IsExtendedMarketHours, end, config.Resolution.ToTimeSpan());
}
// finally apply exchange/user filters
enumerator = SubscriptionFilterEnumerator.WrapForDataFeed(resultHandler, enumerator, security, end);
var subscription = new Subscription(security, enumerator, start, end, userDefined, false);
return subscription;
}
示例8: Get
/// <summary>
/// Get historical data enumerable for a single symbol, type and resolution given this start and end time (in UTC).
/// </summary>
/// <param name="symbol">Symbol for the data we're looking for.</param>
/// <param name="resolution">Resolution of the data request</param>
/// <param name="startUtc">Start time of the data in UTC</param>
/// <param name="endUtc">End time of the data in UTC</param>
/// <returns>Enumerable of base data for this symbol</returns>
public IEnumerable<BaseData> Get(Symbol symbol, Resolution resolution, DateTime startUtc, DateTime endUtc)
{
if (!_symbolMapper.IsKnownLeanSymbol(symbol))
throw new ArgumentException("Invalid symbol requested: " + symbol.Value);
if (resolution == Resolution.Tick)
throw new NotSupportedException("Resolution not available: " + resolution);
if (symbol.ID.SecurityType != SecurityType.Forex && symbol.ID.SecurityType != SecurityType.Cfd)
throw new NotSupportedException("SecurityType not available: " + symbol.ID.SecurityType);
if (endUtc < startUtc)
throw new ArgumentException("The end date must be greater or equal than the start date.");
var barsTotalInPeriod = new List<Candle>();
var barsToSave = new List<Candle>();
// set the starting date/time
DateTime date = startUtc;
DateTime startDateTime = date;
// loop until last date
while (startDateTime <= endUtc.AddDays(1))
{
string start = startDateTime.ToString("yyyy-MM-ddTHH:mm:ssZ");
// request blocks of 5-second bars with a starting date/time
var oandaSymbol = _symbolMapper.GetBrokerageSymbol(symbol);
var bars = _brokerage.DownloadBars(oandaSymbol, start, OandaBrokerage.MaxBarsPerRequest, EGranularity.S5);
if (bars.Count == 0)
break;
var groupedBars = GroupBarsByDate(bars);
if (groupedBars.Count > 1)
{
// we received more than one day, so we save the completed days and continue
while (groupedBars.Count > 1)
{
var currentDate = groupedBars.Keys.First();
if (currentDate > endUtc)
break;
barsToSave.AddRange(groupedBars[currentDate]);
barsTotalInPeriod.AddRange(barsToSave);
barsToSave.Clear();
// remove the completed date
groupedBars.Remove(currentDate);
}
// update the current date
date = groupedBars.Keys.First();
if (date <= endUtc)
{
barsToSave.AddRange(groupedBars[date]);
}
}
else
{
var currentDate = groupedBars.Keys.First();
if (currentDate > endUtc)
break;
// update the current date
date = currentDate;
barsToSave.AddRange(groupedBars[date]);
}
// calculate the next request datetime (next 5-sec bar time)
startDateTime = OandaBrokerage.GetDateTimeFromString(bars[bars.Count - 1].time).AddSeconds(5);
}
if (barsToSave.Count > 0)
{
barsTotalInPeriod.AddRange(barsToSave);
}
switch (resolution)
{
case Resolution.Second:
case Resolution.Minute:
case Resolution.Hour:
case Resolution.Daily:
foreach (var bar in AggregateBars(symbol, barsTotalInPeriod, resolution.ToTimeSpan()))
{
yield return bar;
}
//.........这里部分代码省略.........