/// <summary> /// Read bar stream into bar series starting from the start of stream and ending by given the date. /// </summary> /// <param name="barSeries">The bar series</param> /// <param name="to">the end date.</param> /// <returns></returns> public bool ReadTo(BarSeries barSeries, DateTime to) { if (barSeries == null) { throw new ArgumentNullException("barSeries"); } if (to == default(DateTime)) { throw new ArgumentException("to"); } var readCount = 0; using (var reader = CreateReader()) { ReadHeader(reader); if (to < _fileHeader.BeginTime) { return(false); } long endOffset; Bar endBar = null; if (to >= _fileHeader.EndTime) { endOffset = reader.BaseStream.Length - 1; } else { long endDayOffset; int endCount; _fileHeader.NaturalDayIndices.GetEndOffset(to, out endDayOffset, out endCount); endBar = ReadEndBarOffset(reader, to, endDayOffset, endCount, out endOffset); if (endOffset < 0) { return(false); } } reader.BaseStream.Position = _fileHeader.FileHeaderSize; while (reader.BaseStream.Position <= endOffset) { readCount++; barSeries.Add(ReadBar(reader)); } if (endBar != null) { readCount++; barSeries.Add(endBar); } } return(readCount > 0); }
/// <summary> /// Read bar stream into bar series starting by given date. /// </summary> /// <param name="barSeries">The bar series.</param> /// <param name="from">The start date.</param> /// <returns></returns> public bool ReadFrom(BarSeries barSeries, DateTime from) { if (barSeries == null) { throw new ArgumentNullException("barSeries"); } if (from == default(DateTime)) { throw new ArgumentException("from"); } var readCount = 0; using (var reader = CreateReader()) { ReadHeader(reader); if (from > _fileHeader.EndTime) { return(false); } if (from > _fileHeader.BeginTime) { long startDayOffset; int startCount; _fileHeader.NaturalDayIndices.GetStartOffset(from, out startDayOffset, out startCount); long startOffset; var startBar = ReadStartBarOffset(reader, from, startDayOffset, startCount, out startOffset); if (startOffset < 0) { return(false); } if (startBar != null) { readCount++; barSeries.Add(startBar); } reader.BaseStream.Position = startOffset; } while (reader.BaseStream.Position < reader.BaseStream.Length) { readCount++; barSeries.Add(ReadBar(reader)); } } return(readCount > 0); }
/// <summary> /// 把 count 个 Bar 合并成一个新的 Bar /// </summary> /// <param name="series"></param> /// <param name="inst"></param> /// <param name="count"></param> /// <returns></returns> public static BarSeries MergeCompress(this BarSeries series, Instrument inst, long count) { if (series.Count == 0 || count < 2) { return(new BarSeries()); } var selector = new TimeRangeSelector(inst); bool emitOnClose = !(series[0].Size >= QuantBoxConst.DayBarSize); var bars = new BarSeries(); Bar last = null; var index = 0; foreach (var bar in series) { var range = selector.Get(bar.DateTime.Date); if (index == 0) { last = bar; last.Size *= count; } else { QBHelper.MergeBar(last, bar); } ++index; if (index == count || (emitOnClose && bar.CloseDateTime.TimeOfDay == range.CloseTime)) { bars.Add(last); last = null; index = 0; } } return(bars); }
/* * 按照股指的时间要求,时间划分是这样的 * 9:15 * 9:45 * 10:15 * 10:45 * 11:15-11:30 13:00-13:15 两个15分钟被午休隔开了 * 13:45 * 14:15 * 14:45 * 15:15 交割日时只到15:00,已经到最后一天了,少15分钟也没什么 */ public override void OnBar(Bar bar) { //只处理15分钟的 if (900 == bar.Size) { if (bars == null) { bars = new BarSeries(); } bars.Add(bar); //在处理11:15-11:30 13:00-13:15这两个15分钟时会合并成一个 if (bars.Count == 2) // 2 * 15min = 30 min { // get OHLC values for 30min bar double open = bars[0].Open; double high = bars.HighestHigh(); double low = bars.LowestLow(); double close = bars[1].Close; long volume = bars[0].Volume + bars[1].Volume; // todo something Bar b = new Bar(bars[0].DateTime, open, high, low, close, volume, 900 * 2); bars30min.Add(b); Console.WriteLine(b); // reset 15min bar series bars = null; } } }
private BarSeries GenerateSeries() { BarSeries barSeries = new BarSeries("Symbol", "Symbol"); Random random = new Random(); double num1 = 500.0; long num2 = 100000L; DateTime dateTime = new DateTime(2007, 1, 18); for (int index = 0; index < 100; ++index) { num1 = num1 + (double)random.Next(11) - 5.0; double num3 = num1 - 6.0 - (double)random.Next(6); double num4 = num1 - (double)random.Next(6); double num5 = num4 - (double)random.Next(6); if (random.Next(2) == 1) { double num6 = num4; num4 = num5; num5 = num6; } barSeries.Add(new Bar(dateTime, num4, num1, num3, num5, num2 + num2 / 10L * (long)random.Next(10), 86400L)); dateTime = dateTime.AddDays(1.0); if (dateTime.DayOfWeek == DayOfWeek.Saturday) { dateTime = dateTime.AddDays(2.0); } } return(barSeries); }
protected void readLastNMin5s(Instrument inst, int n) { //获取分线 List <Bar> min5Bars = new List <Bar>(); int i = 0; string lastTimeString = this.timeWhenDeal.ToString("yyyy-MM-dd HH:mm:ss"); do { min5Bars = this.provider.GetLastNBars(inst.Symbol, 300, n, lastTimeString); i++; Thread.Sleep(50); }while(min5Bars.Count == 0 && i <= 5); if (min5Bars.Count > 0) { BarSeries barSeries = this.getMin5Series(inst); foreach (Bar bar in min5Bars) { barSeries.Add(bar); } } else { Console.WriteLine("尝试多次({0})获取{1}的最新5分线失败", i, inst.Symbol); } }
private static BarSeries DownloadBars(DataManager manager, Instrument inst, long barSize, DateTime dateTime1, DateTime dateTime2) { var bars = new BarSeries(); var request = new HistoricalDataRequest() { RequestId = Guid.NewGuid().ToString("N"), DataType = DataObjectType.Bar, BarSize = barSize, Instrument = inst, DateTime1 = dateTime1, DateTime2 = dateTime2 }; DownloadDataRequest(manager.GetFramework(), request, OnHistoricalData); return(bars); void OnHistoricalData(HistoricalData data) { foreach (var item in data.Objects) { switch (item.TypeId) { case DataObjectType.Bar: bars.Add((Bar)item); break; default: break; } } } }
public static BarSeries GetTimeBars(this DataManager manager, Instrument inst, long barSize, DateTime dateTime1, DateTime dateTime2) { var items = manager.GetDataSeries(inst, DataObjectType.Bar, BarType.Time, barSize); if (items == null || items.Count == 0) { return(new BarSeries()); } dateTime1 = dateTime1 <= items.DateTime1 ? DateTime.MinValue : CorrectionDateTime1(dateTime1); dateTime2 = dateTime2 >= items.DateTime2 ? DateTime.Today : CorrectionDateTime2(dateTime2); var index1 = dateTime1 == DateTime.MinValue ? 0 : items.GetIndex(dateTime1, SearchOption.Next); var index2 = dateTime2 == DateTime.Today ? items.Count - 1 : items.GetIndex(dateTime2); if (index1 < 0 || index2 < 0) { return(new BarSeries()); } var bars = new BarSeries((int)(index2 - index1 + 1)); for (long i = index1; i <= index2; i++) { bars.Add((Bar)items[i]); } return(bars); }
public void 生成(BarSeries bs) { 笔 bi = new 笔(); bars.Clear(); blist1.Clear(); for (int i = 0; i < bs.Count; i++) { if (i == 0) {/* * bi.zd = 结构.起点; * bi.o = bs[0].Close; * bi.high = 0; * bi.ba = bs[0]; * bi.low = 0; * blist1.Add(bi); * bars.Add(bs[0]);*/ } else { bars.Add(bs[i]); 包含计算(); } } }
private void ReadBars(BinaryReader reader, BarSeries barlist, DateTime from, DateTime to) { int i = 0; for (; i < _icount; ++i) { #region int year = reader.ReadInt16(); int month = reader.ReadByte(); int day = reader.ReadByte(); reader.BaseStream.Seek(CBarlen - 4, SeekOrigin.Current); DateTime dt = new DateTime(year, month, day); if (dt >= from) { reader.BaseStream.Seek(-CBarlen, SeekOrigin.Current); break; } #endregion } for (; i < _icount; ++i) { #region int year = reader.ReadInt16(); int month = reader.ReadByte(); int day = reader.ReadByte(); DateTime dt = new DateTime(year, month, day); if (dt > to) { break; } Bar bar = new Bar(); bar.BeginTime = dt; bar.EndTime = dt; bar.Open = reader.ReadInt32() / 1000.0; bar.Close = reader.ReadInt32() / 1000.0; bar.High = reader.ReadInt32() / 1000.0; bar.Low = reader.ReadInt32() / 1000.0; bar.PreClose = reader.ReadInt32() / 1000.0; bar.Volume = reader.ReadDouble(); bar.Turnover = reader.ReadDouble(); bar.OpenInterest = reader.ReadDouble(); bar.IsCompleted = true; bar.TradingDate = dt; barlist.Add(bar); #endregion } }
public BarSeries Compress(DataEntryEnumerator enumerator) { var series = new BarSeries(); NewCompressedBar += (sender, e) => series.Add(e.Bar); while (enumerator.MoveNext()) Add(enumerator.Current); this.method_1(); return series; }
public static BarSeries GetHistoricalBars(IHistoricalDataProvider provider, Instrument instrument, DateTime datetime1, DateTime datetime2, long barSize) { ArrayList arrayList = DataManager.r6ZT8iFUv(provider, instrument, DataManager.EDataSeries.Bar, datetime1, datetime2, barSize); BarSeries barSeries = new BarSeries(); foreach (Bar bar in arrayList) { barSeries.Add(bar); } return(barSeries); }
protected override void OnInit() { BarSeries barSeries = new BarSeries(DataSeriesHelper.SeriesNameToString(this.dataSeries.Name)); foreach (Bar bar in (IEnumerable)this.dataSeries) { barSeries.Add(bar); } this.chart.ApplyDefaultTemplate(); this.chart.SetMainSeries((DoubleSeries)barSeries, true); }
private void instrumentListSource_SelectedSeriesChanged(object sender, EventArgs e) { string name = ((TimeSeries)this.instrumentListSource.SelectedSeries).Name; IDataSeries dataSeries = DataManager.Server.GetDataSeries(this.seriesNames[name]); BarSeries series = new BarSeries(name); foreach (Bar bar in (IEnumerable)dataSeries) { series.Add(bar); } this.UpdateMe(series); }
public BarSeries Compress(DataEntryEnumerator enumerator) { BarSeries series = new BarSeries(); this.NewCompressedBar += (sender, args) => series.Add(args.Bar); while (enumerator.MoveNext()) { this.Add(enumerator.Current); } this.Flush(); return(series); }
public void TestCase() { Bar bar1 = new Bar(); Bar bar2 = new Bar(); bs.Add(bar1); bs.Add(bar2); Assert.AreEqual(1, bs.RealCount); Assert.AreSame(bar2, bs[0]); bs.Clear(); Assert.AreEqual(0, bs.RealCount); DateTime dt1 = new DateTime(2014, 1, 1, 12, 12, 12); Bar bar3 = new Bar(dt1, 10, 10, 10, 10, 100, 100); bs.Add(bar3); Assert.AreSame(bar3, bs[dt1]); bs.Clear(); bs.Add(bar3); Assert.AreSame(bar3, bs[dt1, EIndexOption.Next]); }
public BarSeries Compress(DataEntryEnumerator enumerator) { var series = new BarSeries(); NewCompressedBar += (sender, e) => series.Add(e.Bar); while (enumerator.MoveNext()) { Add(enumerator.Current); } this.method_1(); return(series); }
public BarSeries GetBarSeries(string series, DateTime datetime1, DateTime datetime2) { BarSeries bars = new BarSeries(); if (this.file.Series[series] != null) { foreach (Bar bar in this.file.Series[series].GetArray(datetime1, datetime2)) { bars.Add(bar); } } return(bars); }
protected void readLastNDailys(Instrument inst, int n) { //读取日线 DateTime lastDate = this.timeWhenDeal.Date; ISeriesObject[] dailyBars = Util.GetNDailysBeforeDate(inst, lastDate, n); Util.AdjustDailys(dailyBars); //向前复权 BarSeries barSeries = this.getDailySeries(inst); foreach (Daily dBar in dailyBars) { barSeries.Add(dBar); } }
public BarSeries Compress(DataEntryEnumerator enumerator) { BarSeries series = new BarSeries(); this.NewCompressedBar += delegate(object sender, CompressedBarEventArgs args) { series.Add(args.Bar); }; while (enumerator.MoveNext()) { this.Add(enumerator.Current); } this.Flush(); return series; }
public override void OnBar(Bar bar) { if (VolatilityExitEnabled) { rangeSeries.Add(bar.DateTime, bar.High - bar.Low); } // check if there are least "length" bars if (series.Count >= EntryLength && rangeSMA.Count > 0) { double highestHigh = series.HighestHigh(EntryLength); double lowestLow = series.LowestLow(EntryLength); double volatilty = 0; if (VolatilityBarrierEnabled) { volatilty = rangeSMA.Last; } highestHighSeries.Add(bar.DateTime, highestHigh); lowestLowSeries.Add(bar.DateTime, lowestLow); double channelHigh = highestHigh + barrier - volatilty; double channelLow = lowestLow - barrier + volatilty; channelHighSeries.Add(bar.DateTime, channelHigh); channelLowSeries.Add(bar.DateTime, channelLow); if (!HasPosition) { if (channelHigh <= bar.Close) { OpenPosition(OrderSide.Buy); } else if (channelLow >= bar.Close) { OpenPosition(OrderSide.Sell); } } else { SetExit(); } } series.Add(bar); }
public BarSeries Compress(DataEntryEnumerator enumerator) { enumerator.TimeRangeSelector = _timeRangeSelector; BarSeries series = new BarSeries(DataSeriesNameHelper.GetName(inst, DataObjectType.Bar, BarType.Time, newBarSize)); NewCompressedBar += delegate(object sender, CompressedBarEventArgs args) { series.Add(args.Bar); }; while (enumerator.MoveNext()) { Add(enumerator.Current); } Flush(); return(series); }
void LoadHistoricalBars(DateTime datetime) { DateTime dtEnd = datetime; DateTime dtBegin = dtEnd.AddDays(-5);//这个时间按自己的需求修改 TradeSeries ts = DataManager.GetHistoricalTrades(Instrument, dtBegin, dtEnd); //个人认为这个地方应当过滤下Trade数据,去除无效的再转换成Bars BarSeries bs = DataManager.CompressBars(ts, BarType.Time, BarSize); BarSeries barsMin = GetBars(BarType.Time, BarSize); foreach (Bar b in bs) { barsMin.Add(b); } }
public BarSeries Compress(DataEntryEnumerator enumerator) { BarSeries series = new BarSeries(); this.NewCompressedBar += delegate(object sender, CompressedBarEventArgs args) { series.Add(args.Bar); }; while (enumerator.MoveNext()) { this.Add(enumerator.Current); } this.Flush(); return(series); }
/// <summary> /// Read all bars in the stream into bar series. /// </summary> /// <param name="barSeries">The bar series.</param> /// <returns></returns> public bool ReadAll(BarSeries barSeries) { var readCount = 0; using (var reader = CreateReader()) { ReadHeader(reader); while (reader.BaseStream.Position < reader.BaseStream.Length) { readCount++; barSeries.Add(ReadBar(reader)); } } return(readCount > 0); }
protected void addTodayDaily(Instrument inst) { Trade lastTrade = this.getLastTrade(inst); if (lastTrade != null) { GMTrade gmTrade = (GMTrade)lastTrade; GMDaily daily = new GMDaily(); daily.Date = gmTrade.DateTime.Date; daily.High = gmTrade.High; daily.Open = gmTrade.Open; daily.Low = gmTrade.Low; daily.Close = gmTrade.Price; daily.Volume = (long)gmTrade.TotalSize; BarSeries barSeries = this.getDailySeries(inst); barSeries.Add(daily); } }
private void ReadBarsAgo(BinaryReader reader, BarSeries barlist, DateTime now, int len) { int i = 0; for (; i < _icount; ++i) { #region int year = reader.ReadInt16(); int month = reader.ReadByte(); int day = reader.ReadByte(); DateTime dt = new DateTime(year, month, day); if (dt > now) { break; } Bar bar = new Bar(); bar.BeginTime = dt; bar.EndTime = dt; bar.Open = reader.ReadInt32() / 1000.0; bar.Close = reader.ReadInt32() / 1000.0; bar.High = reader.ReadInt32() / 1000.0; bar.Low = reader.ReadInt32() / 1000.0; bar.PreClose = reader.ReadInt32() / 1000.0; bar.Volume = reader.ReadDouble(); bar.Turnover = reader.ReadDouble(); bar.OpenInterest = reader.ReadDouble(); bar.IsCompleted = true; bar.TradingDate = dt; barlist.Add(bar); #endregion } if (i > len) { int rmlen = i - len; barlist.RemoveRange(barlist.Count - i, rmlen); } }
/// <summary> /// 把 count 个 Bar 合并成一个新的 Bar /// </summary> /// <param name="series"></param> /// <param name="inst"></param> /// <param name="count"></param> /// <returns></returns> public static BarSeries MergeCompress(this BarSeries series, Instrument inst, long count) { if (series.Count == 0 || count < 2) { return(new BarSeries()); } var selector = new TimeRangeSelector(inst); var emitOnClose = true; var bar = series[0]; if (bar.Size >= QuantBoxConst.DayBarSize) { emitOnClose = false; } var bars = new BarSeries(); Bar last = null; var index = 0; for (int i = 0; i < series.Count; i++) { var range = selector.Get(series[i].DateTime.Date); if (index == 0) { last = series[i]; last.Size *= count; } else { QBHelper.MergeBar(last, series[i]); } ++index; if (index == count || (emitOnClose && series[i].CloseDateTime.TimeOfDay == range.CloseTime)) { bars.Add(last); last = null; index = 0; continue; } } return(bars); }
private void ModifyBars(BarSeries daybarlist, BarSeries addedBarSeries) { var lastdate = daybarlist.Last.BeginTime.Date; foreach (var bar in addedBarSeries) { var bardate = bar.BeginTime.Date; if (bardate <= lastdate) { var barindex = daybarlist.GetIndex(bardate); if (barindex != -1) { daybarlist[barindex] = bar; } } else { daybarlist.Add(bar); } } }
/// <summary> /// Read bars given the specified trading day. /// </summary> /// <param name="barSeries">The bar series.</param> /// <param name="tradingDay">trading day provided following exchange datetime spec.</param> /// <returns></returns> public bool ReadTradingDay(BarSeries barSeries, DateTime tradingDay) { if (barSeries == null) { throw new ArgumentNullException("barSeries"); } if (tradingDay == default(DateTime)) { throw new ArgumentException("tradingDay"); } var readCount = 0; tradingDay = new DateTime(tradingDay.Year, tradingDay.Month, tradingDay.Day); using (var reader = CreateReader()) { ReadHeader(reader); if (tradingDay < _fileHeader.BeginTradingDay || tradingDay > _fileHeader.EndTradingDay) { return(false); } long startOffset; int count; if (_fileHeader.TradingDayIndices.TryGet(tradingDay, out startOffset, out count)) { reader.BaseStream.Position = startOffset; while (count > 0) { barSeries.Add(ReadBar(reader)); count--; readCount++; } } return(readCount > 0); } }
public BarSeries ReadFile(Stream fs, long size, int instrumentId, SeekOrigin orgin, int offset) { BarSeries bs = new BarSeries(); if (orgin == SeekOrigin.End) { fs.Position = fs.Length - 32 * offset; } else { fs.Position = 32 * offset; } BinaryReader br = new BinaryReader(fs); for (long i = fs.Position; i < fs.Length; i += 32) { bs.Add(ReadBar(br, instrumentId, size)); } br.Close(); fs.Close(); return(bs); }
private static void EnsureDataReady() { var f = Framework.Current; var i = f.InstrumentManager.Get(symbol); if (i == null) { i = new Instrument(InstrumentType.FX, symbol, string.Empty, CurrencyId.USD); f.InstrumentManager.Add(i, true); } var filename = Path.GetFullPath(Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), "..", "..", "..", "Data", string.Format("{0}.csv", symbol))); if (File.Exists(filename)) { var name = DataSeriesNameHelper.GetName(i, BarType.Time, 60); var bs = new BarSeries(name); using (var reader = new StreamReader(filename)) { var line = reader.ReadLine(); while (line != null) { var fields = line.Split(new char[] { ',' }); var closeDateTime = DateTime.ParseExact(string.Format("{0} {1}", fields [0], fields [1]), "yyyy.MM.dd HH:mm", CultureInfo.InvariantCulture); var openDateTime = closeDateTime.Subtract(TimeSpan.FromMinutes(1)); var open = double.Parse(fields [2]); var high = double.Parse(fields [3]); var low = double.Parse(fields [4]); var close = double.Parse(fields [5]); var vol = long.Parse(fields [6]); bs.Add(new Bar(openDateTime, closeDateTime, i.Id, BarType.Time, 60, open, high, low, close, vol, 0)); line = reader.ReadLine(); } } f.DataManager.Save(bs, SaveMode.Add); } }
///<summary> /// Returns bars from within specified dates interval ///</summary> public BarSeries GetRange(DateTime dateTime1, DateTime dateTime2) { BarSeries barSeries = new BarSeries(); int index1 = this.series.GetIndex(dateTime1, EIndexOption.Next); int index2 = this.series.GetIndex(dateTime1, EIndexOption.Prev); if (index1 != -1 && index2 != -1) { for (int index3 = index1; index3 <= index2; ++index3) barSeries.Add(new Bar(this.series[index3])); } return barSeries; }
public BarSeries GetHistoricalBars(IHistoricalDataProvider provider, Instrument instrument, DateTime dateTime1, DateTime dateTime2, BarType barType, long barSize) { if (provider.IsDisconnected) provider.Connect(); DataManager.DataNotifier @class = new DataManager.DataNotifier(); string text = Guid.NewGuid().ToString(); lock (this.dictionary_0) { this.dictionary_0.Add(text, @class); } provider.Send(new HistoricalDataRequest(instrument, dateTime1, dateTime2, 6) { RequestId = text, BarType = new BarType?(barType), BarSize = new long?(barSize) }); @class.ReadyEvent.WaitOne(); lock (this.dictionary_0) { this.dictionary_0.Remove(text); } var bs = new BarSeries("", "", -1, -1); foreach (var data in @class.Data) { var objs = data.Objects; for (int i = 0; i < objs.Length; i++) bs.Add((Bar)objs[i]); } return bs; }
public BarSeries GetHistoricalBars(Instrument instrument, DateTime dateTime1, DateTime dateTime2, BarType barType, long barSize) { var ds = GetDataSeries(instrument, DataObjectType.Bar, barType, barSize); var bs = new BarSeries(); if (ds != null && ds.Count != 0) { long index1 = ds.GetIndex(dateTime1, SearchOption.Next); long index2 = ds.GetIndex(dateTime2, SearchOption.Prev); for (long i = index1; i <= index2; i++) bs.Add((Bar)ds[i]); } return bs; }